<commit_before>var DataStore = require('../lib/datastore');

module.exports = function(grunt ) {

  grunt.registerTask('xen', 'Xen management task', function() {

    var arg = Array.prototype.slice.call(arguments, 1);
    var config = grunt.config.get('xen');
    var task = this;

    if(!config){
      grunt.fatal('Oops! Please provide XenTask configuration in your grunt.js file');
      return;
    }

    var getDataItem = function(type, props, uriPrefix) {

      props.uri = (uriPrefix || '') + props.title.toLowerCase().replace(/[^\w ]+/g,'').replace(/ +/g,'-');
      props.contentPath = props.uri + '.html';
      props.dateCreated = (props.dateCreated === 'now') ? new Date().getTime() : props.dateCreated;
      props.showInNav = ( props.showInNav === 'y' || props.showInNav === 'Y' );
      props.tags = props.tags ? props.tags.replace(/,\s+/g, ',').split(',') : [];

      return props;
    };

    var prompts = {
      content: [{
        name: 'title',
        message: 'Title'
      }, {
        name: 'description',
        message: 'Description'
      }, {
        name: 'tags',
        message: 'Tags (comma separated)'
      }, {
        name: 'view',
        message: 'View file',
        default: 'page/generic'
      }, {
        name: 'dateCreated',
        message: 'Date',
        default: 'now'
      }, {
        name: 'showInNav',
        message: 'Show in navigation?',
        default: 'y/N'
      }]
    };

    // sub-task-specific utilities
    var subtask = {
      addpost: function(uri) {
        var done = task.async();
        grunt.helper('prompt', prompts.content, function(err, props) {
          var data = getDataItem('posts', props, 'post/');
          new DataStore('posts').add(data).save();
          done();
        });
      },
      addpage: function(uri) {
        var done = task.async();
        grunt.helper('prompt', prompts.content, function(err, props) {
          var data = getDataItem('pages', props);
          console.log(data, 'test');
          new DataStore('pages').add(data).save();
          done();
        });
      },
      removepage: function(uri) {
        new DataStore('pages').where(function(page){
          return ( page.uri === uri );
        }).remove();
      },
      removepost: function(uri) {
        new DataStore('posts').where(function(post){
          return ( post.uri === uri );
        }).remove();
      },
    };

    var stask = subtask[this.args[0]];
    if (stask) {
      stask.apply(stask, arg);
    } else {
      grunt.fail.warn('Sub-task not found!');
    }
  });
};<commit_msg>Finishd addpost subtask and add reset subtack<commit_after>var DataStore = require('../lib/datastore');
var fs = require('fs');

module.exports = function(grunt ) {

  grunt.registerTask('xen', 'Xen management task', function() {

    var arg = Array.prototype.slice.call(arguments, 1);
    var config = grunt.config.get('xen');
    var task = this;

    var defaultHTMLpath = grunt.task.getFile('xen/static/default-content.html');
    var defaultHTMLsrc = grunt.file.read(defaultHTMLpath);

    if(!config){
      grunt.fatal('Oops! Please provide XenTask configuration in your grunt.js file');
      return;
    }

    var getDataItem = function(type, props, uriPrefix) {

      var uriSegment = props.title.toLowerCase().replace(/[^\w ]+/g,'').replace(/ +/g,'-');
      props.uri = uriPrefix + uriSegment;
      props.contentPath = type + '/' + uriSegment + '.html';
      props.dateCreated = (props.dateCreated === 'now') ? new Date().getTime() : props.dateCreated;
      props.showInNav = ( props.showInNav === 'y' || props.showInNav === 'Y' );
      props.tags = props.tags ? props.tags.replace(/,\s+/g, ',').split(',') : [];

      return props;
    };

    var prompts = {
      content: [{
        name: 'title',
        message: 'Title'
      }, {
        name: 'description',
        message: 'Description'
      }, {
        name: 'tags',
        message: 'Tags (comma separated)'
      }, {
        name: 'view',
        message: 'View file',
        'default': 'page/generic'
      }, {
        name: 'dateCreated',
        message: 'Date',
        'default': 'now'
      }, {
        name: 'showInNav',
        message: 'Show in navigation? (Y/n)',
        'default': 'y'
      }]
    };

    // sub-task-specific utilities
    var subtask = {
      addpost: function(uri) {
        var done = task.async();
        grunt.helper('prompt', prompts.content, function(err, props) {

          var data = getDataItem('posts', props, 'post/');
          new DataStore('posts').add(data).save();

          var contentPath = './content/' + data.contentPath;
          grunt.file.write(contentPath, defaultHTMLsrc);

          done();
        });
      },
      addpage: function(uri) {
        var done = task.async();
        grunt.helper('prompt', prompts.content, function(err, props) {
          var data = getDataItem('pages', props);
          new DataStore('pages').add(data).save();
          done();
        });
      },
      removepage: function(uri) {
        new DataStore('pages').where(function(page){
          return ( page.uri === uri );
        }).remove();
      },
      removepost: function(uri) {
        new DataStore('posts').where(function(post){
          return ( post.uri === uri );
        }).remove();
      },
      reset: function() {

        function wipeDirectory(dir, callback) {
          fs.readdir(dir, function(err, files) {
            if (!files.length) return callback();
            var i = 0;
            files.forEach(function(file) {
              var filePath = dir + '/' + file;
              fs.stat(filePath, function(err, stats) {
                if (err) {
                  console.log(cd .JSON.stringify(err));
                  return callback();
                }
                if (!stats.isFile()) return callback();
                fs.unlink(filePath, function(err) {
                  if (err) console.log(JSON.stringify(err));
                  if (++i === files.length) callback();
                });
              });
            });
          });
        }

        function copyFiles(oldDir, newDir, callback) {
          fs.readdir(oldDir, function(err, files) {
            if (!files.length) return callback();
            var dir = oldDir.replace(/tasks/, '');
            files.forEach(function(file) {
              var content = grunt.file.read(grunt.task.getFile(dir + '/' + file));
              grunt.file.write('./' + newDir + '/' + file, content);
            });
            callback();
          });
        }

        var done = task.async();

        var pages = new DataStore(null, __dirname + '/xen/content/pages.json');
        pages.save(__dirname + '/../content/pages.json')

        var posts = new DataStore(null, __dirname + '/xen/content/posts.json');
        posts.save(__dirname + '/../content/posts.json')

        wipeDirectory('content/pages', function() {
          wipeDirectory('content/posts', function() {
            copyFiles('tasks/xen/content/pages', 'content/pages', function() {
              copyFiles('tasks/xen/content/posts', 'content/posts', function() {
                done();
              })
            });
          });
        });
      }
    };

    var stask = subtask[this.args[0]];
    if (stask) {
      stask.apply(stask, arg);
    } else {
      grunt.fail.warn('Sub-task not found!');
    }
  });
};
<|endoftext|>


<commit_before>import assert from "assert";
import * as t from "@babel/types";

import ImportBuilder from "./import-builder";
import isModule from "./is-module";

export type ImportOptions = {
  /**
   * The module being referenced.
   */
  importedSource: string | null,

  /**
   * The type of module being imported:
   *
   *  * 'es6'      - An ES6 module.
   *  * 'commonjs' - A CommonJS module. (Default)
   */
  importedType: "es6" | "commonjs",

  /**
   * The type of interop behavior for namespace/default/named when loading
   * CommonJS modules.
   *
   * ## 'babel' (Default)
   *
   * Load using Babel's interop.
   *
   * If '.__esModule' is true, treat as 'compiled', else:
   *
   * * Namespace: A copy of the module.exports with .default
   *     populated by the module.exports object.
   * * Default: The module.exports value.
   * * Named: The .named property of module.exports.
   *
   * The 'ensureLiveReference' has no effect on the liveness of these.
   *
   * ## 'compiled'
   *
   * Assume the module is ES6 compiled to CommonJS. Useful to avoid injecting
   * interop logic if you are confident that the module is a certain format.
   *
   * * Namespace: The root module.exports object.
   * * Default: The .default property of the namespace.
   * * Named: The .named property of the namespace.
   *
   * Will return erroneous results if the imported module is _not_ compiled
   * from ES6 with Babel.
   *
   * ## 'uncompiled'
   *
   * Assume the module is _not_ ES6 compiled to CommonJS. Used a simplified
   * access pattern that doesn't require additional function calls.
   *
   * Will return erroneous results if the imported module _is_ compiled
   * from ES6 with Babel.
   *
   * * Namespace: The module.exports object.
   * * Default: The module.exports object.
   * * Named: The .named property of module.exports.
   */
  importedInterop: "babel" | "node" | "compiled" | "uncompiled",

  /**
   * The type of CommonJS interop included in the environment that will be
   * loading the output code.
   *
   *  * 'babel' - CommonJS modules load with Babel's interop. (Default)
   *  * 'node'  - CommonJS modules load with Node's interop.
   *
   * See descriptions in 'importedInterop' for more details.
   */
  importingInterop: "babel" | "node",

  /**
   * Define whether we explicitly care that the import be a live reference.
   * Only applies when importing default and named imports, not the namespace.
   *
   *  * true  - Force imported values to be live references.
   *  * false - No particular requirements. Keeps the code simplest. (Default)
   */
  ensureLiveReference: boolean,

  /**
   * Define if we explicitly care that the result not be a property reference.
   *
   *  * true  - Force calls to exclude context. Useful if the value is going to
   *            be used as function callee.
   *  * false - No particular requirements for context of the access. (Default)
   */
  ensureNoContext: boolean,
};

/**
 * A general helper classes add imports via transforms. See README for usage.
 */
export default class ImportInjector {
  /**
   * The path used for manipulation.
   */
  _programPath: NodePath;

  /**
   * The scope used to generate unique variable names.
   */
  _programScope;

  /**
   * The file used to inject helpers and resolve paths.
   */
  _hub;

  /**
   * The default options to use with this instance when imports are added.
   */
  _defaultOpts: ImportOptions = {
    importedSource: null,
    importedType: "commonjs",
    importedInterop: "babel",
    importingInterop: "babel",
    ensureLiveReference: false,
    ensureNoContext: false,
  };

  constructor(path, importedSource, opts) {
    const programPath = path.find(p => p.isProgram());

    this._programPath = programPath;
    this._programScope = programPath.scope;
    this._hub = programPath.hub;

    this._defaultOpts = this._applyDefaults(importedSource, opts, true);
  }

  addDefault(importedSourceIn, opts) {
    return this.addNamed("default", importedSourceIn, opts);
  }

  addNamed(importName, importedSourceIn, opts) {
    assert(typeof importName === "string");

    return this._generateImport(
      this._applyDefaults(importedSourceIn, opts),
      importName,
    );
  }

  addNamespace(importedSourceIn, opts) {
    return this._generateImport(
      this._applyDefaults(importedSourceIn, opts),
      null,
    );
  }

  addSideEffect(importedSourceIn, opts) {
    return this._generateImport(
      this._applyDefaults(importedSourceIn, opts),
      false,
    );
  }

