<commit_before>// Karma configuration
// Generated on Tue Jul 18 2017 18:01:48 GMT+0800 (CST)

const path = require('path')
const webpack = require('webpack')
const coverage = String(process.env.COVERAGE) !== 'false'
const ci = String(process.env.CI).match(/^(1|true)$/gi)
const realBrowser = String(process.env.BROWSER).match(/^(1|true)$/gi)
const sauceLabs = realBrowser && ci
const sauceLabsLaunchers = {
  sl_win_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'Windows 10'
  },
  sl_mac_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'macOS 10.12'
  },
  sl_firefox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'Windows 10'
  },
  sl_mac_firfox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'macOS 10.12'
  },
  sl_safari: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'macOS 10.12'
  },
  sl_edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10'
  },
  sl_ie_11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '11.103',
    platform: 'Windows 10'
  },
  sl_ie_10: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '10.0',
    platform: 'Windows 7'
  },
  sl_ie_9: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '9.0',
    platform: 'Windows 7'
  }
}

const travisLaunchers = {
  chrome_travis: {
    base: 'Chrome',
    flags: ['--no-sandbox']
  }
}

const localBrowsers = realBrowser ? Object.keys(travisLaunchers) : ['Chrome']

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['source-map-support', 'mocha', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
      './node_modules/es5-polyfill/dist/polyfill.js',
      'test/spec.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'].concat(
      coverage ? 'coverage-istanbul' : [],
      sauceLabs ? 'saucelabs' : []
    ),

    coverageIstanbulReporter: {
      dir: './coverage',
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true,
      skipFilesWithNoCoverage: true,
      'report-config': {
        html: {
          subdir: 'html'
        },
        'text-summary': {
          subdir: 'text-summary'
        },
        lcovonly: {
          subdir: '.',
          file: 'lcov.info'
        }
      }
    },

    mochaReporter: {
      showDiff: true
    },

    browserLogOptions: { terminal: true },
    browserConsoleLogOptions: { terminal: true },

    browserNoActivityTimeout: 5 * 60 * 1000,
    browserDisconnectTimeout: 15 * 1000,
    browserDisconnectTolerance: 2,

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: sauceLabs ? Object.keys(sauceLabsLaunchers) : localBrowsers,

    customLaunchers: sauceLabs ? sauceLabsLaunchers : travisLaunchers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: 2,

    webpack: {
      // devtool: 'inline-source-map',
      resolve: {
        extensions: ['.js', '.ts']
      },
      module: {
        rules: [
          {
            enforce: 'pre',
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
          },
          {
            test: /\.ts$/,
            loader: 'ts-loader',
            options: {
              produceSourceMap: coverage,
              transpileOnly: true,
              compilerOptions: {
                target: 'es5',
                module: 'commonjs'
              }
            }
          },
          coverage ? {
            enforce: 'post',
            test: /\.ts$/,
            use: {
              loader: 'istanbul-instrumenter-loader',
              options: { esModules: true }
            },
            include: path.resolve('src/'),
            exclude: /node_modules/
          } : {}
        ]
      },
      plugins: [
        new webpack.DefinePlugin({
          coverage: coverage,
          NODE_ENV: JSON.stringify(process.env.NODE_ENV || ''),
          DISABLE_FLAKEY: !!String(process.env.FLAKEY).match(/^(0|false)$/gi)
        })
      ]
    },

    webpackMiddleware: {
      noInfo: true
    }
  })
}
<commit_msg>fix: karma config<commit_after>// Karma configuration
// Generated on Tue Jul 18 2017 18:01:48 GMT+0800 (CST)

const path = require('path')
const webpack = require('webpack')
const coverage = String(process.env.COVERAGE) !== 'false'
const ci = String(process.env.CI).match(/^(1|true)$/gi)
const realBrowser = String(process.env.BROWSER).match(/^(1|true)$/gi)
const sauceLabs = realBrowser && ci
const sauceLabsLaunchers = {
  sl_win_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'Windows 10'
  },
  sl_mac_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'macOS 10.12'
  },
  sl_firefox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'Windows 10'
  },
  sl_mac_firfox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'macOS 10.12'
  },
  sl_safari: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'macOS 10.12'
  },
  sl_edge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10'
  },
  sl_ie_11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '11.103',
    platform: 'Windows 10'
  },
  sl_ie_10: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '10.0',
    platform: 'Windows 7'
  },
  sl_ie_9: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '9.0',
    platform: 'Windows 7'
  }
}

const travisLaunchers = {
  chrome_travis: {
    base: 'Chrome',
    flags: ['--no-sandbox']
  }
}

const localBrowsers = realBrowser ? Object.keys(travisLaunchers) : ['Chrome']

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['source-map-support', 'mocha', 'sinon-chai'],

    // list of files / patterns to load in the browser
    files: [
      './node_modules/es5-polyfill/dist/polyfill.js',
      'test/spec.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'].concat(
      coverage ? 'coverage-istanbul' : [],
      sauceLabs ? 'saucelabs' : []
    ),

    coverageIstanbulReporter: {
      dir: './coverage',
      reports: ['html', 'lcovonly', 'text-summary'],
      fixWebpackSourcePaths: true,
      skipFilesWithNoCoverage: true,
      'report-config': {
        html: {
          subdir: 'html'
        },
        'text-summary': {
          subdir: 'text-summary'
        },
        lcovonly: {
          subdir: '.',
          file: 'lcov.info'
        }
      }
    },

    mochaReporter: {
      showDiff: true
    },

    browserLogOptions: { terminal: true },
    browserConsoleLogOptions: { terminal: true },

    browserNoActivityTimeout: 5 * 60 * 1000,
    browserDisconnectTimeout: 15 * 1000,
    browserDisconnectTolerance: 2,

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: sauceLabs ? Object.keys(sauceLabsLaunchers) : localBrowsers,

    customLaunchers: sauceLabs ? sauceLabsLaunchers : travisLaunchers,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: 2,

    webpack: {
      // devtool: 'inline-source-map',
      resolve: {
        extensions: ['.js', '.ts']
      },
      module: {
        rules: [
          {
            enforce: 'pre',
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
          },
          {
            test: /\.ts$/,
            loader: 'ts-loader',
            options: {
              transpileOnly: true,
              compilerOptions: {
                target: 'es5',
                module: 'commonjs'
              }
            }
          },
          coverage ? {
            enforce: 'post',
            test: /\.ts$/,
            use: {
              loader: 'istanbul-instrumenter-loader',
              options: { esModules: true }
            },
            include: path.resolve('src/'),
            exclude: /node_modules/
          } : {}
        ]
      },
      plugins: [
        new webpack.DefinePlugin({
          coverage: coverage,
          NODE_ENV: JSON.stringify(process.env.NODE_ENV || ''),
          DISABLE_FLAKEY: !!String(process.env.FLAKEY).match(/^(0|false)$/gi)
        })
      ]
    },

    webpackMiddleware: {
      noInfo: true
    }
  })
}
<|endoftext|>


<commit_before>/**
 * @file test for util methods
 * @author nighca<nighca@live.cn>
 */

var path = require('path');
var util = require('../../lib/util');
var packageInfo = require('../../package.json');

describe('app', function () {
    var app = util.app;

    describe('root', function () {
        it('should be a string', function () {
            expect(typeof app.root).toBe('string');
        });

        it('should be the dir path where package.json locates', function () {
            expect(require(path.join(app.root, 'package.json'))).toBe(packageInfo);
        });
    });
});

describe('nodeType', function () {
    var nodeType = util.nodeType;

    it('should be a type map', function () {
        expect(typeof nodeType).toBe('object');
    });
});

describe('isElement', function () {
    var isElement = util.isElement;

    it('should return true if passed an element node', function () {
        expect(isElement({
            type: 'tag'
        })).toBe(true);
        expect(isElement({
            type: 'script'
        })).toBe(true);
        expect(isElement({
            type: 'style'
        })).toBe(true);
    });

    it('should return false if passed an none-element node', function () {
        expect(isElement({
            type: 'comment'
        })).toBe(false);
        expect(isElement({
            type: 'text'
        })).toBe(false);
        expect(isElement({
            type: 'doctype'
        })).toBe(false);
    });
});

describe('extend', function () {
    var extend = util.extend;

    describe('extend object', function () {
        var result = extend(
            {
                a: 1,
                b: 1
            },
            {
                b: 2,
                c: 3
            }
        );

        it('should return right result', function () {
            expect(result.a).toBe(1);
            expect(result.b).toBe(2);
            expect(result.c).toBe(3);
        });
    });
});

describe('cachable', function () {
    var cachable = util.cachable;

    describe('valueOf', function () {
        var count = 0;
        var valueOf = cachable(function (key) {
            count++;
            return key;
        });

        it('should return right result', function () {
            expect(valueOf('1')).toBe('1');
            expect(valueOf('2')).toBe('2');
        });

        it('should cache result', function () {
            expect(valueOf('1')).toBe('1');
            expect(count).toBe(2);
        });

        it('should run getter again if refresh required', function () {
            expect(valueOf('1', true)).toBe('1');
            expect(count).toBe(3);
        });

        it('should clean cached data while method clear called', function () {
            valueOf.clear();
            expect(valueOf('1')).toBe('1');
            expect(valueOf('2')).toBe('2');
            expect(count).toBe(5);
        });
    });
});