  _applyDefaults(importedSource, opts, isInit = false) {
    const optsList = [];
    if (typeof importedSource === "string") {
      optsList.push({ importedSource });
      optsList.push(opts);
    } else {
      assert(!opts, "Unexpected secondary arguments.");

      optsList.push(importedSource);
    }

    const newOpts = {
      ...this._defaultOpts,
    };
    for (const opts of optsList) {
      if (!opts) continue;
      Object.keys(newOpts).forEach(key => {
        if (opts[key] !== undefined) newOpts[key] = opts[key];
      });

      if (!isInit) {
        if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint;
        if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist;
      }
    }
    return newOpts;
  }

  _generateImport(opts, importName) {
    const isDefault = importName === "default";
    const isNamed = !!importName && !isDefault;
    const isNamespace = importName === null;

    const {
      importedSource,
      importedType,
      importedInterop,
      importingInterop,
      ensureLiveReference,
      ensureNoContext,
      nameHint,

      // Not meant for public usage. Allows code that absolutely must control
      // ordering to set a specific hoist value on the import nodes.
      blockHoist,
    } = opts;

    // Provide a hint for generateUidIdentifier for the local variable name
    // to use for the import, if the code will generate a simple assignment
    // to a variable.
    let name = nameHint || importName;

    const isMod = isModule(this._programPath);
    const isModuleForNode = isMod && importingInterop === "node";
    const isModuleForBabel = isMod && importingInterop === "babel";

    const builder = new ImportBuilder(
      importedSource,
      this._programScope,
      this._hub,
    );

    if (importedType === "es6") {
      if (!isModuleForNode && !isModuleForBabel) {
        throw new Error("Cannot import an ES6 module from CommonJS");
      }

      // import * as namespace from ''; namespace
      // import def from ''; def
      // import { named } from ''; named
      builder.import();
      if (isNamespace) {
        builder.namespace(nameHint || importedSource);
      } else if (isDefault || isNamed) {
        builder.named(name, importName);
      }
    } else if (importedType !== "commonjs") {
      throw new Error(`Unexpected interopType "${importedType}"`);
    } else if (importedInterop === "babel") {
      if (isModuleForNode) {
        // import _tmp from ''; var namespace = interopRequireWildcard(_tmp); namespace
        // import _tmp from ''; var def = interopRequireDefault(_tmp).default; def
        // import _tmp from ''; _tmp.named
        name = name !== "default" ? name : importedSource;
        const es6Default = `${importedSource}$es6Default`;

        builder.import();
        if (isNamespace) {
          builder
            .default(es6Default)
            .var(name || importedSource)
            .wildcardInterop();
        } else if (isDefault) {
          if (ensureLiveReference) {
            builder
              .default(es6Default)
              .var(name || importedSource)
              .defaultInterop()
              .read("default");
          } else {
            builder
              .default(es6Default)
              .var(name)
              .defaultInterop()
              .prop(importName);
          }
        } else if (isNamed) {
          builder.default(es6Default).read(importName);
        }
      } else if (isModuleForBabel) {
        // import * as namespace from ''; namespace
        // import def from ''; def
        // import { named } from ''; named
        builder.import();
        if (isNamespace) {
          builder.namespace(name || importedSource);
        } else if (isDefault || isNamed) {
          builder.named(name, importName);
        }
      } else {
        // var namespace = interopRequireWildcard(require(''));
        // var def = interopRequireDefault(require('')).default; def
        // var named = require('').named; named
        builder.require();
        if (isNamespace) {
          builder.var(name || importedSource).wildcardInterop();
        } else if ((isDefault || isNamed) && ensureLiveReference) {
          if (isDefault) {
            name = name !== "default" ? name : importedSource;
            builder.var(name).read(importName);
            builder.defaultInterop();
          } else {
            builder.var(importedSource).read(importName);
          }
        } else if (isDefault) {
          builder
            .var(name)
            .defaultInterop()
            .prop(importName);
        } else if (isNamed) {
          builder.var(name).prop(importName);
        }
      }
    } else if (importedInterop === "compiled") {
      if (isModuleForNode) {
        // import namespace from ''; namespace
        // import namespace from ''; namespace.default
        // import namespace from ''; namespace.named

        builder.import();
        if (isNamespace) {
          builder.default(name || importedSource);
        } else if (isDefault || isNamed) {
          builder.default(importedSource).read(name);
        }
      } else if (isModuleForBabel) {
        // import * as namespace from ''; namespace
        // import def from ''; def
        // import { named } from ''; named
        // Note: These lookups will break if the module has no __esModule set,
        // hence the warning that 'compiled' will not work on standard CommonJS.

        builder.import();
        if (isNamespace) {
          builder.namespace(name || importedSource);
        } else if (isDefault || isNamed) {
          builder.named(name, importName);
        }
      } else {
        // var namespace = require(''); namespace
        // var namespace = require(''); namespace.default
        // var namespace = require(''); namespace.named
        // var named = require('').named;
        builder.require();
        if (isNamespace) {
          builder.var(name || importedSource);
        } else if (isDefault || isNamed) {
          if (ensureLiveReference) {
            builder.var(importedSource).read(name);
          } else {
            builder.prop(importName).var(name);
          }
        }
      }
    } else if (importedInterop === "uncompiled") {
      if (isDefault && ensureLiveReference) {
        throw new Error("No live reference for commonjs default");
      }

      if (isModuleForNode) {
        // import namespace from ''; namespace
        // import def from ''; def;
        // import namespace from ''; namespace.named
        builder.import();
        if (isNamespace) {
          builder.default(name || importedSource);
        } else if (isDefault) {
          builder.default(name);
        } else if (isNamed) {
          builder.default(importedSource).read(name);
        }
      } else if (isModuleForBabel) {
        // import namespace from '';
        // import def from '';
        // import { named } from ''; named;
        // Note: These lookups will break if the module has __esModule set,
        // hence the warning that 'uncompiled' will not work on ES6 transpiled
        // to CommonJS.

        builder.import();
        if (isNamespace) {
          builder.default(name || importedSource);
        } else if (isDefault) {
          builder.default(name);
        } else if (isNamed) {
          builder.named(name, importName);
        }
      } else {
        // var namespace = require(''); namespace
        // var def = require(''); def
        // var namespace = require(''); namespace.named
        // var named = require('').named;
        builder.require();
        if (isNamespace) {
          builder.var(name || importedSource);
        } else if (isDefault) {
          builder.var(name);
        } else if (isNamed) {
          if (ensureLiveReference) {
            builder.var(importedSource).read(name);
          } else {
            builder.var(name).prop(importName);
          }
        }
      }
    } else {
      throw new Error(`Unknown importedInterop "${importedInterop}".`);
    }

    const { statements, resultName } = builder.done();

    this._insertStatements(statements, blockHoist);

    if (
      (isDefault || isNamed) &&
      ensureNoContext &&
      resultName.type !== "Identifier"
    ) {
      return t.sequenceExpression([t.numericLiteral(0), resultName]);
    }
    return resultName;
  }

  _insertStatements(statements, blockHoist = 3) {
    statements.forEach(node => {
      node._blockHoist = blockHoist;
    });

    const targetPath = this._programPath.get("body").filter(p => {
      const val = p.node._blockHoist;
      return Number.isFinite(val) && val < 4;
    })[0];

    if (targetPath) {
      targetPath.insertBefore(statements);
    } else {
      this._programPath.unshiftContainer("body", statements);
    }
  }
}
<commit_msg>Use .find instead of .filter to get targetPath in ImportInjector (#10608)<commit_after>import assert from "assert";
import * as t from "@babel/types";

import ImportBuilder from "./import-builder";
import isModule from "./is-module";

export type ImportOptions = {
  /**
   * The module being referenced.
   */
  importedSource: string | null,

  /**
   * The type of module being imported:
   *
   *  * 'es6'      - An ES6 module.
   *  * 'commonjs' - A CommonJS module. (Default)
   */
  importedType: "es6" | "commonjs",

  /**
   * The type of interop behavior for namespace/default/named when loading
   * CommonJS modules.
   *
   * ## 'babel' (Default)
   *
   * Load using Babel's interop.
   *
   * If '.__esModule' is true, treat as 'compiled', else:
   *
   * * Namespace: A copy of the module.exports with .default
   *     populated by the module.exports object.
   * * Default: The module.exports value.
   * * Named: The .named property of module.exports.
   *
   * The 'ensureLiveReference' has no effect on the liveness of these.
   *
   * ## 'compiled'
   *
   * Assume the module is ES6 compiled to CommonJS. Useful to avoid injecting
   * interop logic if you are confident that the module is a certain format.
   *
   * * Namespace: The root module.exports object.
   * * Default: The .default property of the namespace.
   * * Named: The .named property of the namespace.
   *
   * Will return erroneous results if the imported module is _not_ compiled
   * from ES6 with Babel.
   *
   * ## 'uncompiled'
   *
   * Assume the module is _not_ ES6 compiled to CommonJS. Used a simplified
   * access pattern that doesn't require additional function calls.
   *
   * Will return erroneous results if the imported module _is_ compiled
   * from ES6 with Babel.
   *
   * * Namespace: The module.exports object.
   * * Default: The module.exports object.
   * * Named: The .named property of module.exports.
   */
  importedInterop: "babel" | "node" | "compiled" | "uncompiled",

  /**
   * The type of CommonJS interop included in the environment that will be
   * loading the output code.
   *
   *  * 'babel' - CommonJS modules load with Babel's interop. (Default)
   *  * 'node'  - CommonJS modules load with Node's interop.
   *
   * See descriptions in 'importedInterop' for more details.
   */
  importingInterop: "babel" | "node",

  /**
   * Define whether we explicitly care that the import be a live reference.
   * Only applies when importing default and named imports, not the namespace.
   *
   *  * true  - Force imported values to be live references.
   *  * false - No particular requirements. Keeps the code simplest. (Default)
   */
  ensureLiveReference: boolean,

  /**
   * Define if we explicitly care that the result not be a property reference.
   *
   *  * true  - Force calls to exclude context. Useful if the value is going to
   *            be used as function callee.
   *  * false - No particular requirements for context of the access. (Default)
   */
  ensureNoContext: boolean,
};

/**
 * A general helper classes add imports via transforms. See README for usage.
 */
export default class ImportInjector {
  /**
   * The path used for manipulation.
   */
  _programPath: NodePath;

  /**
   * The scope used to generate unique variable names.
   */
  _programScope;

  /**
   * The file used to inject helpers and resolve paths.
   */
  _hub;

  /**
   * The default options to use with this instance when imports are added.
   */
  _defaultOpts: ImportOptions = {
    importedSource: null,
    importedType: "commonjs",
    importedInterop: "babel",
    importingInterop: "babel",
    ensureLiveReference: false,
    ensureNoContext: false,
  };

  constructor(path, importedSource, opts) {
    const programPath = path.find(p => p.isProgram());

    this._programPath = programPath;
    this._programScope = programPath.scope;
    this._hub = programPath.hub;

    this._defaultOpts = this._applyDefaults(importedSource, opts, true);
  }

  addDefault(importedSourceIn, opts) {
    return this.addNamed("default", importedSourceIn, opts);
  }

  addNamed(importName, importedSourceIn, opts) {
    assert(typeof importName === "string");

    return this._generateImport(
      this._applyDefaults(importedSourceIn, opts),
      importName,
    );
  }

  addNamespace(importedSourceIn, opts) {
    return this._generateImport(
      this._applyDefaults(importedSourceIn, opts),
      null,
    );
  }

  addSideEffect(importedSourceIn, opts) {
    return this._generateImport(
      this._applyDefaults(importedSourceIn, opts),
      false,
    );
  }

  _applyDefaults(importedSource, opts, isInit = false) {
    const optsList = [];
    if (typeof importedSource === "string") {
      optsList.push({ importedSource });
      optsList.push(opts);
    } else {
      assert(!opts, "Unexpected secondary arguments.");

      optsList.push(importedSource);
    }

    const newOpts = {
      ...this._defaultOpts,
    };
    for (const opts of optsList) {
      if (!opts) continue;
      Object.keys(newOpts).forEach(key => {
        if (opts[key] !== undefined) newOpts[key] = opts[key];
      });

      if (!isInit) {
        if (opts.nameHint !== undefined) newOpts.nameHint = opts.nameHint;
        if (opts.blockHoist !== undefined) newOpts.blockHoist = opts.blockHoist;
      }
    }
    return newOpts;
  }

  _generateImport(opts, importName) {
    const isDefault = importName === "default";
    const isNamed = !!importName && !isDefault;
    const isNamespace = importName === null;

    const {
      importedSource,
      importedType,
      importedInterop,
      importingInterop,
      ensureLiveReference,
      ensureNoContext,
      nameHint,

      // Not meant for public usage. Allows code that absolutely must control
      // ordering to set a specific hoist value on the import nodes.
      blockHoist,
    } = opts;

    // Provide a hint for generateUidIdentifier for the local variable name
    // to use for the import, if the code will generate a simple assignment
    // to a variable.
    let name = nameHint || importName;

    const isMod = isModule(this._programPath);
    const isModuleForNode = isMod && importingInterop === "node";
    const isModuleForBabel = isMod && importingInterop === "babel";

    const builder = new ImportBuilder(
      importedSource,
      this._programScope,
      this._hub,
    );

    if (importedType === "es6") {
      if (!isModuleForNode && !isModuleForBabel) {
        throw new Error("Cannot import an ES6 module from CommonJS");
      }

      // import * as namespace from ''; namespace
      // import def from ''; def
      // import { named } from ''; named
      builder.import();
      if (isNamespace) {
        builder.namespace(nameHint || importedSource);
      } else if (isDefault || isNamed) {
        builder.named(name, importName);
      }
    } else if (importedType !== "commonjs") {
      throw new Error(`Unexpected interopType "${importedType}"`);
    } else if (importedInterop === "babel") {
      if (isModuleForNode) {
        // import _tmp from ''; var namespace = interopRequireWildcard(_tmp); namespace
        // import _tmp from ''; var def = interopRequireDefault(_tmp).default; def
        // import _tmp from ''; _tmp.named
        name = name !== "default" ? name : importedSource;
        const es6Default = `${importedSource}$es6Default`;

        builder.import();
        if (isNamespace) {
          builder
            .default(es6Default)
            .var(name || importedSource)
            .wildcardInterop();
        } else if (isDefault) {
          if (ensureLiveReference) {
            builder
              .default(es6Default)
              .var(name || importedSource)
              .defaultInterop()
              .read("default");
          } else {
            builder
              .default(es6Default)
              .var(name)
              .defaultInterop()
              .prop(importName);
          }
        } else if (isNamed) {
          builder.default(es6Default).read(importName);
        }
      } else if (isModuleForBabel) {
        // import * as namespace from ''; namespace
        // import def from ''; def
        // import { named } from ''; named
        builder.import();
        if (isNamespace) {
          builder.namespace(name || importedSource);
        } else if (isDefault || isNamed) {
          builder.named(name, importName);
        }
      } else {
        // var namespace = interopRequireWildcard(require(''));
        // var def = interopRequireDefault(require('')).default; def
        // var named = require('').named; named
        builder.require();
        if (isNamespace) {
          builder.var(name || importedSource).wildcardInterop();
        } else if ((isDefault || isNamed) && ensureLiveReference) {
          if (isDefault) {
            name = name !== "default" ? name : importedSource;
            builder.var(name).read(importName);
            builder.defaultInterop();
          } else {
            builder.var(importedSource).read(importName);
          }
        } else if (isDefault) {
          builder
            .var(name)
            .defaultInterop()
            .prop(importName);
        } else if (isNamed) {
          builder.var(name).prop(importName);
        }
      }
    } else if (importedInterop === "compiled") {
      if (isModuleForNode) {
        // import namespace from ''; namespace
        // import namespace from ''; namespace.default
        // import namespace from ''; namespace.named

        builder.import();
        if (isNamespace) {
          builder.default(name || importedSource);
        } else if (isDefault || isNamed) {
          builder.default(importedSource).read(name);
        }
      } else if (isModuleForBabel) {
        // import * as namespace from ''; namespace
        // import def from ''; def
        // import { named } from ''; named
        // Note: These lookups will break if the module has no __esModule set,
        // hence the warning that 'compiled' will not work on standard CommonJS.

        builder.import();
        if (isNamespace) {
          builder.namespace(name || importedSource);
        } else if (isDefault || isNamed) {
          builder.named(name, importName);
        }
      } else {
        // var namespace = require(''); namespace
        // var namespace = require(''); namespace.default
        // var namespace = require(''); namespace.named
        // var named = require('').named;
        builder.require();
        if (isNamespace) {
          builder.var(name || importedSource);
        } else if (isDefault || isNamed) {
          if (ensureLiveReference) {
            builder.var(importedSource).read(name);
          } else {
            builder.prop(importName).var(name);
          }
        }
      }
    } else if (importedInterop === "uncompiled") {
      if (isDefault && ensureLiveReference) {
        throw new Error("No live reference for commonjs default");
      }

      if (isModuleForNode) {
        // import namespace from ''; namespace
        // import def from ''; def;
        // import namespace from ''; namespace.named
        builder.import();
        if (isNamespace) {
          builder.default(name || importedSource);
        } else if (isDefault) {
          builder.default(name);
        } else if (isNamed) {
          builder.default(importedSource).read(name);
        }
      } else if (isModuleForBabel) {
        // import namespace from '';
        // import def from '';
        // import { named } from ''; named;
        // Note: These lookups will break if the module has __esModule set,
        // hence the warning that 'uncompiled' will not work on ES6 transpiled
        // to CommonJS.

        builder.import();
        if (isNamespace) {
          builder.default(name || importedSource);
        } else if (isDefault) {
          builder.default(name);
        } else if (isNamed) {
          builder.named(name, importName);
        }
      } else {
        // var namespace = require(''); namespace
        // var def = require(''); def
        // var namespace = require(''); namespace.named
        // var named = require('').named;
        builder.require();
        if (isNamespace) {
          builder.var(name || importedSource);
        } else if (isDefault) {
          builder.var(name);
        } else if (isNamed) {
          if (ensureLiveReference) {
            builder.var(importedSource).read(name);
          } else {
            builder.var(name).prop(importName);
          }
        }
      }
    } else {
      throw new Error(`Unknown importedInterop "${importedInterop}".`);
    }

    const { statements, resultName } = builder.done();

    this._insertStatements(statements, blockHoist);

    if (
      (isDefault || isNamed) &&
      ensureNoContext &&
      resultName.type !== "Identifier"
    ) {
      return t.sequenceExpression([t.numericLiteral(0), resultName]);
    }
    return resultName;
  }

  _insertStatements(statements, blockHoist = 3) {
    statements.forEach(node => {
      node._blockHoist = blockHoist;
    });

    const targetPath = this._programPath.get("body").find(p => {
      const val = p.node._blockHoist;
      return Number.isFinite(val) && val < 4;
    });

    if (targetPath) {
      targetPath.insertBefore(statements);
    } else {
      this._programPath.unshiftContainer("body", statements);
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Created by yarden on 11/10/15.
 */

define(function(require) {

  var d3 = require('d3');
  var spec = require('config');

  var localWindow = null;
  var root = null;
  var data = null;
  var active = [];
  var mat;
  var valueSelector = 'min';
  var spec;

  var fields = {
    config:  {name: 'config',  type: 'category', values: [], sort: d3.ascending, selected: new Set()},
    dataset: {name: 'dataset', type: 'category', values: [], sort: d3.ascending, selected: new Set()},
    sim:     {name: 'sim',     type: 'category', values: [], sort: simSort, selected: new Set()},
    jobid:   {name: 'jobid',   type: 'category', values: [], sort: d3.ascending, selected: new Set()},
    color:   {name: 'color',   type: 'fixed', values: ['r', 'g', 'k', 'b'], selected: new Set(['r', 'g', 'k', 'b'])}
  };

  var specs = [
    {
      name: 'config/jobid',
      rows: [fields.config],
      cols: [fields.jobid]
    },
    {
      name: 'config,sim/dataset,jobid',
      rows: [fields.config, fields.sim],
      cols: [fields.dataset, fields.jobid]
    },
    {
      name: 'config,dataset,sim/color,jobid',
      rows: [fields.config, fields.dataset, fields.sim],
      cols: [fields.color, fields.jobid]
    }
  ];

  var filterValues = {};

  var VALUES_COLORMAP =["#4575b4", "#74add1", "#abd9e9", "#e0f3f8", "#ffffbf", "#fee090", "#fdae61", "#f46d43", "#d73027"];
  var value_scale = d3.scale.linear().domain([0, 0.5, 1]).range([0, 0.5, 1]);
  var scale = d3.scale.quantize().range(VALUES_COLORMAP);
  function color(v) { return scale(value_scale(v)); }

  var colorname = ['r', 'g', 'k', 'b'];

  function simSort(a,b) {
    a = +a.slice(3);
    b = +b.slice(3);
    return a -b;
  }

  // launch button on the main page
  d3.select('#show-compare')
    .on('click', function() {
      if (localWindow == null || localWindow.closed) {
        localWindow = window.open('compare.html', 'compare');
        d3.select(localWindow).on('load', init);
      }
      else {
        localWindow.focus();
      }
    });

  // init module only it is actually called
  function init() {
    root = localWindow.document.body;

    d3.select(root).select('#select-options')
      .on('change', function (d) { spec = specs[d3.select(this).property('selectedIndex')]; recompute(); })
      .selectAll('option')
      .data(specs)
      .enter()
        .append('option')
        .attr('value', function(d) {return d.name;})
        .text(function(d) { return d.name;});

    d3.csv('data/alldata.csv')
      .row(function(d) {
        //d.jobid = +d.jobid;
        d.color = colorname[d.color];
        d.min = +d.min;
        d.avg = +d.avg;
        d.max = +d.max;
        d.nonzero = +d.nonzero;
        d.navg = +d.navg;
        return d;
      })
      .get(function(error, rows) {
        if (error) {
          // TODO: better error message notification
          console.err(error);
        }
        else {
          d3.select(root).select('#size').text(rows.length);
          if (rows.length == 0) {
            // TODO: better message notification
            console.log('empty dataset');
            return;
          }
          data = rows;

          // TODO: use keys based on data. Issue: how to determine which fields are values
          var keys = ['min', 'avg', 'max', 'nzavg'];

          d3.select(root).select('#select-values')
            .on('change', selectValue)
            .selectAll('option')
            .data(keys)
            .enter()
              .append('option')

            .attr('value', function(d) {return d;})
            .text(function(d) { return d;});

          // init selection and render
          valueSelector = 'max';
          d3.select(root).select('#select-values')
            .property('value', valueSelector);

          setupFields();
          spec = specs[0];
          filter();
        }
      });
  }

  function setupFields() {
    collectValues(data);

    var li = d3.select(root).select('#info #fields').selectAll('li')
      .data(Object.keys(fields))
      .enter()
      .append('li');

    li.append('label')
      .attr('class', 'li-title')
      .text(function(d) {return d;});

    var entry = li.append('ul')
      .attr('class', 'values')
      .selectAll('li')
      .data(function(d) { return fields[d].values.map(function(v) { return [fields[d].name, v];});})
      .enter()
        .append('li')
        .attr('class', 'value');

    entry
      .append('input')
      .attr('type', 'checkbox')
      .property('name', function(d) {return d[0];})
      .property('value', function(d) { return d[1]; })
      .property('checked', true)
      .on('change', function(d) {
        var set = fields[d3.select(this).property('name')].selected;
        if (d3.select(this).property('checked')) set.add(d[1]);
        else set.delete(d[1]);
        filter();
      });

    entry
      .append('text')
      .text(function(d) { return d[1]});
  }

  function collectValues(rows) {
    Object.keys(fields).forEach(function(field) {
      if (fields[field].type == 'category') {
        var set = new Set();
        rows.forEach(function(row) {
          set.add(row[field]);
        });
        fields[field].values = Array.from(set).sort(fields[field].sort);
        fields[field].selected = new Set(fields[field].values);
      }
    });
  }

  function adjustColormap() {
    var max = d3.max(mat.values, function (d) { return d.values[valueSelector]; });
    value_scale.domain([0, max/2, max]);
  }

  function filter() {
    var keys = Object.keys(fields);
    var i, n = keys.length, key;
    active = data.filter(function(row) {
      for (i=0; i<n; i++) {
        key = keys[i];
        if (!fields[key].selected.has(row[key])) return false;
      }
      return true;
    });
    recompute();
  }

  function selectValue() {
    valueSelector = d3.select(this).property('value');
    adjustColormap();
    render(mat);
  }

  function recompute() {
    buildHeader(spec);
    mat = collect(spec,  aggregate(spec));
    adjustColormap();
    render(mat);
  }

  function aggregate(spec) {
    var nest = d3.nest();
    spec.rows.forEach(function(field) { nest.key(function(d) { return d[field.name];}).sortKeys(field.sort); } );
    spec.cols.forEach(function(field) { nest.key(function(d) { return d[field.name];}).sortKeys(field.sort); } );

    return nest.rollup(function(leaves) { return {
        min: d3.min(leaves, function(d) { return d.min; }),
        avg: d3.mean(leaves, function(d) { return d.avg; }),
        max: d3.max(leaves, function(d) { return d.max; }),
        //nonzero: d3.max(leaves, function(d) { return d.nonzero; }),
        nzavg: d3.sum(leaves, function(d) { return d.nzavg * d.nonzero; })/ d3.sum(leaves, function(d) { return d.nonzero; })
      }})
      .entries(active);
  }

  var header;
  var x0 = 20, y0 = 80;
  var dx = 1, dy = 1;
  var w = 15, h = 15;
  var fontSize = 15;
  var colHeight = 15;
  var lastRowWidth = 30;
  var x, y;

  function buildHeader(spec) {
    var root, entry, value, field;

    // collect
    header = {field: spec.cols[0], label: "", values: new Map()};
    active.forEach(function(row) {
      root = header;
      for (var i= 0, n=spec.cols.length; i<n; i++) {
        field = spec.cols[i];
        value = row[field.name];
        entry = root.values.get(value);
        if (!entry) {
          entry =  i<n-1 && {field: spec.cols[i+1], label: value, values: new Map()} || {label: value};
          root.values.set(value, entry);
        }
        root = entry;
      }
    });

    // assign location and size
    visit(header, x0+spec.rows.length*(w+dx)+lastRowWidth-w+5, y0);

    function visit(root, x, y) {
      root.x = x;
      root.y = y;
      if (root.values) {
        y += colHeight + dy;
        var keys = Array.from(root.values.keys()).sort(root.field.sort);
        keys.forEach(function (key) {
          x = visit(root.values.get(key), x, y)+dx;
        });
      } else {
        x += w+dx;
      }
      x -= dx;
      root.w = x - root.x;
      root.h = h;
      return x;
    }

  }

  function collect(spec, nodes) {
    x = x0;
    y = y0 + (spec.cols.length+1)*(colHeight+dy);
    var mat = {header: {rows:[], cols:[]}, values:[]};
    var max_value = 0;

    visit(spec.rows.length, spec.cols.length, nodes, header);
    return mat;

    function visit(nrows, ncols, nodes, header) {
      var i, n, node, nr = spec.rows.length, nc = spec.cols.length;
      if (nrows > 0) {
        for (i=0, n=nodes.length; i<n; i++) {
          node = nodes[i];
          node.label = node.key;
          node.x = x;
          node.y = y;
          x += +dx + (nrows == 1 ? lastRowWidth+5 : fontSize);
          node.last = nrows == 1;
          visit(nrows-1, ncols, node.values, header);
          if (nrows == 1) {
            y += h;
            node.w = lastRowWidth ;
            node.h = y - node.y - dy+1;
          } else {
            node.h = fontSize;
            node.w = y - node.y - dy;
          }
          x = node.x;
          y += dy;
          mat.header.rows.push(node);
        }
      }
      else {
        for (i=0, n=nodes.length; i<n; i++) {
          node = nodes[i];
          var pos = header.values.get(node.key);
          if (ncols == 1) {
            node.x = pos.x;
            node.y = y;
            node.w = w;
            node.h = h;
            x += w;
            mat.values.push(node);
          } else {
            visit(nrows, ncols-1, node.values, pos);
          }
          x += dx;
        }
      }
    }
  }

  function flatten(node) {
    var list = [];
    visit(node);
    list.shift();
    return list;

    function visit(node) {
      if (node) {
        list.push(node);
        if (node.values)
          node.values.forEach(function (node) { visit(node); });
      }
    }
  }

  function render(mat) {

    d3.select(root).select('#results').attr('height', y);

    var cols = d3.select(root).select('#results').selectAll('.col')
      .data(flatten(header));

    cols.enter()
      .append('div')
      .attr('class', 'col');

    cols
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y;})
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .style('overflow', 'hidden')
      .text(function(d) { return d.label;})
    ;

    cols.exit().remove();

    var list = [];
    for (var i= 0, n=spec.cols.length; i<n; i++) {
      list.push({x: header.x+header.w+dx+5, y: header.y+(i+1)*(colHeight+dy), w:40, h: fontSize, label: spec.cols[i].name });
    }

    var colText = d3.select(root).select('#results').selectAll('.colText')
      .data(list);

    colText.enter()
      .append('div')
      .attr('class', 'colText');

    colText
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y; })
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .text(function(d) { return d.label; });

    colText.exit().remove();

    var rows = d3.select(root).select('#results').selectAll('.row')
      .data(mat.header.rows);

    rows.enter()
      .append('div')
      .attr('class', 'row');

    rows
      .classed('rotate', function(d) { return !d.last; })
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y+ (d.last ? 0 : d.w);})
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .style('overflow', 'hidden')
      .text(function(d) { return d.label;})
    ;

    rows.exit().remove();

    var d3nodes = d3.select(root).select('#results').selectAll('.value')
      .data(mat.values);

    d3nodes.enter()
      .append('div')
      .attr('class', 'value');

    d3nodes
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y;})
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .style('background-color', function(d) { return color(d.values[valueSelector]); })
    ;

    d3nodes.exit().remove();
  }

  return {
  };

});<commit_msg>minor<commit_after>/**
 * Created by yarden on 11/10/15.
 */