describe('getHomePath', function () {
    var getHomePath = util.getHomePath;

    it('should return a path', function () {
        expect(typeof getHomePath()).toBe('string');
    });
});
<commit_msg>test for extendAttribute<commit_after>/**
 * @file test for util methods
 * @author nighca<nighca@live.cn>
 */

var path = require('path');
var util = require('../../lib/util');
var packageInfo = require('../../package.json');

describe('app', function () {
    var app = util.app;

    describe('root', function () {
        it('should be a string', function () {
            expect(typeof app.root).toBe('string');
        });

        it('should be the dir path where package.json locates', function () {
            expect(require(path.join(app.root, 'package.json'))).toBe(packageInfo);
        });
    });
});

describe('nodeType', function () {
    var nodeType = util.nodeType;

    it('should be a type map', function () {
        expect(typeof nodeType).toBe('object');
    });
});

describe('isElement', function () {
    var isElement = util.isElement;

    it('should return true if passed an element node', function () {
        expect(isElement({
            type: 'tag'
        })).toBe(true);
        expect(isElement({
            type: 'script'
        })).toBe(true);
        expect(isElement({
            type: 'style'
        })).toBe(true);
    });

    it('should return false if passed an none-element node', function () {
        expect(isElement({
            type: 'comment'
        })).toBe(false);
        expect(isElement({
            type: 'text'
        })).toBe(false);
        expect(isElement({
            type: 'doctype'
        })).toBe(false);
    });
});

describe('extend', function () {
    var extend = util.extend;

    describe('extend object', function () {
        var result = extend(
            {
                a: 1,
                b: 1
            },
            {
                b: 2,
                c: 3
            }
        );

        it('should return right result', function () {
            expect(result.a).toBe(1);
            expect(result.b).toBe(2);
            expect(result.c).toBe(3);
        });
    });
});

describe('extendAttribute', function () {
    var extendAttribute = util.extendAttribute;

    describe('extend attributes', function () {
        var result = extendAttribute(
            {
                a: 1,
                b: 1
            },
            {
                b: {
                    get: function () {
                        return 2;
                    }
                },
                c: {
                    get: function () {
                        return this.b + 1;
                    },
                    set: function (c) {
                        this.a = c - 2;
                    }
                }
            }
        );

        it('should return right result', function () {
            expect(result.a).toBe(1);
            expect(result.b).toBe(2);
            expect(result.c).toBe(3);

            result.c = 4;
            expect(result.a).toBe(2);
        });
    });
});

describe('cachable', function () {
    var cachable = util.cachable;

    describe('valueOf', function () {
        var count = 0;
        var valueOf = cachable(function (key) {
            count++;
            return key;
        });

        it('should return right result', function () {
            expect(valueOf('1')).toBe('1');
            expect(valueOf('2')).toBe('2');
        });

        it('should cache result', function () {
            expect(valueOf('1')).toBe('1');
            expect(count).toBe(2);
        });

        it('should run getter again if refresh required', function () {
            expect(valueOf('1', true)).toBe('1');
            expect(count).toBe(3);
        });

        it('should clean cached data while method clear called', function () {
            valueOf.clear();
            expect(valueOf('1')).toBe('1');
            expect(valueOf('2')).toBe('2');
            expect(count).toBe(5);
        });
    });
});

describe('getHomePath', function () {
    var getHomePath = util.getHomePath;

    it('should return a path', function () {
        expect(typeof getHomePath()).toBe('string');
    });
});
<|endoftext|>


<commit_before>'use strict';
/**
 * Provider config
 */
var dbox = require("dbox");
var path = require('path');
var CancelError = require('anyfetch-provider').CancelError;

var config = require('../config/configuration.js');
var retrieveFiles = require('./helpers/retrieve.js').delta;
var uploadFile = require('./helpers/upload.js');

var dbApp = dbox.app({
  "app_key": config.dropboxId,
  "app_secret": config.dropboxSecret,
});

var redirectToService = function(callbackUrl, cb) {
  dbApp.requesttoken(function(status, requestToken) {
    if(status !== 200) {
      console.log("Dropbox error:", status, requestToken);
      return cb(new Error("Dropbox returned with non 200 status"));
    }

    var url = requestToken.authorize_url + "&oauth_callback=" + callbackUrl;

    cb(null, url, requestToken);
  });
};

var retrieveTokens = function(reqParams, storedParams, cb) {
  if(reqParams.not_approved) {
    return cb(new CancelError());
  }

  dbApp.accesstoken(storedParams, function(status, dropboxAccessToken) {
    if(status !== 200) {
      return cb(new Error("Bad Dropbox status: " + status));
    }

    dbApp.client(dropboxAccessToken).account(function(status, reply) {
      if(status !== 200) {
        return cb(new Error("Bad Dropbox status: " + status));
      }

      cb(null, (reply.email) ? reply.email : 'unknown', dropboxAccessToken);
    });
  });
};