define(function(require) {

  var d3 = require('d3');
  var spec = require('config');

  var localWindow = null;
  var root = null;
  var data = null;
  var active = [];
  var mat;
  var valueSelector = 'min';
  var spec;

  var fields = {
    config:  {name: 'config',  type: 'category', values: [], sort: d3.ascending, selected: new Set()},
    dataset: {name: 'dataset', type: 'category', values: [], sort: d3.ascending, selected: new Set()},
    sim:     {name: 'sim',     type: 'category', values: [], sort: simSort, selected: new Set()},
    jobid:   {name: 'jobid',   type: 'category', values: [], sort: d3.ascending, selected: new Set()},
    color:   {name: 'color',   type: 'fixed', values: ['r', 'g', 'k', 'b'], selected: new Set(['r', 'g', 'k', 'b'])}
  };

  var specs = [
    {
      name: 'config/jobid',
      rows: [fields.config],
      cols: [fields.jobid]
    },
    {
      name: 'config,sim/dataset,jobid',
      rows: [fields.config, fields.sim],
      cols: [fields.dataset, fields.jobid]
    },
    {
      name: 'config,dataset,sim/color,jobid',
      rows: [fields.config, fields.dataset, fields.sim],
      cols: [fields.color, fields.jobid]
    }
  ];

  var filterValues = {};

  var VALUES_COLORMAP =["#4575b4", "#74add1", "#abd9e9", "#e0f3f8", "#ffffbf", "#fee090", "#fdae61", "#f46d43", "#d73027"];
  var value_scale = d3.scale.linear().domain([0, 0.5, 1]).range([0, 0.5, 1]);
  var scale = d3.scale.quantize().range(VALUES_COLORMAP);
  function color(v) { return scale(value_scale(v)); }

  var colorname = ['r', 'g', 'k', 'b'];

  function simSort(a,b) {
    a = +a.slice(3);
    b = +b.slice(3);
    return a -b;
  }

  // launch button on the main page
  d3.select('#show-compare')
    .on('click', function() {
      if (localWindow == null || localWindow.closed) {
        localWindow = window.open('compare.html', 'compare');
        d3.select(localWindow).on('load', init);
      }
      else {
        localWindow.focus();
      }
    });

  // init module only it is actually called
  function init() {
    root = localWindow.document.body;

    d3.select(root).select('#select-options')
      .on('change', function (d) { spec = specs[d3.select(this).property('selectedIndex')]; recompute(); })
      .selectAll('option')
      .data(specs)
      .enter()
        .append('option')
        .attr('value', function(d) {return d.name;})
        .text(function(d) { return d.name;});

    d3.csv('data/alldata.csv')
      .row(function(d) {
        //d.jobid = +d.jobid;
        d.color = colorname[d.color];
        d.min = +d.min;
        d.avg = +d.avg;
        d.max = +d.max;
        d.nonzero = +d.nonzero;
        d.navg = +d.navg;
        return d;
      })
      .get(function(error, rows) {
        if (error) {
          // TODO: better error message notification
          console.err(error);
        }
        else {
          d3.select(root).select('#size').text(rows.length);
          if (rows.length == 0) {
            // TODO: better message notification
            console.log('empty dataset');
            return;
          }
          data = rows;

          // TODO: use keys based on data. Issue: how to determine which fields are values
          var keys = ['min', 'avg', 'max', 'nzavg'];

          d3.select(root).select('#select-values')
            .on('change', selectValue)
            .selectAll('option')
            .data(keys)
            .enter()
              .append('option')

            .attr('value', function(d) {return d;})
            .text(function(d) { return d;});

          // init selection and render
          valueSelector = 'max';
          d3.select(root).select('#select-values')
            .property('value', valueSelector);

          setupFields();
          spec = specs[0];
          filter();
        }
      });
  }

  function setupFields() {
    collectValues(data);

    var li = d3.select(root).select('#info #fields').selectAll('li')
      .data(Object.keys(fields))
      .enter()
      .append('li');

    li.append('label')
      .attr('class', 'li-title')
      .text(function(d) {return d;});

    var entry = li.append('ul')
      .attr('class', 'values')
      .selectAll('li')
      .data(function(d) { return fields[d].values.map(function(v) { return [fields[d].name, v];});})
      .enter()
        .append('li')
        .attr('class', 'value');

    entry
      .append('input')
      .attr('type', 'checkbox')
      .property('name', function(d) {return d[0];})
      .property('value', function(d) { return d[1]; })
      .property('checked', true)
      .on('change', function(d) {
        var set = fields[d3.select(this).property('name')].selected;
        if (d3.select(this).property('checked')) set.add(d[1]);
        else set.delete(d[1]);
        filter();
      });

    entry
      .append('text')
      .text(function(d) { return d[1]});
  }

  function collectValues(rows) {
    Object.keys(fields).forEach(function(field) {
      if (fields[field].type == 'category') {
        var set = new Set();
        rows.forEach(function(row) {
          set.add(row[field]);
        });
        fields[field].values = Array.from(set).sort(fields[field].sort);
        fields[field].selected = new Set(fields[field].values);
      }
    });
  }

  function adjustColormap() {
    var max = d3.max(mat.values, function (d) { return d.values[valueSelector]; });
    value_scale.domain([0, max/2, max]);
  }

  function filter() {
    var keys = Object.keys(fields);
    var i, n = keys.length, key;
    active = data.filter(function(row) {
      for (i=0; i<n; i++) {
        key = keys[i];
        if (!fields[key].selected.has(row[key])) return false;
      }
      return true;
    });
    recompute();
  }

  function selectValue() {
    valueSelector = d3.select(this).property('value');
    adjustColormap();
    render(mat);
  }

  function recompute() {
    buildHeader(spec);
    mat = collect(spec,  aggregate(spec));
    adjustColormap();
    render(mat);
  }

  function aggregate(spec) {
    var nest = d3.nest();
    spec.rows.forEach(function(field) { nest.key(function(d) { return d[field.name];}).sortKeys(field.sort); } );
    spec.cols.forEach(function(field) { nest.key(function(d) { return d[field.name];}).sortKeys(field.sort); } );

    return nest.rollup(function(leaves) { return {
        min: d3.min(leaves, function(d) { return d.min; }),
        avg: d3.mean(leaves, function(d) { return d.avg; }),
        max: d3.max(leaves, function(d) { return d.max; }),
        //nonzero: d3.max(leaves, function(d) { return d.nonzero; }),
        nzavg: d3.sum(leaves, function(d) { return d.nzavg * d.nonzero; })/ d3.sum(leaves, function(d) { return d.nonzero; })
      }})
      .entries(active);
  }

  var header;
  var x0 = 20, y0 = 20;
  var dx = 1, dy = 1;
  var w = 15, h = 15;
  var fontSize = 15;
  var colHeight = 15;
  var lastRowWidth = 30;
  var x, y;

  function buildHeader(spec) {
    var root, entry, value, field;

    // collect
    header = {field: spec.cols[0], label: "", values: new Map()};
    active.forEach(function(row) {
      root = header;
      for (var i= 0, n=spec.cols.length; i<n; i++) {
        field = spec.cols[i];
        value = row[field.name];
        entry = root.values.get(value);
        if (!entry) {
          entry =  i<n-1 && {field: spec.cols[i+1], label: value, values: new Map()} || {label: value};
          root.values.set(value, entry);
        }
        root = entry;
      }
    });

    // assign location and size
    visit(header, x0+spec.rows.length*(w+dx)+lastRowWidth-w+5, y0);

    function visit(root, x, y) {
      root.x = x;
      root.y = y;
      if (root.values) {
        y += colHeight + dy;
        var keys = Array.from(root.values.keys()).sort(root.field.sort);
        keys.forEach(function (key) {
          x = visit(root.values.get(key), x, y)+dx;
        });
      } else {
        x += w+dx;
      }
      x -= dx;
      root.w = x - root.x;
      root.h = h;
      return x;
    }

  }

  function collect(spec, nodes) {
    x = x0;
    y = y0 + (spec.cols.length+1)*(colHeight+dy);
    var mat = {header: {rows:[], cols:[]}, values:[]};
    var max_value = 0;

    visit(spec.rows.length, spec.cols.length, nodes, header);
    return mat;

    function visit(nrows, ncols, nodes, header) {
      var i, n, node, nr = spec.rows.length, nc = spec.cols.length;
      if (nrows > 0) {
        for (i=0, n=nodes.length; i<n; i++) {
          node = nodes[i];
          node.label = node.key;
          node.x = x;
          node.y = y;
          x += +dx + (nrows == 1 ? lastRowWidth+5 : fontSize);
          node.last = nrows == 1;
          visit(nrows-1, ncols, node.values, header);
          if (nrows == 1) {
            y += h;
            node.w = lastRowWidth ;
            node.h = y - node.y - dy+1;
          } else {
            node.h = fontSize;
            node.w = y - node.y - dy;
          }
          x = node.x;
          y += dy;
          mat.header.rows.push(node);
        }
      }
      else {
        for (i=0, n=nodes.length; i<n; i++) {
          node = nodes[i];
          var pos = header.values.get(node.key);
          if (ncols == 1) {
            node.x = pos.x;
            node.y = y;
            node.w = w;
            node.h = h;
            x += w;
            mat.values.push(node);
          } else {
            visit(nrows, ncols-1, node.values, pos);
          }
          x += dx;
        }
      }
    }
  }

  function flatten(node) {
    var list = [];
    visit(node);
    list.shift();
    return list;

    function visit(node) {
      if (node) {
        list.push(node);
        if (node.values)
          node.values.forEach(function (node) { visit(node); });
      }
    }
  }

  function render(mat) {

    d3.select(root).select('#results').attr('height', y);

    var cols = d3.select(root).select('#results').selectAll('.col')
      .data(flatten(header));

    cols.enter()
      .append('div')
      .attr('class', 'col');

    cols
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y;})
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .style('overflow', 'hidden')
      .text(function(d) { return d.label;})
    ;

    cols.exit().remove();

    var list = [];
    for (var i= 0, n=spec.cols.length; i<n; i++) {
      list.push({x: header.x+header.w+dx+5, y: header.y+(i+1)*(colHeight+dy), w:40, h: fontSize, label: spec.cols[i].name });
    }

    var colText = d3.select(root).select('#results').selectAll('.colText')
      .data(list);

    colText.enter()
      .append('div')
      .attr('class', 'colText');

    colText
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y; })
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .text(function(d) { return d.label; });

    colText.exit().remove();

    var rows = d3.select(root).select('#results').selectAll('.row')
      .data(mat.header.rows);

    rows.enter()
      .append('div')
      .attr('class', 'row');

    rows
      .classed('rotate', function(d) { return !d.last; })
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y+ (d.last ? 0 : d.w);})
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .style('overflow', 'hidden')
      .text(function(d) { return d.label;})
    ;

    rows.exit().remove();

    var d3nodes = d3.select(root).select('#results').selectAll('.value')
      .data(mat.values);

    d3nodes.enter()
      .append('div')
      .attr('class', 'value');

    d3nodes
      .style('left', function(d) { return d.x;})
      .style('top', function(d) { return d.y;})
      .style('width', function(d) { return d.w;})
      .style('height', function(d) { return d.h;})
      .style('background-color', function(d) { return color(d.values[valueSelector]); })
    ;

    d3nodes.exit().remove();
  }

  return {
  };

});<|endoftext|>