var updateAccount = function(serviceData, cursor, queues, cb) {
  // Retrieve all files since last call
  retrieveFiles(serviceData, cursor, function(err, entries, newCursor) {
    if(err) {
      return cb(err);
    }

    entries.forEach(function(entry) {
      if(!entry[1]) {
        queues.deletion.push({title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
      }
      else {
        queues.addition.push({title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
      }
    });

    cb(null, newCursor);
  });
};

var additionQueueWorker = function(job, cb) {
  uploadFile(job.task, job.anyfetchClient, job.serviceData, job.cache, job, cb);
};

var deletionQueueWorker = function(job, cb) {
  var identifier = 'https://dropbox.com/' + job.serviceData.uid + job.task.path;

  console.log("DELETING", identifier);
  job.anyfetchClient.deleteDocumentByIdentifier(identifier, cb);
};

additionQueueWorker.concurrency = config.maxConcurrency;
deletionQueueWorker.concurrency = config.maxConcurrency;

module.exports = {
  connectFunctions: {
    redirectToService: redirectToService,
    retrieveTokens: retrieveTokens
  },
  updateAccount: updateAccount,
  workers: {
    addition: additionQueueWorker,
    deletion: deletionQueueWorker
  },

  config: config
};
<commit_msg>reverse documents<commit_after>'use strict';
/**
 * Provider config
 */
var dbox = require("dbox");
var path = require('path');
var CancelError = require('anyfetch-provider').CancelError;

var config = require('../config/configuration.js');
var retrieveFiles = require('./helpers/retrieve.js').delta;
var uploadFile = require('./helpers/upload.js');

var dbApp = dbox.app({
  "app_key": config.dropboxId,
  "app_secret": config.dropboxSecret,
});

var redirectToService = function(callbackUrl, cb) {
  dbApp.requesttoken(function(status, requestToken) {
    if(status !== 200) {
      console.log("Dropbox error:", status, requestToken);
      return cb(new Error("Dropbox returned with non 200 status"));
    }

    var url = requestToken.authorize_url + "&oauth_callback=" + callbackUrl;

    cb(null, url, requestToken);
  });
};

var retrieveTokens = function(reqParams, storedParams, cb) {
  if(reqParams.not_approved) {
    return cb(new CancelError());
  }

  dbApp.accesstoken(storedParams, function(status, dropboxAccessToken) {
    if(status !== 200) {
      return cb(new Error("Bad Dropbox status: " + status));
    }

    dbApp.client(dropboxAccessToken).account(function(status, reply) {
      if(status !== 200) {
        return cb(new Error("Bad Dropbox status: " + status));
      }

      cb(null, (reply.email) ? reply.email : 'unknown', dropboxAccessToken);
    });
  });
};

var updateAccount = function(serviceData, cursor, queues, cb) {
  // Retrieve all files since last call
  retrieveFiles(serviceData, cursor, function(err, entries, newCursor) {
    if(err) {
      return cb(err);
    }
    entries.reverse().forEach(function(entry) {
      if(!entry[1]) {
        queues.deletion.push({title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
      }
      else {
        queues.addition.push({title: path.basename(entry[0]), path: entry[0], metadata: entry[1]});
      }
    });

    cb(null, newCursor);
  });
};

var additionQueueWorker = function(job, cb) {
  uploadFile(job.task, job.anyfetchClient, job.serviceData, job.cache, job, cb);
};

var deletionQueueWorker = function(job, cb) {
  var identifier = 'https://dropbox.com/' + job.serviceData.uid + job.task.path;

  console.log("DELETING", identifier);
  job.anyfetchClient.deleteDocumentByIdentifier(identifier, cb);
};

additionQueueWorker.concurrency = config.maxConcurrency;
deletionQueueWorker.concurrency = config.maxConcurrency;

module.exports = {
  connectFunctions: {
    redirectToService: redirectToService,
    retrieveTokens: retrieveTokens
  },
  updateAccount: updateAccount,
  workers: {
    addition: additionQueueWorker,
    deletion: deletionQueueWorker
  },

  config: config
};
<|endoftext|>


<commit_before>
/*global assert:true*/ // chai
/*
  To ensure correct, isolated, unit test behavior,
  everything except the file being tested should be mocked or stubbed out.
*/
define(['models/element'],
function (ElementModel /* change this to whatever you want */) {
  'use strict';

  var noop = function () {};

  suite('models/element.js', function () {
    suite('#setExternalErrors()', function () {
      var model1
        , model2
        , model3
        , model4;

      setup(function () {
        ElementModel.prototype.initialize = noop;

        model1 = new ElementModel({ name: 'model1', id: 'model1' });
        model2 = new ElementModel({ name: 'model2', id: 'model2' });
        model3 = new ElementModel({ name: 'model3', id: 'model3' });
        model4 = new ElementModel({ name: 'model4', id: 'model4' });

        model1.validationError = { value: [{code: 'EMAIL'}] };
        model2.validationError = { value: [{code: 'MAX'}, {code: 'REQUIRED'}] };
        model3.validationError = null;
        model4.validationError = { value: [{code: 'EMAIL'}] };
      });

      teardown(function () {
        model1 = null;
        model2 = null;
        model3 = null;
        model4 = null;
      });

      test('should keep the current errors', function () {
        model1.setExternalErrors([{code: 'blah1'}], {merge: true});
        assert.equal(model1.validationError.value.length, 2);
        assert.equal(model1.validationError.value[0].code, 'blah1');
        assert.equal(model1.validationError.value[1].code, 'EMAIL');

        model2.setExternalErrors([{code: 'blah2'}, {code: 'blah3'}, {code: 'blah4'}], {merge: true});
        assert.equal(model2.validationError.value.length, 5);
        assert.equal(model2.validationError.value[0].code, 'blah4');
        assert.equal(model2.validationError.value[1].code, 'blah3');
        assert.equal(model2.validationError.value[2].code, 'blah2');
        assert.equal(model2.validationError.value[3].code, 'REQUIRED');
        assert.equal(model2.validationError.value[4].code, 'MAX');

        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}], {merge: true});
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });

      test('should not keep the current field errors', function () {
        model1.setExternalErrors([{code: 'blah1'}], {merge: false});
        assert.equal(model1.validationError.value.length, 1);
        assert.equal(model1.validationError.value[0].code, 'blah1');
      });

      test('should default to keeping the current field errors', function () {
        model1.setExternalErrors([{code: 'blah1'}]);
        assert.equal(model1.validationError.value.length, 2);
        assert.equal(model1.validationError.value[0].code, 'blah1');
      });

      test('should handle an empty error list when merging', function () {
        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}], {merge: true});
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });

      test('should handle an empty error list when not merging', function () {
        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}], {merge: false});
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });

      test('should handle an empty error list when not merging and merge is default', function () {
        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}]);
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });
    });
  });
});
<commit_msg>FORMS-247 # Fix eslint warnings<commit_after>
/*global assert:true*/ // chai
/*
  To ensure correct, isolated, unit test behavior,
  everything except the file being tested should be mocked or stubbed out.
*/
define(['models/element'],
function (ElementModel) {
  'use strict';

  var noop = function () {};

  suite('models/element.js', function () {
    suite('#setExternalErrors()', function () {
      var model1
        , model2
        , model3
        , model4;

      setup(function () {
        ElementModel.prototype.initialize = noop;

        model1 = new ElementModel({ name: 'model1', id: 'model1' });
        model2 = new ElementModel({ name: 'model2', id: 'model2' });
        model3 = new ElementModel({ name: 'model3', id: 'model3' });
        model4 = new ElementModel({ name: 'model4', id: 'model4' });

        model1.validationError = { value: [{code: 'EMAIL'}] };
        model2.validationError = { value: [{code: 'MAX'}, {code: 'REQUIRED'}] };
        model3.validationError = null;
        model4.validationError = { value: [{code: 'EMAIL'}] };
      });

      teardown(function () {
        model1 = null;
        model2 = null;
        model3 = null;
        model4 = null;
      });

      test('should keep the current errors', function () {
        model1.setExternalErrors([{code: 'blah1'}], {merge: true});
        assert.equal(model1.validationError.value.length, 2);
        assert.equal(model1.validationError.value[0].code, 'blah1');
        assert.equal(model1.validationError.value[1].code, 'EMAIL');

        model2.setExternalErrors([{code: 'blah2'}, {code: 'blah3'}, {code: 'blah4'}], {merge: true});
        assert.equal(model2.validationError.value.length, 5);
        assert.equal(model2.validationError.value[0].code, 'blah4');
        assert.equal(model2.validationError.value[1].code, 'blah3');
        assert.equal(model2.validationError.value[2].code, 'blah2');
        assert.equal(model2.validationError.value[3].code, 'REQUIRED');
        assert.equal(model2.validationError.value[4].code, 'MAX');

        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}], {merge: true});
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });

      test('should not keep the current field errors', function () {
        model1.setExternalErrors([{code: 'blah1'}], {merge: false});
        assert.equal(model1.validationError.value.length, 1);
        assert.equal(model1.validationError.value[0].code, 'blah1');
      });

      test('should default to keeping the current field errors', function () {
        model1.setExternalErrors([{code: 'blah1'}]);
        assert.equal(model1.validationError.value.length, 2);
        assert.equal(model1.validationError.value[0].code, 'blah1');
      });

      test('should handle an empty error list when merging', function () {
        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}], {merge: true});
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });

      test('should handle an empty error list when not merging', function () {
        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}], {merge: false});
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });

      test('should handle an empty error list when not merging and merge is default', function () {
        model3.setExternalErrors([{code: 'blah3'}, {code: 'blah4'}]);
        assert.equal(model3.validationError.value.length, 2);
        assert.equal(model3.validationError.value[0].code, 'blah4');
        assert.equal(model3.validationError.value[1].code, 'blah3');
      });
    });
  });
});
<|endoftext|>


<commit_before>Router.map(function () {
	this.route('frameCalendar', {
		path: '/frame/calendar',
		template: 'frameCalendar',
		layoutTemplate: 'frameCalendar',
		onAfterAction: function() {
			document.title = webpagename + ' Calendar';
		}
	});
});

Template.frameCalendar.onCreated(function() {
	var instance = this;

	// create custom property object
	instance.customProperty = function(key, name, selector) {
		return {
			key: key,
			name: name,
			selector: selector
		};
	};

	instance.eventsRendered = new ReactiveVar(false);

	instance.startOfWeek = new ReactiveVar();
	instance.groupedEvents = new ReactiveVar([]);
	instance.days = new ReactiveVar([]);

	this.autorun(function() {
		minuteTime.get();
		instance.startOfWeek.set(moment().startOf('week'));
	});

	this.autorun(function() {
		var filter = Filtering(EventPredicates)
		             .read(Router.current().params.query)
		             .done();

		var filterParams = filter.toParams();
		var startOfWeek = instance.startOfWeek.get();
		filterParams.after = startOfWeek.toDate();

		instance.subscribe('eventsFind', filterParams, 200);

		var events = Events.find({}, {sort: {start: 1}}).fetch();
		var groupedEvents = _.groupBy(events, function(event) {
			return moment(event.start).format('LL');
		});

		instance.groupedEvents.set(groupedEvents);
		instance.days.set(Object.keys(groupedEvents));
	});
});

Template.frameCalendar.helpers({
	'ready': function() {
		return Template.instance().subscriptionsReady();
	},

	'days': function() {
		return Template.instance().days.get();
	},

	'eventsOn': function(day) {
		var groupedEvents = Template.instance().groupedEvents.get();
		return groupedEvents[day];
	}
});

Template.frameCalendar.onRendered(function() {
	var instance = this;

	instance.autorun(function() {
		var eventsRendered = instance.eventsRendered.get();
		if (eventsRendered) {
			var query = Router.current().params.query;
			var customProperty = instance.customProperty;

			var customProperties = [
				customProperty('bgcolor', 'background-color', 'body'),
				customProperty('color', 'color', 'body'),
				customProperty('eventbg', 'background-color', '.frame-calendar-event'),
				customProperty('eventcolor', 'color', '.frame-calendar-event'),
				customProperty('linkcolor', 'color', '.frame-calendar-event a')
			];

			_.forEach(customProperties, function(property) {
				var value = query[property.key];

				if (value) {
					value = '#' + value;
					$(property.selector).css(property.name, value);
				}
			});
		}
	});
});

Template.frameCalendarEvent.events({
	'click .js-toggle-event-details': function(e, instance) {
		var jQueryTarget = $(e.currentTarget);

		jQueryTarget.toggleClass('active');
		jQueryTarget.nextAll('.frame-calendar-event-body').toggle();
		jQueryTarget.children('.frame-calendar-event-time').toggle();
	}
});

Template.frameCalendarEvent.onRendered(function() {
	var eventsRendered = this.parentInstance().eventsRendered;
	if (!eventsRendered.get()) eventsRendered.set(true);
});
<commit_msg>start calendar-frame from now. closes #689<commit_after>Router.map(function () {
	this.route('frameCalendar', {
		path: '/frame/calendar',
		template: 'frameCalendar',
		layoutTemplate: 'frameCalendar',
		onAfterAction: function() {
			document.title = webpagename + ' Calendar';
		}
	});
});

Template.frameCalendar.onCreated(function() {
	var instance = this;

	// create custom property object
	instance.customProperty = function(key, name, selector) {
		return {
			key: key,
			name: name,
			selector: selector
		};
	};

	instance.eventsRendered = new ReactiveVar(false);

	instance.startOfWeek = new ReactiveVar();
	instance.groupedEvents = new ReactiveVar([]);
	instance.days = new ReactiveVar([]);

	this.autorun(function() {
		var filter = Filtering(EventPredicates)
		             .read(Router.current().params.query)
		             .done();

		var filterParams = filter.toParams();
		filterParams.after = new Date();

		instance.subscribe('eventsFind', filterParams, 200);

		var events = Events.find({}, {sort: {start: 1}}).fetch();
		var groupedEvents = _.groupBy(events, function(event) {
			return moment(event.start).format('LL');
		});

		instance.groupedEvents.set(groupedEvents);
		instance.days.set(Object.keys(groupedEvents));
	});
});

Template.frameCalendar.helpers({
	'ready': function() {
		return Template.instance().subscriptionsReady();
	},

	'days': function() {
		return Template.instance().days.get();
	},

	'eventsOn': function(day) {
		var groupedEvents = Template.instance().groupedEvents.get();
		return groupedEvents[day];
	}
});

Template.frameCalendar.onRendered(function() {
	var instance = this;

	instance.autorun(function() {
		var eventsRendered = instance.eventsRendered.get();
		if (eventsRendered) {
			var query = Router.current().params.query;
			var customProperty = instance.customProperty;

			var customProperties = [
				customProperty('bgcolor', 'background-color', 'body'),
				customProperty('color', 'color', 'body'),
				customProperty('eventbg', 'background-color', '.frame-calendar-event'),
				customProperty('eventcolor', 'color', '.frame-calendar-event'),
				customProperty('linkcolor', 'color', '.frame-calendar-event a')
			];

			_.forEach(customProperties, function(property) {
				var value = query[property.key];

				if (value) {
					value = '#' + value;
					$(property.selector).css(property.name, value);
				}
			});
		}
	});
});

Template.frameCalendarEvent.events({
	'click .js-toggle-event-details': function(e, instance) {
		var jQueryTarget = $(e.currentTarget);

		jQueryTarget.toggleClass('active');
		jQueryTarget.nextAll('.frame-calendar-event-body').toggle();
		jQueryTarget.children('.frame-calendar-event-time').toggle();
	}
});

Template.frameCalendarEvent.onRendered(function() {
	var eventsRendered = this.parentInstance().eventsRendered;
	if (!eventsRendered.get()) eventsRendered.set(true);
});
<|endoftext|>


<commit_before><commit_msg>add theme for FormHeader<commit_after>import { checkBaseTheme } from 'cf-style-const';

export default baseTheme => {
  checkBaseTheme(baseTheme, 'FormHeaderTheme');
  return {
    padding: '1em',
    borderBottom: `1px solid ${baseTheme.colorGrayLight}`
  };
};
<|endoftext|>


<commit_before>
/**
 * Dependencies
 * --------------------------------------------------------------------------*/

var Promise = require('bluebird'),
    _       = require('underscore');

/**
 * Invokes a promisified version of method on an object
 */

function invokeP(obj, method_name, args) {
  return Promise.promisify(obj[method_name], obj).apply(obj, args);
}

/**
 * Returns a promise of a document's save operation
 */

function saveP(doc) {
  return invokeP(doc, 'save')
    .then(_.first, function(err) {
      if(err.name === 'ValidationError') err.status = 400;
      throw err;
    });
}

/**
 * Returns a promise of a document's remove operation
 */

function removeP(doc) {
  return invokeP(doc, 'remove').then(_.first);
}

/**
 * Returns a promise of a Model's find operation
 */

function findP(model, query) {
  var find = model.findAsync || Promise.promisify(model.find, model),
      docP = find.call(model, query);
  return docP;
}

/**
 * Returns a promise of a Model's findOne operation, with an optional not found
 * error message
 */

function findOneP(model, query, not_found_msg) {
  var findOne = model.findOneAsync || Promise.promisify(model.findOne, model),
      docP = findOne.call(model, query);

  if(not_found_msg) {
    return docP.then(function(doc) {
      if(!doc) throw _.extend(new Error(not_found_msg), { status: 404 });
      else     return doc;
    });
  } else return docP;
}

function findByIdP(model, id, not_found_msg) {
  return findOneP(model, {_id: id}, not_found_msg);
}

/**
 * Execs a mongoose query returning a Promise for its results
 */

function execP(query, not_found_msg) {
  var resultsP = invokeP(query, 'exec');
  if(not_found_msg) {
    return resultsP.then(function(results) {
      if(!results || (_.isArray(results) && _.isEmpty(results)))
        throw _.extend(new Error(not_found_msg), { status: 404 });
      else return results;
    });
  } else return resultsP;
}

module.exports = {
  invokeP:   invokeP,
  saveP:     saveP,
  removeP:   removeP,
  findP:     findP,
  findOneP:  findOneP,
  findByIdP: findByIdP,
  execP:     execP
};
<commit_msg>Set Errors' status to 400 error when a query doesn't get results<commit_after>
/**
 * Dependencies
 * --------------------------------------------------------------------------*/

var Promise = require('bluebird'),
    _       = require('underscore');

/**
 * Invokes a promisified version of method on an object
 */

function invokeP(obj, method_name, args) {
  return Promise.promisify(obj[method_name], obj).apply(obj, args);
}

/**
 * Returns a promise of a document's save operation
 */

function saveP(doc) {
  return invokeP(doc, 'save')
    .then(_.first, function(err) {
      if(err.name === 'ValidationError') err.status = 400;
      throw err;
    });
}

/**
 * Returns a promise of a document's remove operation
 */

function removeP(doc) {
  return invokeP(doc, 'remove').then(_.first);
}

/**
 * Returns a promise of a Model's find operation
 */

function findP(model, query) {
  var find = model.findAsync || Promise.promisify(model.find, model),
      docP = find.call(model, query);
  return docP;
}

/**
 * Returns a promise of a Model's findOne operation, with an optional not found
 * error message
 */

function findOneP(model, query, not_found_msg) {
  var findOne = model.findOneAsync || Promise.promisify(model.findOne, model),
      docP = findOne.call(model, query);

  if(not_found_msg) {
    return docP.then(function(doc) {
      if(!doc) throw _.extend(new Error(not_found_msg), { status: 400 });
      else     return doc;
    });
  } else return docP;
}

function findByIdP(model, id, not_found_msg) {
  return findOneP(model, {_id: id}, not_found_msg);
}

/**
 * Execs a mongoose query returning a Promise for its results
 */

function execP(query, not_found_msg) {
  var resultsP = invokeP(query, 'exec');
  if(not_found_msg) {
    return resultsP.then(function(results) {
      if(!results || (_.isArray(results) && _.isEmpty(results)))
        throw _.extend(new Error(not_found_msg), { status: 400 });
      else return results;
    });
  } else return resultsP;
}

module.exports = {
  invokeP:   invokeP,
  saveP:     saveP,
  removeP:   removeP,
  findP:     findP,
  findOneP:  findOneP,
  findByIdP: findByIdP,
  execP:     execP
};
<|endoftext|>


<commit_before>export default function createTestIssue(key, type, color, parentKey, parentType) {
  switch(type) {
    case 'Initiative':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          }
        }
      };
    case 'Epic':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          },
      'issuelinks': [
          {
            'inwardIssue': {
              'key': parentKey
              }
            }
        ]
      }
      };
    case 'Story':
      if(parentType === 'Epic') {
        return {
          'fields': {
            'key': key,
            'status': {
              'statusCategory': {
                'colorName': color
              }
            },
            'issuetype': {
              'name': color
            },
            'customfield_10805': parentKey
          }
        };
      }
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          },
          'issuelinks': [
          {
            'outwardIssue': {
              'key': parentKey
              }
            }
        ]
      }
    };
    case 'Sub-task':
      return {
        'fields': {
          'key': key,
          'parent': {
            'key': parentKey
          },
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          }
        }
      };
    case 'Bug':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          }
        }
      };
    case 'MT':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          }
        }
      };
  }
}
<commit_msg>Fix color as type error in issue-generator<commit_after>export default function createTestIssue(key, type, color, parentKey, parentType) {
  switch(type) {
    case 'Initiative':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          }
        }
      };
    case 'Epic':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          },
      'issuelinks': [
          {
            'inwardIssue': {
              'key': parentKey
              }
            }
        ]
      }
      };
    case 'Story':
      if(parentType === 'Epic') {
        return {
          'fields': {
            'key': key,
            'status': {
              'statusCategory': {
                'colorName': color
              }
            },
            'issuetype': {
              'name': type
            },
            'customfield_10805': parentKey
          }
        };
      }
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          },
          'issuelinks': [
          {
            'outwardIssue': {
              'key': parentKey
              }
            }
        ]
      }
    };
    case 'Sub-task':
      return {
        'fields': {
          'key': key,
          'parent': {
            'key': parentKey
          },
          'status': {
            'statusCategory': {
              'colorName': color
            }
          },
          'issuetype': {
            'name': type
          }
        }
      };
    case 'Bug':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          }
        }
      };
    case 'MT':
      return {
        'fields': {
          'key': key,
          'status': {
            'statusCategory': {
              'colorName': color
            }
          }
        }
      };
  }
}
<|endoftext|>