<commit_before>$(function () {
  function placesScopeCondition(){
    if(window.placesScope.length)
      return " i.place_id IN (" + window.placesScope + ")";
    else
      return " 1=1";
  }

  function filterOutliers(someArray) {
    // Copy the values, rather than operating on references to existing values
    var values = someArray.slice(0);

    // Then sort
    values.sort( function(a, b) {
            return a - b;
         });

    /* Then find a generous IQR. This is generous because if (values.length / 4)
     * is not an int, then really you should average the two elements on either
     * side to find q1.
     */
    var q1 = values[Math.floor((values.length / 4))];
    // Likewise for q3.
    var q3 = values[Math.ceil((values.length * (3 / 4)))];
    var iqr = q3 - q1;

    // Then find min and max values
    var maxValue = q3 + iqr*1.5;
    var minValue = q1 - iqr*1.5;

    // Then filter anything beyond or beneath these values.
    var filteredValues = values.filter(function(x) {
        return (x < maxValue) && (x > minValue);
    });

    // Then return
    return filteredValues;
  }

  function renderMapIndicator(layer, vis){
    $('[data-indicator]').click(function(e){
      $('#map .overlay').css({
        'display': 'block'
      });

      $('#map .cartodb-tiles-loader').css({
        'position': 'relative',
        'z-index': '-1'
      });

      $('.cartodb-tooltip').hide();
      var year = $('body').data('year');
      var indicator = $('.metric.selected').data('indicator');
      layer.show();

      var sql = new cartodb.SQL({ user: 'gobierto' });
      sql.execute("SELECT {{indicator}} as value FROM indicators_{{year}} as i WHERE" + placesScopeCondition(), { indicator: indicator, year: year })
        .done(function(data) {
          var customColors = colors.slice(0);

          // push all the values into an array
          var values = [];
          data.rows.forEach(function(row,i) {
            values.push(row['value']);
          });
          values = filterOutliers(values);

          var clusters = ss.ckmeans(values, customColors.length);
          var ranges = clusters.map(function(cluster){
            return [cluster[0],cluster.pop()];
          });

          var css = "#indicators_2016 [ value = 0]  { polygon-fill: #ffffff; } ";
          if(indicator === 'debt'){
            css = "#indicators_2016 [ value = 0]  { polygon-fill: "+customColors[0]+"; } ";
          }
          ranges.forEach(function(range,i){
            var value = range[0];
            if(i === 0)
              value = 0;
            var color = customColors[i];
            css += "#indicators_2016 [value>"+value + "] {polygon-fill:" + color + "}\n";
          });

          var query = "select i.cartodb_id, t.place_id as place_id, t.nameunit as name, t.the_geom, " +
                      "t.the_geom_webmercator, i."+indicator+" as value, TO_CHAR(i."+indicator+", '999G999G990') as valuef, " +
                      "'"+indicators[indicator].name+"' as indicator_name, '"+indicators[indicator].unit+"' as unit" +
                      " from ign_spanish_adm3_municipalities_displaced_canary as t full join indicators_"+year+" as i " +
                      " on i.place_id = t.place_id WHERE" + placesScopeCondition();
          layer.setSQL(query);

          layer.setCartoCSS(css);
          layer.show();

          var lc = $('#legend-container');
          lc.html($('#legend').html());
          lc.find('.min').html('< ' + accounting.formatNumber(ranges[0][1], 0) + ' ' + indicators[indicator].unit);
          lc.find('.max').html('> ' + accounting.formatNumber(ranges[ranges.length-1][0], 0) + ' ' + indicators[indicator].unit);
          customColors.forEach(function(color){
            var c = $('

');
            lc.find('.colors').append(c);
          });
        })
      .error(function(errors) {
        console.log("errors:" + errors);
      });
    });
  }

  function renderMapBudgetLine(layer, vis){
    $(document).on('renderBudgetLineCategory', function(e){
      $('#map .overlay').css({
        'display': 'block'
      });

      $('#map .cartodb-tiles-loader').css({
        'position': 'relative',
        'z-index': '-1'
      });

      $('.cartodb-tooltip').hide();
      $('.metric').removeClass('selected');
      var year = $('body').data('year');

      layer.show();

      var sql = new cartodb.SQL({ user: 'gobierto' });
      sql.execute("SELECT i.amount_per_inhabitant as value FROM planned_budgets_{{year}} as i WHERE code='"+e.code+"' AND kind='" + e.kind + "' AND area='" + e.area[0] + "' AND" + placesScopeCondition(), { year: year })
        .done(function(data) {
          // push all the values into an array
          var values = [];
          data.rows.forEach(function(row,i) {
            values.push(row['value']);
          });
          values = filterOutliers(values);

          var clusters = ss.ckmeans(values, colors.length);
          var ranges = clusters.map(function(cluster){
            return [cluster[0],cluster.pop()];
          });

          var css = "#indicators_2016 [ value = 0]  { polygon-fill: #ffffff; } ";
          ranges.forEach(function(range,i){
            var value = range[0]
            var color = colors[i];
            css += "#indicators_2016 [value>"+value + "] {polygon-fill:" + color + "}\n";
          });

          var query = "select i.cartodb_id, t.place_id as place_id, t.nameunit as name, t.the_geom, t.the_geom_webmercator, " +
            " i.code, i.kind, i.area, i.amount, i.amount_per_inhabitant as value," +
            " TO_CHAR(i.amount_per_inhabitant, '999G999G990') as valuef, " +
            " '"+indicators['gasto_por_habitante'].name+"' as indicator_name, '"+indicators['gasto_por_habitante'].unit+"' as unit" +
            " from ign_spanish_adm3_municipalities_displaced_canary as t full join planned_budgets_"+year+" as i on i.place_id = t.place_id" +
            " WHERE code='"+e.code+"' AND kind='" + e.kind + "' AND area='" + e.area[0] + "' AND" + placesScopeCondition();

          layer.setSQL(query);

          layer.setCartoCSS(css);
          layer.show();

          var lc = $('#legend-container');
          lc.html($('#legend').html());
          lc.find('.min').html('< ' + accounting.formatNumber(ranges[0][1], 0) + ' ' + indicators['gasto_por_habitante'].unit);
          lc.find('.max').html('> ' + accounting.formatNumber(ranges[ranges.length-1][0], 0) + ' ' + indicators['gasto_por_habitante'].unit);
          colors.forEach(function(color){
            var c = $('

');
            lc.find('.colors').append(c);
          });
        })
        .error(function(errors) {
          console.log("errors:" + errors);
        });

      $('#legend-container').html($('#legend').html());
    });
  }

  if($('#map').length){

    var colors = ['#ffffcc','#c7e9b4','#7fcdbb','#41b6c4','#1d91c0','#225ea8','#0c2c84'];
    var indicators = {
      gasto_por_habitante: {
        name: I18n.t('gobierto_budgets.pages.map.expense_per_inhabitant'),
        unit: '€/hab',
      },
      gasto_total: {
        name: I18n.t('gobierto_budgets.pages.map.expense'),
        unit: '€',
      },
      planned_vs_executed: {
        name: I18n.t('gobierto_budgets.pages.map.planned_vs_executed'),
        unit: '%',
      },
      debt: {
        name: I18n.t('gobierto_budgets.pages.map.debt'),
        unit: '€',
      },
      population: {
        name: I18n.t('gobierto_budgets.pages.map.population'),
        unit: ' ' + I18n.t('gobierto_budgets.pages.map.people'),
      }
    };

    cartodb.createVis('map', 'https://gobierto.carto.com/api/v2/viz/205616b2-b893-11e6-b070-0e233c30368f/viz.json', {
      shareable: false,
      title: false,
      description: false,
      search: false,
      tiles_loader: true,
      center_lat: window.mapSettings.centerLat,
      center_lon: window.mapSettings.centerLon,
      zoom: window.mapSettings.zoomLevel,
      zoomControl: true,
      loaderControl: true
    })
    .done(function(vis, layers) {
      var sublayer = layers[1].getSubLayer(0);
      vis.addOverlay({
        type: 'tooltip',
        layer: sublayer,
        template: $('#infowindow_template').html(),
        position: 'bottom|right',
        fields: [{ name: 'name', value: 'value', valuef: 'valuef', indicator_name: 'indicator_name', unit: 'unit', place_id: 'place_id' }]
      });
      sublayer.setInteractivity('name, value,valuef,indicator_name,unit,place_id');
      renderMapIndicator(sublayer, vis);
      renderMapBudgetLine(sublayer, vis);
      $('[data-indicator].selected').click();

      // On load, hide the overlay and reset the tile spinner
      layers[1].on("load", function() {
        $('#map .overlay').css({
          'display': 'none'
        });

        $('#map .cartodb-tiles-loader').css({
          'position': 'initial',
          'z-index': '0'
        });
      });

      var year = $('body').data('year');
      sublayer.on('featureClick', function(e, latlng, pos, data, subLayerIndex) {
        window.location.href = "/places/" + data.place_id + "/" + year + "/redirect";
      });
    })
    .error(function(err) {
      console.log(err);
    });

    $('.metric').on('click', function(e){
      e.preventDefault();
      $('.metric').removeClass('selected');
      $('[data-category-code]').removeClass('active');
      $(this).addClass('selected');
    });
  }
});
<commit_msg>Remove map attribution when places scoped<commit_after>$(function () {
  function placesScopeCondition(){
    if(window.placesScope.length)
      return " i.place_id IN (" + window.placesScope + ")";
    else
      return " 1=1";
  }

  function filterOutliers(someArray) {
    // Copy the values, rather than operating on references to existing values
    var values = someArray.slice(0);

    // Then sort
    values.sort( function(a, b) {
            return a - b;
         });

    /* Then find a generous IQR. This is generous because if (values.length / 4)
     * is not an int, then really you should average the two elements on either
     * side to find q1.
     */
    var q1 = values[Math.floor((values.length / 4))];
    // Likewise for q3.
    var q3 = values[Math.ceil((values.length * (3 / 4)))];
    var iqr = q3 - q1;

    // Then find min and max values
    var maxValue = q3 + iqr*1.5;
    var minValue = q1 - iqr*1.5;

    // Then filter anything beyond or beneath these values.
    var filteredValues = values.filter(function(x) {
        return (x < maxValue) && (x > minValue);
    });

    // Then return
    return filteredValues;
  }

  function renderMapIndicator(layer, vis){
    $('[data-indicator]').click(function(e){
      $('#map .overlay').css({
        'display': 'block'
      });

      $('#map .cartodb-tiles-loader').css({
        'position': 'relative',
        'z-index': '-1'
      });

      $('.cartodb-tooltip').hide();
      var year = $('body').data('year');
      var indicator = $('.metric.selected').data('indicator');
      layer.show();

      var sql = new cartodb.SQL({ user: 'gobierto' });
      sql.execute("SELECT {{indicator}} as value FROM indicators_{{year}} as i WHERE" + placesScopeCondition(), { indicator: indicator, year: year })
        .done(function(data) {
          var customColors = colors.slice(0);

          // push all the values into an array
          var values = [];
          data.rows.forEach(function(row,i) {
            values.push(row['value']);
          });
          values = filterOutliers(values);

          var clusters = ss.ckmeans(values, customColors.length);
          var ranges = clusters.map(function(cluster){
            return [cluster[0],cluster.pop()];
          });

          var css = "#indicators_2016 [ value = 0]  { polygon-fill: #ffffff; } ";
          if(indicator === 'debt'){
            css = "#indicators_2016 [ value = 0]  { polygon-fill: "+customColors[0]+"; } ";
          }
          ranges.forEach(function(range,i){
            var value = range[0];
            if(i === 0)
              value = 0;
            var color = customColors[i];
            css += "#indicators_2016 [value>"+value + "] {polygon-fill:" + color + "}\n";
          });

          var query = "select i.cartodb_id, t.place_id as place_id, t.nameunit as name, t.the_geom, " +
                      "t.the_geom_webmercator, i."+indicator+" as value, TO_CHAR(i."+indicator+", '999G999G990') as valuef, " +
                      "'"+indicators[indicator].name+"' as indicator_name, '"+indicators[indicator].unit+"' as unit" +
                      " from ign_spanish_adm3_municipalities_displaced_canary as t full join indicators_"+year+" as i " +
                      " on i.place_id = t.place_id WHERE" + placesScopeCondition();
          layer.setSQL(query);

          layer.setCartoCSS(css);
          layer.show();

          var lc = $('#legend-container');
          lc.html($('#legend').html());
          lc.find('.min').html('< ' + accounting.formatNumber(ranges[0][1], 0) + ' ' + indicators[indicator].unit);
          lc.find('.max').html('> ' + accounting.formatNumber(ranges[ranges.length-1][0], 0) + ' ' + indicators[indicator].unit);
          customColors.forEach(function(color){
            var c = $('

');
            lc.find('.colors').append(c);
          });
        })
      .error(function(errors) {
        console.log("errors:" + errors);
      });
    });
  }

  function renderMapBudgetLine(layer, vis){
    $(document).on('renderBudgetLineCategory', function(e){
      $('#map .overlay').css({
        'display': 'block'
      });

      $('#map .cartodb-tiles-loader').css({
        'position': 'relative',
        'z-index': '-1'
      });

      $('.cartodb-tooltip').hide();
      $('.metric').removeClass('selected');
      var year = $('body').data('year');

      layer.show();

      var sql = new cartodb.SQL({ user: 'gobierto' });
      sql.execute("SELECT i.amount_per_inhabitant as value FROM planned_budgets_{{year}} as i WHERE code='"+e.code+"' AND kind='" + e.kind + "' AND area='" + e.area[0] + "' AND" + placesScopeCondition(), { year: year })
        .done(function(data) {
          // push all the values into an array
          var values = [];
          data.rows.forEach(function(row,i) {
            values.push(row['value']);
          });
          values = filterOutliers(values);

          var clusters = ss.ckmeans(values, colors.length);
          var ranges = clusters.map(function(cluster){
            return [cluster[0],cluster.pop()];
          });

          var css = "#indicators_2016 [ value = 0]  { polygon-fill: #ffffff; } ";
          ranges.forEach(function(range,i){
            var value = range[0]
            var color = colors[i];
            css += "#indicators_2016 [value>"+value + "] {polygon-fill:" + color + "}\n";
          });

          var query = "select i.cartodb_id, t.place_id as place_id, t.nameunit as name, t.the_geom, t.the_geom_webmercator, " +
            " i.code, i.kind, i.area, i.amount, i.amount_per_inhabitant as value," +
            " TO_CHAR(i.amount_per_inhabitant, '999G999G990') as valuef, " +
            " '"+indicators['gasto_por_habitante'].name+"' as indicator_name, '"+indicators['gasto_por_habitante'].unit+"' as unit" +
            " from ign_spanish_adm3_municipalities_displaced_canary as t full join planned_budgets_"+year+" as i on i.place_id = t.place_id" +
            " WHERE code='"+e.code+"' AND kind='" + e.kind + "' AND area='" + e.area[0] + "' AND" + placesScopeCondition();

          layer.setSQL(query);

          layer.setCartoCSS(css);
          layer.show();

          var lc = $('#legend-container');
          lc.html($('#legend').html());
          lc.find('.min').html('< ' + accounting.formatNumber(ranges[0][1], 0) + ' ' + indicators['gasto_por_habitante'].unit);
          lc.find('.max').html('> ' + accounting.formatNumber(ranges[ranges.length-1][0], 0) + ' ' + indicators['gasto_por_habitante'].unit);
          colors.forEach(function(color){
            var c = $('

');
            lc.find('.colors').append(c);
          });
        })
        .error(function(errors) {
          console.log("errors:" + errors);
        });

      $('#legend-container').html($('#legend').html());
    });
  }

  if($('#map').length){

    var colors = ['#ffffcc','#c7e9b4','#7fcdbb','#41b6c4','#1d91c0','#225ea8','#0c2c84'];
    var indicators = {
      gasto_por_habitante: {
        name: I18n.t('gobierto_budgets.pages.map.expense_per_inhabitant'),
        unit: '€/hab',
      },
      gasto_total: {
        name: I18n.t('gobierto_budgets.pages.map.expense'),
        unit: '€',
      },
      planned_vs_executed: {
        name: I18n.t('gobierto_budgets.pages.map.planned_vs_executed'),
        unit: '%',
      },
      debt: {
        name: I18n.t('gobierto_budgets.pages.map.debt'),
        unit: '€',
      },
      population: {
        name: I18n.t('gobierto_budgets.pages.map.population'),
        unit: ' ' + I18n.t('gobierto_budgets.pages.map.people'),
      }
    };

    cartodb.createVis('map', 'https://gobierto.carto.com/api/v2/viz/205616b2-b893-11e6-b070-0e233c30368f/viz.json', {
      shareable: false,
      title: false,
      description: false,
      search: false,
      tiles_loader: true,
      center_lat: window.mapSettings.centerLat,
      center_lon: window.mapSettings.centerLon,
      zoom: window.mapSettings.zoomLevel,
      zoomControl: true,
      loaderControl: true
    })
    .done(function(vis, layers) {
      var sublayer = layers[1].getSubLayer(0);
      vis.addOverlay({
        type: 'tooltip',
        layer: sublayer,
        template: $('#infowindow_template').html(),
        position: 'bottom|right',
        fields: [{ name: 'name', value: 'value', valuef: 'valuef', indicator_name: 'indicator_name', unit: 'unit', place_id: 'place_id' }]
      });
      sublayer.setInteractivity('name, value,valuef,indicator_name,unit,place_id');
      renderMapIndicator(sublayer, vis);
      renderMapBudgetLine(sublayer, vis);
      $('[data-indicator].selected').click();

      // On load, hide the overlay and reset the tile spinner
      layers[1].on("load", function() {
        $('#map .overlay').css({
          'display': 'none'
        });

        $('#map .cartodb-tiles-loader').css({
          'position': 'initial',
          'z-index': '0'
        });
      });

      var year = $('body').data('year');
      sublayer.on('featureClick', function(e, latlng, pos, data, subLayerIndex) {
        window.location.href = "/places/" + data.place_id + "/" + year + "/redirect";
      });

      // If there is a placesScop, remove Spain attribution
      if(window.placesScope.length > 0 && $('.leaflet-control-attribution').length){
        var str = $('.leaflet-control-attribution').html().replace(", © IGN España", "");
        $('.leaflet-control-attribution').html(str);
      }
    })
    .error(function(err) {
      console.log(err);
    });

    $('.metric').on('click', function(e){
      e.preventDefault();
      $('.metric').removeClass('selected');
      $('[data-category-code]').removeClass('active');
      $(this).addClass('selected');
    });
  }
});
<|endoftext|>


<commit_before>/* globals define */

/**
 * BoardView is basically a grid layout with a bunch of surfaces
 */
define(function(require, exports, module) {
  var View          = require('famous/core/View');
  var Surface       = require('famous/core/Surface');
  var Transform     = require('famous/core/Transform');
  var StateModifier = require('famous/modifiers/StateModifier');
  var GridLayout    = require('famous/view/GridLayout');

  function _createBackground() {
    var bgSurface = new Surface({
      properties: {
        backgroundColor: 'black'
      }
    });

    this.add(bgSurface);
  }

  function BoardView() {
    View.apply(this, arguments);

    _createBackground.call(this);
  }

  BoardView.prototype = Object.create(View.prototype);
  BoardView.prototype.constructor = BoardView;

  BoardView.DEFAULT_OPTIONS = {};

  module.exports = BoardView;
});
<commit_msg>added GridLayout to BoardView<commit_after>/* globals define */

/**
 * BoardView is basically a grid layout with a bunch of surfaces
 */
define(function(require, exports, module) {
  var View          = require('famous/core/View');
  var Surface       = require('famous/core/Surface');
  var Transform     = require('famous/core/Transform');
  var StateModifier = require('famous/modifiers/StateModifier');
  var GridLayout    = require('famous/views/GridLayout');

  var boardDimensions = [5,7];

  function _createBackground() {
    var bgSurface = new Surface({
      properties: {
        backgroundColor: 'black'
      }
    });

    this.add(bgSurface);
  }

  function _createSurfaces() {
    var size = boardDimensions[0] * boardDimensions[1];
    var surfaces = [];
    for(var i = 0; i < size; i++){
      surfaces.push(new Surface({
        content: 'panel ' + (i + 1),
        size: undefined,
        properties: {
          color: 'black',
          backgroundColor: 'hsl(100, 100%, 100%)',
          textAlign: 'center'
        }

      }));
    }

    return surfaces;
  }

  function _createGrid(dimensions) {
    var grid = new GridLayout({
      dimensions: dimensions
    });

    var surfaces = _createSurfaces();
    grid.sequenceFrom(surfaces);
    this.add(grid);

  }

  function BoardView() {
    View.apply(this, arguments);

    // add background
    _createBackground.call(this);
    // add grid
    _createGrid.call(this, boardDimensions);
  }

  BoardView.prototype = Object.create(View.prototype);
  BoardView.prototype.constructor = BoardView;

  BoardView.DEFAULT_OPTIONS = {};

  module.exports = BoardView;
});
<|endoftext|>


<commit_before>function MaterialsFilePicker(callback) {
  this.doneCallback = callback;
  this.selectedMaterials = {};
  this.treeElement = $('#file-picker-tree');

  var courseId = gon.course;
  var that = this;
  $.ajax({
    url: '/courses/' + courseId + '/materials.json',
    success: that.onWorkbinStructureReceived
  });
}

MaterialsFilePicker.prototype.onSelectionCompleted = function() {
  this.doneCallback(this.selectedMaterials);
}

MaterialsFilePicker.prototype.onWorkbinStructureReceived = function(rootNode) {

}<commit_msg>Add logic to parse hash and return it to callback when done.<commit_after>function MaterialsFilePicker(callback) {
  this.doneCallback = callback;
  this.selectedMaterials = {};
  this.treeElement = $('#file-picker-tree');

  var courseId = gon.course;
  var that = this;
  $.ajax({
    url: '/courses/' + courseId + '/materials.json',
    success: that.onWorkbinStructureReceived
  });
}

MaterialsFilePicker.prototype.onSelectionCompleted = function() {
  var selectedItems = [];
  for (var id in selectedMaterials) {
    var currentTuple = selectedMaterials[id];
    selectedItems.push(currentTuple);
  }

  this.doneCallback(selectedItems);
};

MaterialsFilePicker.prototype.onWorkbinStructureReceived = function(rootNode) {

}<|endoftext|>


<commit_before>'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => Promise.all([
    // Remove unneeded columns
    queryInterface.removeColumn('Games', 'game_number'),
    queryInterface.removeColumn('Games', 'sr_change'),
    queryInterface.removeColumn('Games', 'streak'),
    queryInterface.removeColumn('Games', 'score'),
    queryInterface.removeColumn('Games', 'group_size'),
    queryInterface.removeColumn('Games', 'heroes'),
    queryInterface.removeColumn('Games', 'notes'),

    //add missing columns
    queryInterface.addColumn('Games', 'outcome', Sequelize.TEXT),
  ]),

  down: (queryInterface, Sequelize) => Promise.all([
    queryInterface.addColumn('Games', 'game_number', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'sr_change', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'streak', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'score', Sequelize.STRING),
    queryInterface.addColumn('Games', 'group_size', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'heroes', Sequelize.TEXT),
    queryInterface.addColumn('Games', 'notes', Sequelize.TEXT),

    queryInterface.removeColumn('Games', 'outcome'),
  ]),
};
<commit_msg>remove map from games table<commit_after>'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => Promise.all([
    // Remove unneeded columns
    queryInterface.removeColumn('Games', 'game_number'),
    queryInterface.removeColumn('Games', 'sr_change'),
    queryInterface.removeColumn('Games', 'streak'),
    queryInterface.removeColumn('Games', 'map'),
    queryInterface.removeColumn('Games', 'score'),
    queryInterface.removeColumn('Games', 'group_size'),
    queryInterface.removeColumn('Games', 'heroes'),
    queryInterface.removeColumn('Games', 'notes'),

    //add missing columns
    queryInterface.addColumn('Games', 'outcome', Sequelize.TEXT),
  ]),

  down: (queryInterface, Sequelize) => Promise.all([
    queryInterface.addColumn('Games', 'game_number', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'sr_change', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'streak', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'map', Sequelize.TEXT),
    queryInterface.addColumn('Games', 'score', Sequelize.STRING),
    queryInterface.addColumn('Games', 'group_size', Sequelize.INTEGER),
    queryInterface.addColumn('Games', 'heroes', Sequelize.TEXT),
    queryInterface.addColumn('Games', 'notes', Sequelize.TEXT),

    queryInterface.removeColumn('Games', 'outcome'),
  ]),
};
<|endoftext|>