<commit_before>describe('ax5.util.getObject TEST', function() {

    /* ax5.util.filter */
    //example 01
    var array = [5,4,3,2,1];
    it('ax5.util.filter([5,4,3,2,1],function(){return this%2;})' , function(){
        var result = ax5.util.filter(array,function(){
            return this % 2;
        });

        _.isEqual(result , [5,3,1]).should.equal(true);
    });

    //example 02
    var list = [
        {isdel : 1 , name : "ax5-1"},
        {name : "ax5-2"},
        {isdel : 1 , name : "ax5-3"},
        {name : "ax5-4"},
        {name : "ax5-5"}
    ];

    it('ax5.util.filter([{isdel : 1 , name : "ax5-1"},{name : "ax5-2"},{isdel : 1 , name : "ax5-3"},{name : "ax5-4"},{name : "ax5-5"}] , function(){return (this.isdel !=1)})' , function(){
        var result = ax5.util.filter(list , function(){
            return (this.isdel != 1);
        });

        _.isEqual(result , [{name : "ax5-2"},{name : "ax5-4"},{name : "ax5-5"}  ]).should.equal(true);
    });

    //example03
    var filObject = {
        a : 1,
        s : "string",
        oa : {pickup:true, name:"AXISJ"},
        os : {pickup:true, name:"AX5"}
    };

    it('ax5.util.filter( {a : 1, s : "string", oa : {pickup:true, name:"AXISJ"}, os : {pickup:true, name:"AX5"}}; , function(){return this.pickup;})' , function(){
        var result = ax5.util.filter(filObject , function(){
            return this.pickup;
        });

        _.isEqual(ax5.util.toJson(result) , [{"pickup": true, "name": "AXISJ"}, {"pickup": true , "name": "AX5"}]).should.equal(true);
    });

    /* end ax5.util.filter */
    /*ax5.util.search */
    //example01
    var a = ["A" , "X" , "5"];

    it('ax5.util.search(["A" , "X" , "5"], function(){return this == "X"})' , function(){
        var idx = ax5.util.search(a , function(){
            return this == "X";
        });

        _.isEqual(a[idx] , "X").should.equal(true);
    });

    //example02
    var a = ["A" , "X" ,"5"];

    it('["A" , "X" ,"5"][ax5.util.search(["A" , "X" ,"5"] , function(idx){return idx == 2;})]' , function(){
        var result = a[ax5.util.search(a,function(idx){
            return idx == 2;})
        ];

        _.isEqual(result,"5").should.equal(true);
    });

    //example03
    var b = {a:"AX5-0" , x: "AX5-1" , 5:"AX5-2"};

    it('{a:"AX5-0" , x:"AX5-1" , 5:"AX5-2"}[ax5.util.search(b , function(k){return k == "x"})]' , function(){
        var result = b[ax5.util.search(b,function(k){
            return k == "x";
        })];

        _.isEqual(result , "AX5-1").should.equal(true);
    });
    /*end ax5.util.search */

    /*ax5.util.map*/
    //Usage 01
    var map_a = [1,2,3,4,5];

    it('[1,2,3,4,5] = ax5.util.map([1,2,3,4,5] , function(){return {id : this}})' , function(){
        map_a = ax5.util.map(map_a, function(){
            return {id: this}
        });

        _.isEqual(map_a , [{"id": 1},{"id": 2},{"id": 3},{"id": 4},{"id": 5}]).should.equal(true);
    });

    //Usage 02
    it('ax5.util.map({a: 1, b: 2}, function (k, v) {return {id: k, value: v};})' , function(){

        _.isEqual(ax5.util.map({a: 1, b: 2}, function (k, v) {return {id: k, value: v};}) , [{"id":"a","value":1},{"id":"b","value":2}]).should.equal(true);
    });
    /*end ax5.util.map*/
});
<commit_msg>add ax5.util.merge , ax5.util.reduce , ax5.util.reduceRight test<commit_after>describe('ax5.util.getObject TEST', function() {

    /* ax5.util.filter */
    //example 01
    var array = [5,4,3,2,1];
    it('ax5.util.filter([5,4,3,2,1],function(){return this%2;})' , function(){
        var result = ax5.util.filter(array,function(){
            return this % 2;
        });

        _.isEqual(result , [5,3,1]).should.equal(true);
    });

    //example 02
    var list = [
        {isdel : 1 , name : "ax5-1"},
        {name : "ax5-2"},
        {isdel : 1 , name : "ax5-3"},
        {name : "ax5-4"},
        {name : "ax5-5"}
    ];

    it('ax5.util.filter([{isdel : 1 , name : "ax5-1"},{name : "ax5-2"},{isdel : 1 , name : "ax5-3"},{name : "ax5-4"},{name : "ax5-5"}] , function(){return (this.isdel !=1)})' , function(){
        var result = ax5.util.filter(list , function(){
            return (this.isdel != 1);
        });

        _.isEqual(result , [{name : "ax5-2"},{name : "ax5-4"},{name : "ax5-5"}  ]).should.equal(true);
    });

    //example03
    var filObject = {
        a : 1,
        s : "string",
        oa : {pickup:true, name:"AXISJ"},
        os : {pickup:true, name:"AX5"}
    };

    it('ax5.util.filter( {a : 1, s : "string", oa : {pickup:true, name:"AXISJ"}, os : {pickup:true, name:"AX5"}}; , function(){return this.pickup;})' , function(){
        var result = ax5.util.filter(filObject , function(){
            return this.pickup;
        });

        _.isEqual(ax5.util.toJson(result) , [{"pickup": true, "name": "AXISJ"}, {"pickup": true , "name": "AX5"}]).should.equal(true);
    });

    /* end ax5.util.filter */
    /*ax5.util.search */
    //example01
    var a = ["A" , "X" , "5"];

    it('ax5.util.search(["A" , "X" , "5"], function(){return this == "X"})' , function(){
        var idx = ax5.util.search(a , function(){
            return this == "X";
        });

        _.isEqual(a[idx] , "X").should.equal(true);
    });

    //example02
    var a = ["A" , "X" ,"5"];

    it('["A" , "X" ,"5"][ax5.util.search(["A" , "X" ,"5"] , function(idx){return idx == 2;})]' , function(){
        var result = a[ax5.util.search(a,function(idx){
            return idx == 2;})
        ];

        _.isEqual(result,"5").should.equal(true);
    });

    //example03
    var b = {a:"AX5-0" , x: "AX5-1" , 5:"AX5-2"};

    it('{a:"AX5-0" , x:"AX5-1" , 5:"AX5-2"}[ax5.util.search(b , function(k){return k == "x"})]' , function(){
        var result = b[ax5.util.search(b,function(k){
            return k == "x";
        })];

        _.isEqual(result , "AX5-1").should.equal(true);
    });
    /*end ax5.util.search */

    /*ax5.util.map*/
    //Usage 01
    var map_a = [1,2,3,4,5];

    it('[1,2,3,4,5] = ax5.util.map([1,2,3,4,5] , function(){return {id : this}})' , function(){
        map_a = ax5.util.map(map_a, function(){
            return {id: this}
        });

        _.isEqual(map_a , [{"id": 1},{"id": 2},{"id": 3},{"id": 4},{"id": 5}]).should.equal(true);
    });

    //Usage 02
    it('ax5.util.map({a: 1, b: 2}, function (k, v) {return {id: k, value: v};})' , function(){

        _.isEqual(ax5.util.map({a: 1, b: 2}, function (k, v) {return {id: k, value: v};}) , [{"id":"a","value":1},{"id":"b","value":2}]).should.equal(true);
    });
    /*end ax5.util.map*/

     /*ax5.util.merge*/
    it('ax5.util.merge([1,2,3],[7,8,9])' , function(){
        _.isEqual(ax5.util.merge([1,2,3],[7,8,9]) , [1,2,3,7,8,9]).should.equal(true);
    });
    /*end ax5.util.merge*/

    /*ax5.util.reduce*/
    //Example01
    it('ax5.util.reduce([5,4,3,2,1]) , function(p , n){return p*n;}' , function(){
        should.deepEqual(ax5.util.reduce([5,4,3,2,1] , function(p,n){return p*n;}) , 120);
    });
    //Example02
    it('ax5.util.reduce({a:1,b:2} , function(p,n){ return parseInt(p || 0) + parseInt(n);})' , function(){
        should.deepEqual(ax5.util.reduce({a:1,b:2} , function(p,n){ return parseInt(p || 0) + parseInt(n);}), 3);
    });
    /*end ax5.util.reduce*/

    /*ax5.util.reduceRight*/
    it('ax5.util.reduceRight([5,4,3,2,1] , function(p,n){return p-n;})' ,function(){
        should.deepEqual(ax5.util.reduceRight([5,4,3,2,1] , function(p,n){return p-n;}) , -13);
    });
    /*end ax5.util.reduceRight*/
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
 */

var net = require('net');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var assert = require('assert');

var MAGIC = 'SHAFT';
var MAGICLEN = MAGIC.length;

var MSGTYPE_RESERVED_MIN = 0xf000;
var MSGTYPE_MAGIC = MSGTYPE_RESERVED_MIN + 1;

function
Shaft(conn)
{
	var self = this;
	EventEmitter.call(self);

	self._conn = conn;
	self._data = new Buffer(0);
	self._shutdown = false;
	self._seenmagic = false;

	self._conn.on('data', function(ch) {
		self._ingest(ch);
		self._process();
	});
	self._conn.once('end', function() {
		if (!self._shutdown)
			self.end();
	});

	/*
	 * Identify the strength of our character immediately.
	 */
	self._send_magic();
}
util.inherits(Shaft, EventEmitter);

Shaft.prototype._send_magic = function
neat_send_magic()
{
	var buf = new Buffer(MAGIC, 'ascii');
	self.send(MSGTYPE_MAGIC, buf);
}

Shaft.prototype.send = function
neat_send(type, buf)
{
	assert.ok(!this._shutdown);

	assert.ok(Buffer.isBuffer(buf), 'buf must be a buffer');
	assert.ok(type >= 0 && type < MSGTYPE_RESERVED_MIN, 'type must be ' +
	    'less than ' + MSGTYPE_RESERVED_MIN);
	assert.ok(buf.length <= 0xffff, 'cannot send Shaft payloads longer ' +
	    'than 65535 bytes');

	var hdr = new Buffer(2);
	hdr.writeUInt16BE(type, 0);
	hdr.writeUInt16BE(buf.length, 2);

	this._conn.write(hdr);
	this._conn.write(buf);
}

Shaft.prototype.end = function
neat_end()
{
	if (!this._shutdown) {
		this._shutdown = true;
		this._conn.end();
		this.emit('end');
	}
}

Shaft.prototype._ingest = function
neat_ingest(buf)
{
	/*
	 * Pull buffer up:
	 */
	if (this._data.length > 0) {
		var _tmp = new Buffer(buf.length + this._data.length);
		this._data.copy(_tmp, 0);
		buf.copy(_tmp, this._data.length);
		this._data = _tmp;
	} else {
		this._data = buf;
	}
}

Shaft.prototype._process = function
neat_process()
{
	for (;;) {
		/*
		 * Wait for at least one message header:
		 */
		if (this._data.length < 2)
			break;

		var msgtype = this._data.readUInt8(0);
		var msglen = this._data.readUInt8(1);

		/*
		 * Do we have at least one complete message?
		 */
		if (this._data.length < msglen + 2)
			break;

		/*
		 * If so, slice it out:
		 */
		var msgbuf = this._data.slice(2, msglen + 2);
		this._data = this._data.slice(msglen + 2);

		switch (msgtype) {
		case MSGTYPE_MAGIC:
			if (msgbuf.length !== MAGICLEN ||
			    msgbuf.msgbuf.toString('ascii') !== MAGIC) {
				this.emit('fail', 'client magic not ok');
				this.end();
				return;
			} else {
				this._seenmagic = true;
			}
			break;
		default:
			if (!this._seenmagic) {
				this.emit('fail', 'client did not send magic');
				this.end();
				return;
			}
			this.emit('message', msgtype, msgbuf);
			msgbuf = null;
			break;
		}
	}
}

module.exports = {
	Shaft: Shaft
};

/* vim: set sts=8 ts=8 sw=8 noet: */
<commit_msg>this, not self<commit_after>/*
 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
 */

var net = require('net');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var assert = require('assert');

var MAGIC = 'SHAFT';
var MAGICLEN = MAGIC.length;

var MSGTYPE_RESERVED_MIN = 0xf000;
var MSGTYPE_MAGIC = MSGTYPE_RESERVED_MIN + 1;

function
Shaft(conn)
{
	var self = this;
	EventEmitter.call(self);

	self._conn = conn;
	self._data = new Buffer(0);
	self._shutdown = false;
	self._seenmagic = false;

	self._conn.on('data', function(ch) {
		self._ingest(ch);
		self._process();
	});
	self._conn.once('end', function() {
		if (!self._shutdown)
			self.end();
	});

	/*
	 * Identify the strength of our character immediately.
	 */
	self._send_magic();
}
util.inherits(Shaft, EventEmitter);

Shaft.prototype._send_magic = function
neat_send_magic()
{
	var buf = new Buffer(MAGIC, 'ascii');
	this.send(MSGTYPE_MAGIC, buf);
}

Shaft.prototype.send = function
neat_send(type, buf)
{
	assert.ok(!this._shutdown);

	assert.ok(Buffer.isBuffer(buf), 'buf must be a buffer');
	assert.ok(type >= 0 && type < MSGTYPE_RESERVED_MIN, 'type must be ' +
	    'less than ' + MSGTYPE_RESERVED_MIN);
	assert.ok(buf.length <= 0xffff, 'cannot send Shaft payloads longer ' +
	    'than 65535 bytes');

	var hdr = new Buffer(2);
	hdr.writeUInt16BE(type, 0);
	hdr.writeUInt16BE(buf.length, 2);

	this._conn.write(hdr);
	this._conn.write(buf);
}

Shaft.prototype.end = function
neat_end()
{
	if (!this._shutdown) {
		this._shutdown = true;
		this._conn.end();
		this.emit('end');
	}
}

Shaft.prototype._ingest = function
neat_ingest(buf)
{
	/*
	 * Pull buffer up:
	 */
	if (this._data.length > 0) {
		var _tmp = new Buffer(buf.length + this._data.length);
		this._data.copy(_tmp, 0);
		buf.copy(_tmp, this._data.length);
		this._data = _tmp;
	} else {
		this._data = buf;
	}
}

Shaft.prototype._process = function
neat_process()
{
	for (;;) {
		/*
		 * Wait for at least one message header:
		 */
		if (this._data.length < 2)
			break;

		var msgtype = this._data.readUInt8(0);
		var msglen = this._data.readUInt8(1);

		/*
		 * Do we have at least one complete message?
		 */
		if (this._data.length < msglen + 2)
			break;

		/*
		 * If so, slice it out:
		 */
		var msgbuf = this._data.slice(2, msglen + 2);
		this._data = this._data.slice(msglen + 2);

		switch (msgtype) {
		case MSGTYPE_MAGIC:
			if (msgbuf.length !== MAGICLEN ||
			    msgbuf.msgbuf.toString('ascii') !== MAGIC) {
				this.emit('fail', 'client magic not ok');
				this.end();
				return;
			} else {
				this._seenmagic = true;
			}
			break;
		default:
			if (!this._seenmagic) {
				this.emit('fail', 'client did not send magic');
				this.end();
				return;
			}
			this.emit('message', msgtype, msgbuf);
			msgbuf = null;
			break;
		}
	}
}

module.exports = {
	Shaft: Shaft
};

/* vim: set sts=8 ts=8 sw=8 noet: */
<|endoftext|>


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

const should = require("should");
const path = require("path");

const webpack = require("../");
const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter");

const webpack = require("../");
const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter");

describe("Compiler", () => {
	function compile(entry, options, callback) {
		const noOutputPath = !options.output || !options.output.path;
		new WebpackOptionsDefaulter().process(options);
		options.entry = entry;
		options.context = path.join(__dirname, "fixtures");
		if(noOutputPath) options.output.path = "/";
		options.output.pathinfo = true;
		const logs = {
			mkdirp: [],
			writeFile: [],
		};

		const c = webpack(options);
		const files = {};
		c.outputFileSystem = {
			join: function() {
				return [].join.call(arguments, "/").replace(/\/+/g, "/");
			},
			mkdirp: function(path, callback) {
				logs.mkdirp.push(path);
				callback();
			},
			writeFile: function(name, content, callback) {
				logs.writeFile.push(name, content);
				files[name] = content.toString("utf-8");
				callback();
			}
		};
		c.plugin("compilation", (compilation) => compilation.bail = true);
		c.run((err, stats) => {
			if(err) throw err;
			should.strictEqual(typeof stats, "object");
			const compilation = stats.compilation;
			stats = stats.toJson({
				modules: true,
				reasons: true
			});
			should.strictEqual(typeof stats, "object");
			stats.should.have.property("errors");
			Array.isArray(stats.errors).should.be.ok();
			if(stats.errors.length > 0) {
				stats.errors[0].should.be.instanceOf(Error);
				throw stats.errors[0];
			}
			stats.logs = logs;
			callback(stats, files, compilation);
		});
	}
	it("should compile a single file to deep output", (done) => {
		compile("./c", {
			output: {
				path: "/what",
				filename: "the/hell.js",
			}
		}, (stats, files) => {
			stats.logs.mkdirp.should.eql([
				"/what",
				"/what/the",
			]);
			done();
		});
	});

  it("should compile a single file", (done) => {
		compile("./c", {}, (stats, files) => {
			files.should.have.property("/main.js").have.type("string");
			Object.keys(files).should.be.eql(["/main.js"]);
			const bundle = files["/main.js"];
			bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./a */ 0);");
			bundle.should.containEql("./c.js");
			bundle.should.containEql("./a.js");
			bundle.should.containEql("This is a");
			bundle.should.containEql("This is c");
			bundle.should.not.containEql("2: function(");
			bundle.should.not.containEql("window");
			bundle.should.not.containEql("jsonp");
			bundle.should.not.containEql("fixtures");
			done();
		});
	});

  it("should compile a complex file", (done) => {
		compile("./main1", {}, (stats, files) => {
			files.should.have.property("/main.js").have.type("string");
			Object.keys(files).should.be.eql(["/main.js"]);
			const bundle = files["/main.js"];
			bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./a */");
			bundle.should.containEql("./main1.js");
			bundle.should.containEql("./a.js");
			bundle.should.containEql("./b.js");
			bundle.should.containEql("./~/m1/a.js");
			bundle.should.containEql("This is a");
			bundle.should.containEql("This is b");
			bundle.should.containEql("This is m1/a");
			bundle.should.not.containEql("4: function(");
			bundle.should.not.containEql("window");
			bundle.should.not.containEql("jsonp");
			bundle.should.not.containEql("fixtures");
			done();
		});
	});

  it("should compile a file with transitive dependencies", (done) => {
		compile("./abc", {}, (stats, files) => {
			files.should.have.property("/main.js").have.type("string");
			Object.keys(files).should.be.eql(["/main.js"]);
			const bundle = files["/main.js"];
			bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./a */");
			bundle.should.containEql("__webpack_require__(/*! ./b */");
			bundle.should.containEql("__webpack_require__(/*! ./c */");
			bundle.should.containEql("./abc.js");
			bundle.should.containEql("./a.js");
			bundle.should.containEql("./b.js");
			bundle.should.containEql("./c.js");
			bundle.should.containEql("This is a");
			bundle.should.containEql("This is b");
			bundle.should.containEql("This is c");
			bundle.should.not.containEql("4: function(");
			bundle.should.not.containEql("window");
			bundle.should.not.containEql("jsonp");
			bundle.should.not.containEql("fixtures");
			done();
		});
	});

  it("should compile a file with multiple chunks", (done) => {
		compile("./chunks", {}, (stats, files) => {
			stats.chunks.length.should.be.eql(2);
			files.should.have.property("/main.js").have.type("string");
			files.should.have.property("/0.js").have.type("string");
			Object.keys(files).should.be.eql(["/0.js", "/main.js"]);
			const bundle = files["/main.js"];
			const chunk = files["/0.js"];
      bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./b */");
			chunk.should.not.containEql("__webpack_require__(/* ./b */");
			bundle.should.containEql("./chunks.js");
			chunk.should.containEql("./a.js");
			chunk.should.containEql("./b.js");
			chunk.should.containEql("This is a");
			bundle.should.not.containEql("This is a");
			chunk.should.containEql("This is b");
			bundle.should.not.containEql("This is b");
			bundle.should.not.containEql("4: function(");
			bundle.should.not.containEql("fixtures");
			chunk.should.not.containEql("fixtures");
			bundle.should.containEql("webpackJsonp");
			chunk.should.containEql("webpackJsonp(");
			done();
		});
	});
});
<commit_msg>fixup incorrect merge<commit_after>/* globals describe, it */
"use strict";

const should = require("should");
const path = require("path");

const webpack = require("../");
const WebpackOptionsDefaulter = require("../lib/WebpackOptionsDefaulter");

describe("Compiler", () => {
	function compile(entry, options, callback) {
		const noOutputPath = !options.output || !options.output.path;
		new WebpackOptionsDefaulter().process(options);
		options.entry = entry;
		options.context = path.join(__dirname, "fixtures");
		if(noOutputPath) options.output.path = "/";
		options.output.pathinfo = true;
		const logs = {
			mkdirp: [],
			writeFile: [],
		};

		const c = webpack(options);
		const files = {};
		c.outputFileSystem = {
			join: function() {
				return [].join.call(arguments, "/").replace(/\/+/g, "/");
			},
			mkdirp: function(path, callback) {
				logs.mkdirp.push(path);
				callback();
			},
			writeFile: function(name, content, callback) {
				logs.writeFile.push(name, content);
				files[name] = content.toString("utf-8");
				callback();
			}
		};
		c.plugin("compilation", (compilation) => compilation.bail = true);
		c.run((err, stats) => {
			if(err) throw err;
			should.strictEqual(typeof stats, "object");
			const compilation = stats.compilation;
			stats = stats.toJson({
				modules: true,
				reasons: true
			});
			should.strictEqual(typeof stats, "object");
			stats.should.have.property("errors");
			Array.isArray(stats.errors).should.be.ok();
			if(stats.errors.length > 0) {
				stats.errors[0].should.be.instanceOf(Error);
				throw stats.errors[0];
			}
			stats.logs = logs;
			callback(stats, files, compilation);
		});
	}
	it("should compile a single file to deep output", (done) => {
		compile("./c", {
			output: {
				path: "/what",
				filename: "the/hell.js",
			}
		}, (stats, files) => {
			stats.logs.mkdirp.should.eql([
				"/what",
				"/what/the",
			]);
			done();
		});
	});

  it("should compile a single file", (done) => {
		compile("./c", {}, (stats, files) => {
			files.should.have.property("/main.js").have.type("string");
			Object.keys(files).should.be.eql(["/main.js"]);
			const bundle = files["/main.js"];
			bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./a */ 0);");
			bundle.should.containEql("./c.js");
			bundle.should.containEql("./a.js");
			bundle.should.containEql("This is a");
			bundle.should.containEql("This is c");
			bundle.should.not.containEql("2: function(");
			bundle.should.not.containEql("window");
			bundle.should.not.containEql("jsonp");
			bundle.should.not.containEql("fixtures");
			done();
		});
	});

  it("should compile a complex file", (done) => {
		compile("./main1", {}, (stats, files) => {
			files.should.have.property("/main.js").have.type("string");
			Object.keys(files).should.be.eql(["/main.js"]);
			const bundle = files["/main.js"];
			bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./a */");
			bundle.should.containEql("./main1.js");
			bundle.should.containEql("./a.js");
			bundle.should.containEql("./b.js");
			bundle.should.containEql("./~/m1/a.js");
			bundle.should.containEql("This is a");
			bundle.should.containEql("This is b");
			bundle.should.containEql("This is m1/a");
			bundle.should.not.containEql("4: function(");
			bundle.should.not.containEql("window");
			bundle.should.not.containEql("jsonp");
			bundle.should.not.containEql("fixtures");
			done();
		});
	});

  it("should compile a file with transitive dependencies", (done) => {
		compile("./abc", {}, (stats, files) => {
			files.should.have.property("/main.js").have.type("string");
			Object.keys(files).should.be.eql(["/main.js"]);
			const bundle = files["/main.js"];
			bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./a */");
			bundle.should.containEql("__webpack_require__(/*! ./b */");
			bundle.should.containEql("__webpack_require__(/*! ./c */");
			bundle.should.containEql("./abc.js");
			bundle.should.containEql("./a.js");
			bundle.should.containEql("./b.js");
			bundle.should.containEql("./c.js");
			bundle.should.containEql("This is a");
			bundle.should.containEql("This is b");
			bundle.should.containEql("This is c");
			bundle.should.not.containEql("4: function(");
			bundle.should.not.containEql("window");
			bundle.should.not.containEql("jsonp");
			bundle.should.not.containEql("fixtures");
			done();
		});
	});

  it("should compile a file with multiple chunks", (done) => {
		compile("./chunks", {}, (stats, files) => {
			stats.chunks.length.should.be.eql(2);
			files.should.have.property("/main.js").have.type("string");
			files.should.have.property("/0.js").have.type("string");
			Object.keys(files).should.be.eql(["/0.js", "/main.js"]);
			const bundle = files["/main.js"];
			const chunk = files["/0.js"];
      bundle.should.containEql("function __webpack_require__(");
			bundle.should.containEql("__webpack_require__(/*! ./b */");
			chunk.should.not.containEql("__webpack_require__(/* ./b */");
			bundle.should.containEql("./chunks.js");
			chunk.should.containEql("./a.js");
			chunk.should.containEql("./b.js");
			chunk.should.containEql("This is a");
			bundle.should.not.containEql("This is a");
			chunk.should.containEql("This is b");
			bundle.should.not.containEql("This is b");
			bundle.should.not.containEql("4: function(");
			bundle.should.not.containEql("fixtures");
			chunk.should.not.containEql("fixtures");
			bundle.should.containEql("webpackJsonp");
			chunk.should.containEql("webpackJsonp(");
			done();
		});
	});
});
<|endoftext|>


<commit_before>//@flow

import styled, { css } from "styled-components";

export const CrazyLine = styled.path.attrs({
  d: ({ top }: { top: boolean }): string =>
    top
      ? "M5.51471863,40.4852814 C11.1715729,34.8284271 16.8284271,29.1715729 22.4852814,23.5147186 C31,15 28,0 14,0 C-4,0 -3,26 14,26 C24,26 25.5,19 32.4852814,19 C39.4705627,19 41,25 48,25 C55,25 55.5,19 63,19 C70.5,19 67.5,23 83.5,23 C85.8333333,23 93.6666667,23 107,23"
      : "M5.51239599,63.9852814 C11.1692502,58.3284271 16.8261045,52.6715729 22.4829587,47.0147186 C30.9976774,38.5 27.9976774,23.5 13.9976774,23.5 C-4.00232264,23.5 -3.00232264,49.5 13.9976774,49.5 C23.9976774,49.5 25.4976774,42.5 32.4829587,42.5 C39.4682401,42.5 40.9976774,48.5 47.9976774,48.5 C54.9976774,48.5 55.4976774,42.5 62.9976774,42.5 C70.4976774,42.5 67.4976774,46.5 83.4976774,46.5 C85.8310107,46.5 93.664344,46.5 106.997677,46.5"
})`
  stroke-dasharray: 24 173;
  will-change: stroke-dashoffset;
  transition: stroke-dashoffset 0.4s;
  ${({ top, isOpen }: { top: boolean, isOpen: boolean }) => css`
    stroke-dashoffset: ${isOpen ? 197 : 25};
    ${!top && css`
      transform: matrix(1, 0, 0, -1, 0, 87.485);
    `}
  `}
`;
<commit_msg>Slow the mobile-menu-button animation<commit_after>//@flow