<commit_before>angular.module('ocWebGui.queue', ['ocWebGui.queue.service', 'ui.router', 'ocWebGui.shared.time', 'nvd3'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('queue', {
        url: '/queue',
        templateUrl: 'queue/_queue.html',
        controller: 'QueueController',
        controllerAs: 'queue'
      });
  })
  .controller('QueueController', function ($interval, $scope, Queue, $http) {
    var vm = this;
    vm.options = {
      chart: {
        type: 'linePlusBarChart',
        height: 360,
        margin: {
          top: 30,
          right: 40,
          bottom: 60,
          left: 40
        },
        x: function (d) { return d.hour; },
        y: function (d) { return d.calls; },
        bars: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        lines: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        xAxis: {
          tickFormat: function (d) {
            return d3.format(',f')(d);
          },
          axisLabel: 'Kellonaika',
          showMaxMin: true
        },
        y1Axis: {
          tickValues: [0, 2]
        },
        y2Axis: {
          tickValues: [0, 2]
        },
        legend: {
          maxKeyLength: 100
        },
        duration: 500
      }
    };
    vm.data = [{
      'key': 'Puheluja tunnissa',
      'bar': true,
      'color': '#000000',
      'values': []
    }, {
      'key': 'Keskim. jonotusaika',
      'color': '#ff0000',
      'values': []
    }];

    function fetchContactStats() {
      $http.get('contacts/stats.json').then(function (response) {
        var data = response.data;
        var values = data.calls_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          // .filter(function (item) { return item.calls !== 0; });
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; })
          ;
        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }
        angular.extend(vm.stats, vm.stats, data);
        vm.data[0].values = values;

        var nearest_ten = get_nearest_ten(0);
        if (nearest_ten == 0) return;

        vm.options.chart.bars.yDomain[1] = nearest_ten;

        setTicks("y1", nearest_ten);
      });
    }

    function fetchQueueStats() {
      $http.get('queue/stats.json').then(function (response) {
        var data = response.data;
        var values = data.queue_items_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; });
        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }
        angular.extend(vm.stats, vm.stats, data);
        vm.data[1].values = values;

        var nearest_ten = get_nearest_ten(1);
        if (nearest_ten == 0) return;

        vm.options.chart.lines.yDomain[1] = nearest_ten;

        setTicks("y2", nearest_ten);
      });
    }

    function setTicks(axis, nearest_ten) {
      if (axis == "y1")
        var ticks = vm.options.chart.y1Axis.tickValues;

      if (axis == "y2")
        var ticks = vm.options.chart.y2xis.tickValues;

      newTicks = get_ticks(nearest_ten);

      if (angular.equals(ticks, newTicks)) return;

      while (ticks.length > 0) {
        ticks.pop();
      }

      newTicks.forEach(function (tick) {
        ticks.push(tick);
      });
    }

    function get_nearest_ten(i) {
      var max_val = d3.max(vm.data[i].values, function(x) { return x.calls; });
      if (max_val == null) {
        return 0;
      }
      return Math.ceil(max_val / 10) * 10;
    }

    function get_ticks(nearest_ten) {
      if (nearest_ten == 10) {
        return Array.from({length: 10}, (v, k) => k);
      }
      return Array.from({length: nearest_ten / 10}, (v, k) => k * 10);
    }

    vm.message = 'Jono';

    vm.queue = [];

    vm.date = new Date();

    function fetchData() {
      Queue.query(function (queue) {
        vm.queue = queue.filter(function (queuer) {
          return queuer.language !== 'Unknown';
        });
      });
      // Also update date/time
      vm.date = new Date();
    }
    var fetchDataInterval = $interval(fetchData, 5 * 1000);
    var fetchContactStatsInterval = $interval(fetchContactStats, 5 * 60 * 1000);
    var fetchQueueStatsInterval = $interval(fetchQueueStats, 5 * 60 * 1000);
    $scope.$on('$destroy', function () {
      $interval.cancel(fetchDataInterval);
      $interval.cancel(fetchContactStatsInterval);
      $interval.cancel(fetchQueueStatsInterval);
    });

    fetchData();
    fetchContactStats();
    fetchQueueStats();

    // mock data for testing css
    // vm.queue = [
    //   { line: 135, language: 'Fin', time_in_queue: 360 },
    //   { line: 137, language: 'Fin', time_in_queue: 123 },
    //   { line: 125, language: 'Eng', time_in_queue: 123 },
    //   { line: 137, language: 'Fin', time_in_queue: 123 },
    //   { line: 133, language: 'Swe', time_in_queue: 53  },
    //   { line: 131, language: 'Eng', time_in_queue: 123 },
    //   { line: 121, language: 'Eng', time_in_queue: 214 }
    // ];
  });