import styled, { css } from "styled-components";

export const CrazyLine = styled.path.attrs({
  d: ({ top }: { top: boolean }): string =>
    top
      ? "M5.51471863,40.4852814 C11.1715729,34.8284271 16.8284271,29.1715729 22.4852814,23.5147186 C31,15 28,0 14,0 C-4,0 -3,26 14,26 C24,26 25.5,19 32.4852814,19 C39.4705627,19 41,25 48,25 C55,25 55.5,19 63,19 C70.5,19 67.5,23 83.5,23 C85.8333333,23 93.6666667,23 107,23"
      : "M5.51239599,63.9852814 C11.1692502,58.3284271 16.8261045,52.6715729 22.4829587,47.0147186 C30.9976774,38.5 27.9976774,23.5 13.9976774,23.5 C-4.00232264,23.5 -3.00232264,49.5 13.9976774,49.5 C23.9976774,49.5 25.4976774,42.5 32.4829587,42.5 C39.4682401,42.5 40.9976774,48.5 47.9976774,48.5 C54.9976774,48.5 55.4976774,42.5 62.9976774,42.5 C70.4976774,42.5 67.4976774,46.5 83.4976774,46.5 C85.8310107,46.5 93.664344,46.5 106.997677,46.5"
})`
  stroke-dasharray: 24 173;
  will-change: stroke-dashoffset;
  transition: stroke-dashoffset 1s;
  ${({ top, isOpen }: { top: boolean, isOpen: boolean }) => css`
    stroke-dashoffset: ${isOpen ? 197 : 25};
    ${!top &&
      css`
      transform: matrix(1, 0, 0, -1, 0, 87.485);
    `}
  `}
`;
<|endoftext|>