<commit_msg>longer variable name<commit_after>angular.module('ocWebGui.queue', ['ocWebGui.queue.service', 'ui.router', 'ocWebGui.shared.time', 'nvd3'])
  .config(function ($stateProvider) {
    $stateProvider
      .state('queue', {
        url: '/queue',
        templateUrl: 'queue/_queue.html',
        controller: 'QueueController',
        controllerAs: 'queue'
      });
  })
  .controller('QueueController', function ($interval, $scope, Queue, $http) {
    var vm = this;
    vm.options = {
      chart: {
        type: 'linePlusBarChart',
        height: 360,
        margin: {
          top: 30,
          right: 40,
          bottom: 60,
          left: 40
        },
        x: function (d) { return d.hour; },
        y: function (d) { return d.calls; },
        bars: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        lines: {
          forceY: [0, 50],
          yDomain: [0, 10]
        },
        xAxis: {
          tickFormat: function (d) {
            return d3.format(',f')(d);
          },
          axisLabel: 'Kellonaika',
          showMaxMin: true
        },
        y1Axis: {
          tickValues: [0, 2]
        },
        y2Axis: {
          tickValues: [0, 2]
        },
        legend: {
          maxKeyLength: 100
        },
        duration: 500
      }
    };
    vm.data = [{
      'key': 'Puheluja tunnissa',
      'bar': true,
      'color': '#000000',
      'values': []
    }, {
      'key': 'Keskim. jonotusaika',
      'color': '#ff0000',
      'values': []
    }];

    function fetchContactStats() {
      $http.get('contacts/stats.json').then(function (response) {
        var data = response.data;
        var values = data.calls_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          // .filter(function (item) { return item.calls !== 0; });
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; })
          ;
        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }
        angular.extend(vm.stats, vm.stats, data);
        vm.data[0].values = values;

        var nearest_ten_for_max_value = get_nearest_ten_for_max_value(0);
        if (nearest_ten_for_max_value == 0) return;

        vm.options.chart.bars.yDomain[1] = nearest_ten_for_max_value;

        setTicks("y1", nearest_ten_for_max_value);
      });
    }

    function fetchQueueStats() {
      $http.get('queue/stats.json').then(function (response) {
        var data = response.data;
        var values = data.queue_items_by_hour
          .map(function (calls, hour) { return { hour: hour, calls: calls }; })
          .filter(function (item) { return item.hour >= 8 && item.hour <= 18; });
        if (!angular.isDefined(vm.stats)) {
          vm.stats = {};
        }
        angular.extend(vm.stats, vm.stats, data);
        vm.data[1].values = values;

        var nearest_ten_for_max_value = get_nearest_ten_for_max_value(1);
        if (nearest_ten_for_max_value == 0) return;

        vm.options.chart.lines.yDomain[1] = nearest_ten_for_max_value;

        setTicks("y2", nearest_ten_for_max_value);
      });
    }

    function setTicks(axis, nearest_ten_for_max_value) {
      if (axis == "y1")
        var ticks = vm.options.chart.y1Axis.tickValues;

      if (axis == "y2")
        var ticks = vm.options.chart.y2xis.tickValues;

      newTicks = get_ticks(nearest_ten_for_max_value);

      if (angular.equals(ticks, newTicks)) return;

      while (ticks.length > 0) {
        ticks.pop();
      }

      newTicks.forEach(function (tick) {
        ticks.push(tick);
      });
    }

    function get_nearest_ten_for_max_value(i) {
      var max_val = d3.max(vm.data[i].values, function(x) { return x.calls; });
      if (max_val == null) {
        return 0;
      }
      return Math.ceil(max_val / 10) * 10;
    }

    function get_ticks(nearest_ten_for_max_value) {
      if (nearest_ten_for_max_value == 10) {
        return Array.from({length: 10}, (v, k) => k);
      }
      return Array.from({length: nearest_ten_for_max_value / 10}, (v, k) => k * 10);
    }

    vm.message = 'Jono';

    vm.queue = [];

    vm.date = new Date();

    function fetchData() {
      Queue.query(function (queue) {
        vm.queue = queue.filter(function (queuer) {
          return queuer.language !== 'Unknown';
        });
      });
      // Also update date/time
      vm.date = new Date();
    }
    var fetchDataInterval = $interval(fetchData, 5 * 1000);
    var fetchContactStatsInterval = $interval(fetchContactStats, 5 * 60 * 1000);
    var fetchQueueStatsInterval = $interval(fetchQueueStats, 5 * 60 * 1000);
    $scope.$on('$destroy', function () {
      $interval.cancel(fetchDataInterval);
      $interval.cancel(fetchContactStatsInterval);
      $interval.cancel(fetchQueueStatsInterval);
    });

    fetchData();
    fetchContactStats();
    fetchQueueStats();

    // mock data for testing css
    // vm.queue = [
    //   { line: 135, language: 'Fin', time_in_queue: 360 },
    //   { line: 137, language: 'Fin', time_in_queue: 123 },
    //   { line: 125, language: 'Eng', time_in_queue: 123 },
    //   { line: 137, language: 'Fin', time_in_queue: 123 },
    //   { line: 133, language: 'Swe', time_in_queue: 53  },
    //   { line: 131, language: 'Eng', time_in_queue: 123 },
    //   { line: 121, language: 'Eng', time_in_queue: 214 }
    // ];
  });
<|endoftext|>