<commit_before>requirejs(["rAppid"], function (rAppid) {

    rAppid.defineClass("js.ui.ItemsView",
        ["js.ui.View", "js.core.Template", "js.core.List"], function (View, Template, List) {
            return View.inherit({
                defaults: {
                    tagName: "div",
                    items: []
                },
                hasItems: function(){
                    return this.$.items.length > 0;
                }.on('items'),
                addItem: function (item) {
                    this.$.items.push(item);
                    if (this.isRendered()) {
                        this._renderItem(item);
                    }
                },
                render: function(){
                    this.$renderedItems = [];
                    return this.callBase();
                },
                removeItem: function(item){
                    var index = this.$.items.indexOf(item);
                    if(index > -1){
                        this.$.items.slice(index,1);
                        if (this.isRendered()) {
                            this._removeRenderedItem(item);
                        }
                    }

                },
                clear: function(){

                },
                _renderList: function(list, oldList){
                    if(oldList){
                        // TODO: unbind!
                    }
                    if(list instanceof List){
                        list.bind('sort', this._onSort, this);
                        list.bind('reset', this._onReset, this);
                        list.bind('add', this._onItemAdd,this);
                        list.bind('remove', this._onItemRemove,this);

                        this.set({items: list.$items});
                    }
                },
                _onSort: function(e){
                    if(this.isRendered()){
                        var item, c;
                        for (var i = 0; i < e.$.items.length; i++) {
                            item = e.$.items[i];
                            c = this.getComponentForItem(item);
                            this.$el.removeChild(c.$el);
                            this.$el.appendChild(c.$el);
                        }
                    }
                },
                _onReset: function(e){
                    this.set('items',e.$.items);
                },
                _onItemAdd: function(e){
                    this._renderItem(e.$.item,e.$.index);
                },
                _onItemRemove: function(e){
                    this._removeRenderedItem(e.$.item);
                },
                _renderItems: function (items) {
                    if (this.$renderedItems) {
                        var c;
                        for (var j = this.$renderedItems.length - 1; j >= 0; j--) {
                            c = this.$renderedItems[j];
                            this.$el.removeChild(c.component.$el);
                        }
                    }
                    this.$renderedItems = [];
                    for (var i = 0; i < items.length; i++) {
                        this._renderItem(items[i],i);
                    }

                },
                _renderItem: function (item,i) {
                    var comp = this.$templates['item'].createComponents({$item: item, $index: i})[0];
                    // add to rendered item map
                    this.$renderedItems.push({
                        item: item,
                        component: comp
                    });
                    this.addChild(comp);
                },
                _removeRenderedItem: function(item){
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            this.$el.removeChild(ri.component.$el);
                            this.$renderedItems.slice(i,1);
                            return;
                        }
                    }
                },
                getComponentForItem: function (item) {
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            return ri.component;
                        }
                    }
                    return null;
                }
            });
        }
    );
});<commit_msg>fixed ItemsView<commit_after>requirejs(["rAppid"], function (rAppid) {

    rAppid.defineClass("js.ui.ItemsView",
        ["js.ui.View", "js.core.Template", "js.core.List"], function (View, Template, List) {
            return View.inherit({
                defaults: {
                    tagName: "div",
                    items: null
                },
                hasItems: function(){
                    if(this.$.items){
                        return this.$.items.length;
                    }
                    return 0;
                }.on('items'),
                render: function(){
                    this.$renderedItems = [];
                    return this.callBase();
                },
                clear: function(){

                },
                _renderItems: function(items,oldItems){
                    if (oldItems && oldItems instanceof List) {
                        oldItems.unbind('sort', this._onSort);
                        oldItems.unbind('reset', this._onReset);
                        oldItems.unbind('add', this._onItemAdd);
                        oldItems.unbind('remove', this._onItemRemove);
                    }

                    if(items instanceof List){

                        items.bind('sort', this._onSort, this);
                        items.bind('reset', this._onReset, this);
                        items.bind('add', this._onItemAdd, this);
                        items.bind('remove', this._onItemRemove, this);
                        this._innerRenderItems(items.$items);
                    } else if(rAppid._.isArray(items)){
                        this._innerRenderItems(items);
                    }
                },
                _onSort: function(e){
                    if(this.isRendered()){
                        var item, c;
                        for (var i = 0; i < e.$.items.length; i++) {
                            item = e.$.items[i];
                            c = this.getComponentForItem(item);
                            this.$el.removeChild(c.$el);
                            this.$el.appendChild(c.$el);
                        }
                    }
                },
                _onReset: function(e){
                    this._innerRenderItems(e.$.items);
                },
                _onItemAdd: function(e){
                    this._innerRenderItem(e.$.item,e.$.index);
                },
                _onItemRemove: function(e){
                    this._removeRenderedItem(e.$.item);
                },
                _innerRenderItems: function (items) {
                    if (this.$renderedItems) {
                        var c;
                        for (var j = this.$renderedItems.length - 1; j >= 0; j--) {
                            c = this.$renderedItems[j];
                            this.$el.removeChild(c.component.$el);
                        }
                    }
                    this.$renderedItems = [];
                    for (var i = 0; i < items.length; i++) {
                        this._innerRenderItem(items[i],i);
                    }

                },
                _innerRenderItem: function (item,i) {
                    var comp = this.$templates['item'].createComponents({$item: item, $index: i})[0];
                    // add to rendered item map
                    this.$renderedItems.push({
                        item: item,
                        component: comp
                    });
                    this.addChild(comp);
                },
                _removeRenderedItem: function(item){
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            this.$el.removeChild(ri.component.$el);
                            this.$renderedItems.slice(i,1);
                            return;
                        }
                    }
                },
                getComponentForItem: function (item) {
                    var ri;
                    for (var i = 0; i < this.$renderedItems.length; i++) {
                        ri = this.$renderedItems[i];
                        if (ri.item === item) {
                            return ri.component;
                        }
                    }
                    return null;
                }
            });
        }
    );
});<|endoftext|>


<commit_before>module.exports = function(config) {
  config.set({
    basePath: './',
    frameworks: ['jasmine'],
    files: [
      'node_modules/jquery/dist/jquery.js',
      'node_modules/bootstrap/dist/js/bootstrap.js',
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/dropdown.js',
      'test/dropdown.spec.js'
    ],
    plugins: [
      require('karma-jasmine'),
      require('karma-phantomjs-launcher')
    ],
    reporters: ['progress',],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false
  })
}<commit_msg>Update karma.conf<commit_after>module.exports = function(config) {
  config.set({
    basePath: './',
    frameworks: ['jasmine'],
    files: [
      'node_modules/jquery/dist/jquery.js',
      'node_modules/bootstrap/dist/js/bootstrap.js',
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'src/dropdown.js',
      'test/dropdown.spec.js'
    ],
    plugins: [
      require('karma-jasmine'),
      require('karma-phantomjs-launcher')
    ],
    reporters: ['progress',],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: true
  })
}<|endoftext|>