<commit_before>import React, {PropTypes} from 'react'
import Pane from 'component:desk-tool/pane'
import QueryPane from 'component:desk-tool/query-pane'
import schema from 'schema:@sanity/base/schema'
import PaneContainer from 'component:desk-tool/pane-container'
import FormBuilderContainer from 'role:@sanity/form-builder/container'
import locationStore from 'datastore:@sanity/base/location'
import styles from '../styles/DeskTool.css'

function getTypeItems() {
  return (schema.types || []).map(type => ({
    pathSegment: type.name,
    title: type.name.substr(0, 1).toUpperCase() + type.name.substr(1)
  }))
}

const looksLikeDisplayField = field => ['name', 'title'].indexOf(field.name) !== -1

class SchemaPaneResolver extends React.Component {
  shouldComponentUpdate(nextProps) {
    return this.props.location !== nextProps.location
  }

  getPaneQuery(typeName) {
    const type = schema.types.find(currType => currType.name === typeName)
    if (!type) {
      console.error(`Type "${typeName}" not defined in schema`)
      return locationStore.actions.navigate('/')
    }

    const displayField = type.displayField
      ? type.fields.find(field => field.name === type.displayField)
      : type.fields.find(looksLikeDisplayField)

    const fieldName = displayField && displayField.name || 'title'
    const selection = `{"pathSegment": .$id, "title": .${fieldName}}`
    return `${schema.name}.${typeName} ${selection}`
  }

  render() {
    const segments = this.props.location.split('/').slice(1)
    const selectedType = segments[0]
    const selectedItem = segments[1]
    const panes = [
      <Pane
        key="types"
        items={getTypeItems()}
        activeItem={selectedType}
      />
    ]

    if (selectedType) {
      panes.push(
        <QueryPane
          key={selectedType}
          basePath={`/${selectedType}`}
          segments={segments}
          query={this.getPaneQuery(selectedType)}
          activeItem={segments[1]}
          previousPathSegment={segments[0]}
        />
      )
    }

    const editor = selectedItem && (
      <FormBuilderContainer
        documentId={selectedItem}
        typeName={selectedType}
      />
    )

    return (

        <PaneContainer className={styles.paneContainer}>
          {panes}
        </PaneContainer>

          {editor}

    )
  }
}

SchemaPaneResolver.propTypes = {
  location: PropTypes.string.isRequired
}

export default SchemaPaneResolver
<commit_msg>Use data-aspects when getting and presenting content<commit_after>import React, {PropTypes} from 'react'
import Pane from 'component:desk-tool/pane'
import QueryPane from 'component:desk-tool/query-pane'
import schema from 'schema:@sanity/base/schema'
import PaneContainer from 'component:desk-tool/pane-container'
import FormBuilderContainer from 'role:@sanity/form-builder/container'
import styles from '../styles/DeskTool.css'
import DataAspectsResolver from 'role:@sanity/data-aspects/resolver'
const dataAspects = new DataAspectsResolver(schema)

function getTypeItems() {
  return dataAspects.getInferredTypes().map(type => ({
    pathSegment: type.name,
    title: type.name.substr(0, 1).toUpperCase() + type.name.substr(1)
  }))
}

class SchemaPaneResolver extends React.Component {

  shouldComponentUpdate(nextProps) {
    return this.props.location !== nextProps.location
  }

  parseLocation() {
    const segments = this.props.location.split('/').slice(1)
    let selectedType = segments[0]
    let selectedItem = segments[1]
    if (selectedType && !dataAspects.getType(selectedType)) {
      selectedType = null
      selectedItem = null
    }
    return {segments, selectedType, selectedItem}
  }

  render() {
    const {segments, selectedType, selectedItem} = this.parseLocation()
    const typeItems = getTypeItems()

    const panes = [
      <Pane
        key="types"
        items={typeItems}
        activeItem={selectedType}
      />
    ]

    if (selectedType) {
      const queryOpts = {
        typeName: selectedType,
        keyForId: 'pathSegment',
        keyForDisplayFieldName: 'title'
      }
      const selectedTypeQuery = dataAspects.getListQuery(queryOpts)
      console.log('query:', selectedTypeQuery)

      panes.push(
        <QueryPane
          key={selectedType}
          basePath={`/${selectedType}`}
          segments={segments}
          query={selectedTypeQuery}
          activeItem={selectedItem}
          previousPathSegment={selectedType}
        />
      )
    }

    const editor = selectedItem && (
      <FormBuilderContainer
        documentId={selectedItem}
        typeName={selectedType}
      />
    )

    return (

        <PaneContainer className={styles.paneContainer}>
          {panes}
        </PaneContainer>

          {editor}

    )
  }
}

SchemaPaneResolver.propTypes = {
  location: PropTypes.string.isRequired
}

export default SchemaPaneResolver
<|endoftext|>


<commit_before>/* @flow */
/* global BabelParserOptions */
/* global BabelFileMetadata */
/* global BabelFileResult */

import getHelper from "babel-helpers";
import * as metadataVisitor from "./metadata";
import convertSourceMap from "convert-source-map";
import OptionManager from "./options/option-manager";
import type Pipeline from "../pipeline";
import type Plugin from "../plugin";
import PluginPass from "../plugin-pass";
import shebangRegex from "shebang-regex";
import { NodePath, Hub, Scope } from "babel-traverse";
import sourceMap from "source-map";
import generate from "babel-generator";
import codeFrame from "babel-code-frame";
import defaults from "lodash/object/defaults";
import traverse from "babel-traverse";
import Logger from "./logger";
import Store from "../../store";
import { parse } from "babylon";
import * as util from  "../../util";
import path from "path";
import * as t from "babel-types";

import blockHoistPlugin from "../internal-plugins/block-hoist";
import shadowFunctionsPlugin from "../internal-plugins/shadow-functions";

const INTERNAL_PLUGINS = [
  [blockHoistPlugin],
  [shadowFunctionsPlugin]
];

let errorVisitor = {
  enter(path, state) {
    let loc = path.node.loc;
    if (loc) {
      state.loc = loc;
      path.stop();
    }
  }
};

export default class File extends Store {
  constructor(opts: Object = {}, pipeline: Pipeline) {
    super();

    this.pipeline = pipeline;

    this.log  = new Logger(this, opts.filename || "unknown");
    this.opts = this.initOptions(opts);

    this.parserOpts = {
      highlightCode: this.opts.highlightCode,
      nonStandard:   this.opts.nonStandard,
      sourceType:    this.opts.sourceType,
      filename:      this.opts.filename,
      plugins:       []
    };

    this.pluginVisitors = [];
    this.pluginPasses = [];
    this.pluginStack = [];
    this.buildPlugins();

    this.metadata = {
      usedHelpers: [],
      marked: [],
      modules: {
        imports: [],
        exports: {
          exported: [],
          specifiers: []
        }
      }
    };

    this.dynamicImportTypes = {};
    this.dynamicImportIds   = {};
    this.dynamicImports     = [];
    this.declarations       = {};
    this.usedHelpers        = {};

    this.path = null;
    this.ast  = {};

    this.code    = "";
    this.shebang = "";

    this.hub = new Hub(this);
  }

  static helpers: Array<string>;

  pluginVisitors: Array<Object>;
  pluginPasses: Array<PluginPass>;
  pluginStack: Array<Plugin>;
  pipeline: Pipeline;
  parserOpts: BabelParserOptions;
  log: Logger;
  opts: Object;
  dynamicImportTypes: Object;
  dynamicImportIds: Object;
  dynamicImports: Array<Object>;
  declarations: Object;
  usedHelpers: Object;
  path: NodePath;
  ast: Object;
  scope: Scope;
  metadata: BabelFileMetadata;
  hub: Hub;
  code: string;
  shebang: string;

  getMetadata() {
    let has = false;
    for (let node of (this.ast.program.body: Array<Object>)) {
      if (t.isModuleDeclaration(node)) {
        has = true;
        break;
      }
    }
    if (has) {
      this.path.traverse(metadataVisitor, this);
    }
  }

  initOptions(opts) {
    opts = new OptionManager(this.log, this.pipeline).init(opts);

    if (opts.inputSourceMap) {
      opts.sourceMaps = true;
    }

    if (opts.moduleId) {
      opts.moduleIds = true;
    }

    opts.basename = path.basename(opts.filename, path.extname(opts.filename));

    opts.ignore = util.arrayify(opts.ignore, util.regexify);

    if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);

    defaults(opts, {
      moduleRoot: opts.sourceRoot
    });

    defaults(opts, {
      sourceRoot: opts.moduleRoot
    });

    defaults(opts, {
      filenameRelative: opts.filename
    });

    let basenameRelative = path.basename(opts.filenameRelative);

    defaults(opts, {
      sourceFileName:   basenameRelative,
      sourceMapTarget:  basenameRelative
    });

    return opts;
  }

  buildPlugins() {
    let plugins: Array<[PluginPass, Object]> = this.opts.plugins.concat(INTERNAL_PLUGINS);

    // init plugins!
    for (let ref of plugins) {
      let [plugin, pluginOpts] = ref; // todo: fix - can't embed in loop head because of flow bug

      this.pluginStack.push(plugin);
      this.pluginVisitors.push(plugin.visitor);
      this.pluginPasses.push(new PluginPass(this, plugin, pluginOpts));

      if (plugin.manipulateOptions) {
        plugin.manipulateOptions(this.opts, this.parserOpts, this);
      }
    }
  }

  getModuleName(): ?string {
    let opts = this.opts;
    if (!opts.moduleIds) {
      return null;
    }

    // moduleId is n/a if a `getModuleId()` is provided
    if (opts.moduleId != null && !opts.getModuleId) {
      return opts.moduleId;
    }

    let filenameRelative = opts.filenameRelative;
    let moduleName = "";

    if (opts.moduleRoot != null) {
      moduleName = opts.moduleRoot + "/";
    }

    if (!opts.filenameRelative) {
      return moduleName + opts.filename.replace(/^\//, "");
    }

    if (opts.sourceRoot != null) {
      // remove sourceRoot from filename
      let sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
      filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
    }

    // remove extension
    filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");

    moduleName += filenameRelative;

    // normalize path separators
    moduleName = moduleName.replace(/\\/g, "/");

    if (opts.getModuleId) {
      // If return is falsy, assume they want us to use our generated default name
      return opts.getModuleId(moduleName) || moduleName;
    } else {
      return moduleName;
    }
  }

  resolveModuleSource(source: string): string {
    let resolveModuleSource = this.opts.resolveModuleSource;
    if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
    return source;
  }

  addImport(source: string, imported: string, name?: string = imported): Object {
    let alias = `${source}:${imported}`;
    let id = this.dynamicImportIds[alias];

    if (!id) {
      source = this.resolveModuleSource(source);
      id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name);

      let specifiers = [];

      if (imported === "*") {
        specifiers.push(t.importNamespaceSpecifier(id));
      } else if (imported === "default") {
        specifiers.push(t.importDefaultSpecifier(id));
      } else {
        specifiers.push(t.importSpecifier(id, t.identifier(imported)));
      }

      let declar = t.importDeclaration(specifiers, t.stringLiteral(source));
      declar._blockHoist = 3;

      this.path.unshiftContainer("body", declar);
    }

    return id;
  }

  addHelper(name: string): Object {
    let declar = this.declarations[name];
    if (declar) return declar;

    if (!this.usedHelpers[name]) {
      this.metadata.usedHelpers.push(name);
      this.usedHelpers[name] = true;
    }

    let generator = this.get("helperGenerator");
    let runtime   = this.get("helpersNamespace");
    if (generator) {
      let res = generator(name);
      if (res) return res;
    } else if (runtime) {
      let id = t.identifier(t.toIdentifier(name));
      return t.memberExpression(runtime, id);
    }

    let ref = getHelper(name);
    let uid = this.declarations[name] = this.scope.generateUidIdentifier(name);

    if (t.isFunctionExpression(ref) && !ref.id) {
      ref.body._compact = true;
      ref._generated = true;
      ref.id = uid;
      ref.type = "FunctionDeclaration";
      this.path.unshiftContainer("body", ref);
    } else {
      ref._compact = true;
      this.scope.push({
        id: uid,
        init: ref,
        unique: true
      });
    }

    return uid;
  }

  addTemplateObject(
    helperName: string,
    strings: Array<Object>,
    raw: Object,
  ): Object {
    // Generate a unique name based on the string literals so we dedupe
    // identical strings used in the program.
    let stringIds = raw.elements.map(function(string) {
      return string.value;
    });
    let name = `${helperName}_${raw.elements.length}_${stringIds.join(",")}`;

    let declar = this.declarations[name];
    if (declar) return declar;

    let uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");

    let helperId = this.addHelper(helperName);
    let init = t.callExpression(helperId, [strings, raw]);
    init._compact = true;
    this.scope.push({
      id: uid,
      init: init,
      _blockHoist: 1.9    // This ensures that we don't fail if not using function expression helpers
    });
    return uid;
  }

  buildCodeFrameError(node: Object, msg: string, Error: typeof Error = SyntaxError): Error {
    let loc = node && (node.loc || node._loc);

    let err = new Error(msg);

    if (loc) {
      err.loc = loc.start;
    } else {
      traverse(node, errorVisitor, this.scope, err);

      err.message += " (This is an error on an internal node. Probably an internal error";

      if (err.loc) {
        err.message += ". Location has been estimated.";
      }

      err.message += ")";
    }

    return err
  }

  mergeSourceMap(map: Object) {
    let inputMap = this.opts.inputSourceMap;

    if (inputMap) {
      let inputMapConsumer   = new sourceMap.SourceMapConsumer(inputMap);
      let outputMapConsumer  = new sourceMap.SourceMapConsumer(map);
      let outputMapGenerator = sourceMap.SourceMapGenerator.fromSourceMap(outputMapConsumer);
      outputMapGenerator.applySourceMap(inputMapConsumer);

      let mergedMap = outputMapGenerator.toJSON();
      mergedMap.sources = inputMap.sources;
      mergedMap.file    = inputMap.file;
      return mergedMap;
    } else {
      return map;
    }
  }

  parse(code: string) {
    this.log.debug("Parse start");
    let ast = parse(code, this.parserOpts);
    this.log.debug("Parse stop");
    return ast;
  }

  _addAst(ast) {
    this.path = NodePath.get({
      hub: this.hub,
      parentPath: null,
      parent: ast,
      container: ast,
      key: "program"
    }).setContext();
    this.scope = this.path.scope;
    this.ast   = ast;
    this.getMetadata();
  }

  addAst(ast) {
    this.log.debug("Start set AST");
    this._addAst(ast);
    this.log.debug("End set AST");
  }

  transform(): BabelFileResult {
    this.call("pre");
    this.log.debug(`Start transform traverse`);
    traverse(this.ast, traverse.visitors.merge(this.pluginVisitors, this.pluginPasses), this.scope);
    this.log.debug(`End transform traverse`);
    this.call("post");
    return this.generate();
  }

  wrap(code: string, callback: Function): BabelFileResult {
    code = code + "";

    try {
      if (this.shouldIgnore()) {
        return this.makeResult({ code, ignored: true });
      } else {
        return callback();
      }
    } catch (err) {
      if (err._babel) {
        throw err;
      } else {
        err._babel = true;
      }

      let message = err.message = `${this.opts.filename}: ${err.message}`;

      let loc = err.loc;
      if (loc) {
        err.codeFrame = codeFrame(code, loc.line, loc.column + 1, this.opts);
        message += "\n" + err.codeFrame;
      }

      if (process.browser) {
        // chrome has it's own pretty stringifier which doesn't use the stack property
        // https://github.com/babel/babel/issues/2175
        err.message = message;
      }

      if (err.stack) {
        let newStack = err.stack.replace(err.message, message);
        try {
          err.stack = newStack;
        } catch (e) {
          // `err.stack` may be a readonly property in some environments
        }
      }

      throw err;
    }
  }

  addCode(code: string) {
    code = (code || "") + "";
    code = this.parseInputSourceMap(code);
    this.code = code;
  }

  parseCode() {
    this.parseShebang();
    let ast = this.parse(this.code);
    this.addAst(ast);
  }

  shouldIgnore() {
    let opts = this.opts;
    return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
  }

  call(key: "pre" | "post") {
    for (let pass of (this.pluginPasses: Array<PluginPass>)) {
      let plugin = pass.plugin;
      let fn = plugin[key];
      if (fn) fn.call(pass, this, pass);
    }
  }

  parseInputSourceMap(code: string): string {
    let opts = this.opts;

    if (opts.inputSourceMap !== false) {
      let inputMap = convertSourceMap.fromSource(code);
      if (inputMap) {
        opts.inputSourceMap = inputMap.toObject();
        code = convertSourceMap.removeComments(code);
      }
    }

    return code;
  }

  parseShebang() {
    let shebangMatch = shebangRegex.exec(this.code);
    if (shebangMatch) {
      this.shebang = shebangMatch[0];
      this.code = this.code.replace(shebangRegex, "");
    }
  }

  makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult {
    let result = {
      metadata: null,
      options:  this.opts,
      ignored:  !!ignored,
      code:     null,
      ast:      null,
      map:      map || null
    };

    if (this.opts.code) {
      result.code = code;
    }

    if (this.opts.ast) {
      result.ast = ast;
    }

    if (this.opts.metadata) {
      result.metadata = this.metadata;
    }

    return result;
  }

  generate(): BabelFileResult {
    let opts = this.opts;
    let ast  = this.ast;

    let result: BabelFileResult = { ast };
    if (!opts.code) return this.makeResult(result);

    this.log.debug("Generation start");

    let _result = generate(ast, opts, this.code);
    result.code = _result.code;
    result.map  = _result.map;

    this.log.debug("Generation end");

    if (this.shebang) {
      // add back shebang
      result.code = `${this.shebang}\n${result.code}`;
    }

    if (result.map) {
      result.map = this.mergeSourceMap(result.map);
    }

    if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
      result.code += "\n" + convertSourceMap.fromObject(result.map).toComment();
    }

    if (opts.sourceMaps === "inline") {
      result.map = null;
    }

    return this.makeResult(result);
  }
}

export { File };
<commit_msg>remove state arg from pre and post plugin hooks<commit_after>/* @flow */
/* global BabelParserOptions */
/* global BabelFileMetadata */
/* global BabelFileResult */

import getHelper from "babel-helpers";
import * as metadataVisitor from "./metadata";
import convertSourceMap from "convert-source-map";
import OptionManager from "./options/option-manager";
import type Pipeline from "../pipeline";
import type Plugin from "../plugin";
import PluginPass from "../plugin-pass";
import shebangRegex from "shebang-regex";
import { NodePath, Hub, Scope } from "babel-traverse";
import sourceMap from "source-map";
import generate from "babel-generator";
import codeFrame from "babel-code-frame";
import defaults from "lodash/object/defaults";
import traverse from "babel-traverse";
import Logger from "./logger";
import Store from "../../store";
import { parse } from "babylon";
import * as util from  "../../util";
import path from "path";
import * as t from "babel-types";

import blockHoistPlugin from "../internal-plugins/block-hoist";
import shadowFunctionsPlugin from "../internal-plugins/shadow-functions";

const INTERNAL_PLUGINS = [
  [blockHoistPlugin],
  [shadowFunctionsPlugin]
];

let errorVisitor = {
  enter(path, state) {
    let loc = path.node.loc;
    if (loc) {
      state.loc = loc;
      path.stop();
    }
  }
};

export default class File extends Store {
  constructor(opts: Object = {}, pipeline: Pipeline) {
    super();

    this.pipeline = pipeline;

    this.log  = new Logger(this, opts.filename || "unknown");
    this.opts = this.initOptions(opts);

    this.parserOpts = {
      highlightCode: this.opts.highlightCode,
      nonStandard:   this.opts.nonStandard,
      sourceType:    this.opts.sourceType,
      filename:      this.opts.filename,
      plugins:       []
    };

    this.pluginVisitors = [];
    this.pluginPasses = [];
    this.pluginStack = [];
    this.buildPlugins();

    this.metadata = {
      usedHelpers: [],
      marked: [],
      modules: {
        imports: [],
        exports: {
          exported: [],
          specifiers: []
        }
      }
    };

    this.dynamicImportTypes = {};
    this.dynamicImportIds   = {};
    this.dynamicImports     = [];
    this.declarations       = {};
    this.usedHelpers        = {};

    this.path = null;
    this.ast  = {};

    this.code    = "";
    this.shebang = "";

    this.hub = new Hub(this);
  }

  static helpers: Array<string>;

  pluginVisitors: Array<Object>;
  pluginPasses: Array<PluginPass>;
  pluginStack: Array<Plugin>;
  pipeline: Pipeline;
  parserOpts: BabelParserOptions;
  log: Logger;
  opts: Object;
  dynamicImportTypes: Object;
  dynamicImportIds: Object;
  dynamicImports: Array<Object>;
  declarations: Object;
  usedHelpers: Object;
  path: NodePath;
  ast: Object;
  scope: Scope;
  metadata: BabelFileMetadata;
  hub: Hub;
  code: string;
  shebang: string;

  getMetadata() {
    let has = false;
    for (let node of (this.ast.program.body: Array<Object>)) {
      if (t.isModuleDeclaration(node)) {
        has = true;
        break;
      }
    }
    if (has) {
      this.path.traverse(metadataVisitor, this);
    }
  }

  initOptions(opts) {
    opts = new OptionManager(this.log, this.pipeline).init(opts);

    if (opts.inputSourceMap) {
      opts.sourceMaps = true;
    }

    if (opts.moduleId) {
      opts.moduleIds = true;
    }

    opts.basename = path.basename(opts.filename, path.extname(opts.filename));

    opts.ignore = util.arrayify(opts.ignore, util.regexify);

    if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);

    defaults(opts, {
      moduleRoot: opts.sourceRoot
    });

    defaults(opts, {
      sourceRoot: opts.moduleRoot
    });

    defaults(opts, {
      filenameRelative: opts.filename
    });

    let basenameRelative = path.basename(opts.filenameRelative);

    defaults(opts, {
      sourceFileName:   basenameRelative,
      sourceMapTarget:  basenameRelative
    });

    return opts;
  }

  buildPlugins() {
    let plugins: Array<[PluginPass, Object]> = this.opts.plugins.concat(INTERNAL_PLUGINS);

    // init plugins!
    for (let ref of plugins) {
      let [plugin, pluginOpts] = ref; // todo: fix - can't embed in loop head because of flow bug

      this.pluginStack.push(plugin);
      this.pluginVisitors.push(plugin.visitor);
      this.pluginPasses.push(new PluginPass(this, plugin, pluginOpts));

      if (plugin.manipulateOptions) {
        plugin.manipulateOptions(this.opts, this.parserOpts, this);
      }
    }
  }

  getModuleName(): ?string {
    let opts = this.opts;
    if (!opts.moduleIds) {
      return null;
    }

    // moduleId is n/a if a `getModuleId()` is provided
    if (opts.moduleId != null && !opts.getModuleId) {
      return opts.moduleId;
    }

    let filenameRelative = opts.filenameRelative;
    let moduleName = "";

    if (opts.moduleRoot != null) {
      moduleName = opts.moduleRoot + "/";
    }

    if (!opts.filenameRelative) {
      return moduleName + opts.filename.replace(/^\//, "");
    }

    if (opts.sourceRoot != null) {
      // remove sourceRoot from filename
      let sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
      filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
    }

    // remove extension
    filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");

    moduleName += filenameRelative;

    // normalize path separators
    moduleName = moduleName.replace(/\\/g, "/");

    if (opts.getModuleId) {
      // If return is falsy, assume they want us to use our generated default name
      return opts.getModuleId(moduleName) || moduleName;
    } else {
      return moduleName;
    }
  }

  resolveModuleSource(source: string): string {
    let resolveModuleSource = this.opts.resolveModuleSource;
    if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
    return source;
  }

  addImport(source: string, imported: string, name?: string = imported): Object {
    let alias = `${source}:${imported}`;
    let id = this.dynamicImportIds[alias];

    if (!id) {
      source = this.resolveModuleSource(source);
      id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name);

      let specifiers = [];

      if (imported === "*") {
        specifiers.push(t.importNamespaceSpecifier(id));
      } else if (imported === "default") {
        specifiers.push(t.importDefaultSpecifier(id));
      } else {
        specifiers.push(t.importSpecifier(id, t.identifier(imported)));
      }

      let declar = t.importDeclaration(specifiers, t.stringLiteral(source));
      declar._blockHoist = 3;

      this.path.unshiftContainer("body", declar);
    }

    return id;
  }

  addHelper(name: string): Object {
    let declar = this.declarations[name];
    if (declar) return declar;

    if (!this.usedHelpers[name]) {
      this.metadata.usedHelpers.push(name);
      this.usedHelpers[name] = true;
    }

    let generator = this.get("helperGenerator");
    let runtime   = this.get("helpersNamespace");
    if (generator) {
      let res = generator(name);
      if (res) return res;
    } else if (runtime) {
      let id = t.identifier(t.toIdentifier(name));
      return t.memberExpression(runtime, id);
    }

    let ref = getHelper(name);
    let uid = this.declarations[name] = this.scope.generateUidIdentifier(name);

    if (t.isFunctionExpression(ref) && !ref.id) {
      ref.body._compact = true;
      ref._generated = true;
      ref.id = uid;
      ref.type = "FunctionDeclaration";
      this.path.unshiftContainer("body", ref);
    } else {
      ref._compact = true;
      this.scope.push({
        id: uid,
        init: ref,
        unique: true
      });
    }

    return uid;
  }

  addTemplateObject(
    helperName: string,
    strings: Array<Object>,
    raw: Object,
  ): Object {
    // Generate a unique name based on the string literals so we dedupe
    // identical strings used in the program.
    let stringIds = raw.elements.map(function(string) {
      return string.value;
    });
    let name = `${helperName}_${raw.elements.length}_${stringIds.join(",")}`;

    let declar = this.declarations[name];
    if (declar) return declar;

    let uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");

    let helperId = this.addHelper(helperName);
    let init = t.callExpression(helperId, [strings, raw]);
    init._compact = true;
    this.scope.push({
      id: uid,
      init: init,
      _blockHoist: 1.9    // This ensures that we don't fail if not using function expression helpers
    });
    return uid;
  }

  buildCodeFrameError(node: Object, msg: string, Error: typeof Error = SyntaxError): Error {
    let loc = node && (node.loc || node._loc);

    let err = new Error(msg);

    if (loc) {
      err.loc = loc.start;
    } else {
      traverse(node, errorVisitor, this.scope, err);

      err.message += " (This is an error on an internal node. Probably an internal error";

      if (err.loc) {
        err.message += ". Location has been estimated.";
      }

      err.message += ")";
    }

    return err
  }

  mergeSourceMap(map: Object) {
    let inputMap = this.opts.inputSourceMap;

    if (inputMap) {
      let inputMapConsumer   = new sourceMap.SourceMapConsumer(inputMap);
      let outputMapConsumer  = new sourceMap.SourceMapConsumer(map);
      let outputMapGenerator = sourceMap.SourceMapGenerator.fromSourceMap(outputMapConsumer);
      outputMapGenerator.applySourceMap(inputMapConsumer);

      let mergedMap = outputMapGenerator.toJSON();
      mergedMap.sources = inputMap.sources;
      mergedMap.file    = inputMap.file;
      return mergedMap;
    } else {
      return map;
    }
  }

  parse(code: string) {
    this.log.debug("Parse start");
    let ast = parse(code, this.parserOpts);
    this.log.debug("Parse stop");
    return ast;
  }

  _addAst(ast) {
    this.path = NodePath.get({
      hub: this.hub,
      parentPath: null,
      parent: ast,
      container: ast,
      key: "program"
    }).setContext();
    this.scope = this.path.scope;
    this.ast   = ast;
    this.getMetadata();
  }

  addAst(ast) {
    this.log.debug("Start set AST");
    this._addAst(ast);
    this.log.debug("End set AST");
  }

  transform(): BabelFileResult {
    this.call("pre");
    this.log.debug(`Start transform traverse`);
    traverse(this.ast, traverse.visitors.merge(this.pluginVisitors, this.pluginPasses), this.scope);
    this.log.debug(`End transform traverse`);
    this.call("post");
    return this.generate();
  }

  wrap(code: string, callback: Function): BabelFileResult {
    code = code + "";

    try {
      if (this.shouldIgnore()) {
        return this.makeResult({ code, ignored: true });
      } else {
        return callback();
      }
    } catch (err) {
      if (err._babel) {
        throw err;
      } else {
        err._babel = true;
      }

      let message = err.message = `${this.opts.filename}: ${err.message}`;

      let loc = err.loc;
      if (loc) {
        err.codeFrame = codeFrame(code, loc.line, loc.column + 1, this.opts);
        message += "\n" + err.codeFrame;
      }

      if (process.browser) {
        // chrome has it's own pretty stringifier which doesn't use the stack property
        // https://github.com/babel/babel/issues/2175
        err.message = message;
      }

      if (err.stack) {
        let newStack = err.stack.replace(err.message, message);
        try {
          err.stack = newStack;
        } catch (e) {
          // `err.stack` may be a readonly property in some environments
        }
      }

      throw err;
    }
  }

  addCode(code: string) {
    code = (code || "") + "";
    code = this.parseInputSourceMap(code);
    this.code = code;
  }

  parseCode() {
    this.parseShebang();
    let ast = this.parse(this.code);
    this.addAst(ast);
  }

  shouldIgnore() {
    let opts = this.opts;
    return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
  }

  call(key: "pre" | "post") {
    for (let pass of (this.pluginPasses: Array<PluginPass>)) {
      let plugin = pass.plugin;
      let fn = plugin[key];
      if (fn) fn.call(pass, this);
    }
  }

  parseInputSourceMap(code: string): string {
    let opts = this.opts;

    if (opts.inputSourceMap !== false) {
      let inputMap = convertSourceMap.fromSource(code);
      if (inputMap) {
        opts.inputSourceMap = inputMap.toObject();
        code = convertSourceMap.removeComments(code);
      }
    }

    return code;
  }

  parseShebang() {
    let shebangMatch = shebangRegex.exec(this.code);
    if (shebangMatch) {
      this.shebang = shebangMatch[0];
      this.code = this.code.replace(shebangRegex, "");
    }
  }

  makeResult({ code, map, ast, ignored }: BabelFileResult): BabelFileResult {
    let result = {
      metadata: null,
      options:  this.opts,
      ignored:  !!ignored,
      code:     null,
      ast:      null,
      map:      map || null
    };

    if (this.opts.code) {
      result.code = code;
    }

    if (this.opts.ast) {
      result.ast = ast;
    }

    if (this.opts.metadata) {
      result.metadata = this.metadata;
    }

    return result;
  }

  generate(): BabelFileResult {
    let opts = this.opts;
    let ast  = this.ast;

    let result: BabelFileResult = { ast };
    if (!opts.code) return this.makeResult(result);

    this.log.debug("Generation start");

    let _result = generate(ast, opts, this.code);
    result.code = _result.code;
    result.map  = _result.map;

    this.log.debug("Generation end");

    if (this.shebang) {
      // add back shebang
      result.code = `${this.shebang}\n${result.code}`;
    }

    if (result.map) {
      result.map = this.mergeSourceMap(result.map);
    }

    if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
      result.code += "\n" + convertSourceMap.fromObject(result.map).toComment();
    }

    if (opts.sourceMaps === "inline") {
      result.map = null;
    }

    return this.makeResult(result);
  }
}

export { File };
<|endoftext|>


<commit_before>var Sidebar = React.createClass({
    componentDidMount: function() {
        /* Look up categories in semantic search.
         * For some reason they can't run locally,
         * but we'll use them with our API to
         * seperate users, problems, and blog posts.
         * For the moment though, they're together.
         */

        var dummySearchContent = [
            { title: 'Traveling Salesman Problem', description: 'Find the optimal route through a set of 500 points in 3D space.' },
            { title: 'Tron: A Postmortem', description: 'by Jake Sanders' },
            { title: 'Joshua Gruenstein', description: 'Horace Mann' }
        ];

        $('.ui.search').search({
            source: this.props.searchContent
        });
    },
    gameList: function(games, active) {
        var season = -1;
        return games.map(function(game) {
            if (game.season != season) {
                season = game.season;
                return (

                            {"Season " + game.season}

                        {game.name}

                );
            } else return (
                {game.name}
            );
        });
    },
    render: function() {
        return (

                            <input className="prompt" type="text" placeholder="Search..." />

Games

                        { this.gameList(this.props.games, this.props.active) }

                    Users

                    Blog

About

NYCSL is an inter-mural programming competition for highschool students in the New York area.  Each month-ish a new problem is posted, and participants are challenged to create the optimal solution.  Challenges can be games, algorithmic problems, or something else entirely.  The top ranked students for each challenge receive prizes, and are invited to attend the NYCSL Championship at Horace Mann in the summer.

        );
    }
});

var NavBar = React.createClass({
    componentDidMount: function() {
        $('#accountBtn').popup({
            popup: '.special.popup',
            hoverable: true,
            position : 'bottom center'
        });
    },
    openMenu: function() {
        $('.ui.sidebar').sidebar('toggle');
    },
    openLoginModal: function() {
        $('.ui.modal').modal('show');
    },
    signInModal: function() {
        return (

                    Login with Github

Click the button below to login with Github.

If you don't already have an account linked to your Github profile, that's ok. Well automatically detect it and help you get things set up.

                    <button className="ui button fluid">

                        Connect to Github
                    </button>

        );
    },
    signUpModal: function() {
        return (

                    Signup with Github

                            School
                            <select className="ui fluid search dropdown selection">
                                <option value="">Select School</option>
                                <option value="HM">Horace Mann School</option>
                                <option value="DA">Dalton School</option>
                                <option value="ST">Stuyvesant</option>
                            </select>

                    <button className="ui button fluid">
                        Create Account
                    </button>

        );
    },
    loggedInMenu: function(githubID) {
        return (

                    Submit

                        Profile

                        Logout

        );
    },
    loggedOutMenu: function() {
        return (

                    Login with Github

                { this.signInModal() }

        );
    },
    render: function() {
        return (

                    NYCSL

                     Menu

                { this.props.logState ? this.loggedInMenu(this.props.githubID) : this.loggedOutMenu() }

        );
    }
});

$.get('http://' + location.hostname + ':5000/problems', function (result) {
    $.get('http://' + location.hostname + ':5000/search', function (content) {
        ReactDOM.render(
            <Sidebar games={result} active={document.body.id} searchContent={content} />,
            document.getElementById('sidebarBox')
        );
    });
});

ReactDOM.render(
    <NavBar githubID="7736334" logState={false} />,
    document.getElementById('navbarBox')
);
<commit_msg>change login link system<commit_after>var Sidebar = React.createClass({
    componentDidMount: function() {
        /* Look up categories in semantic search.
         * For some reason they can't run locally,
         * but we'll use them with our API to
         * seperate users, problems, and blog posts.
         * For the moment though, they're together.
         */

        var dummySearchContent = [
            { title: 'Traveling Salesman Problem', description: 'Find the optimal route through a set of 500 points in 3D space.' },
            { title: 'Tron: A Postmortem', description: 'by Jake Sanders' },
            { title: 'Joshua Gruenstein', description: 'Horace Mann' }
        ];

        $('.ui.search').search({
            source: this.props.searchContent
        });
    },
    gameList: function(games, active) {
        var season = -1;
        return games.map(function(game) {
            if (game.season != season) {
                season = game.season;
                return (

                            {"Season " + game.season}

                        {game.name}

                );
            } else return (
                {game.name}
            );
        });
    },
    render: function() {
        return (

                            <input className="prompt" type="text" placeholder="Search..." />

Games

                        { this.gameList(this.props.games, this.props.active) }

                    Users

                    Blog

About

NYCSL is an inter-mural programming competition for highschool students in the New York area.  Each month-ish a new problem is posted, and participants are challenged to create the optimal solution.  Challenges can be games, algorithmic problems, or something else entirely.  The top ranked students for each challenge receive prizes, and are invited to attend the NYCSL Championship at Horace Mann in the summer.

        );
    }
});

var NavBar = React.createClass({
    componentDidMount: function() {
        $('#accountBtn').popup({
            popup: '.special.popup',
            hoverable: true,
            position : 'bottom center'
        });
    },
    openMenu: function() {
        $('.ui.sidebar').sidebar('toggle');
    },
    openLoginModal: function() {
        $('.ui.modal').modal('show');
    },
    loggedInMenu: function(githubID) {
        return (

                    Submit

                        Profile

                        Logout

        );
    },
    loggedOutMenu: function() {
        return (

                    Login with Github

        );
    },
    render: function() {
        return (

                    NYCSL

                     Menu

                { this.props.logState ? this.loggedInMenu(this.props.githubID) : this.loggedOutMenu() }

        );
    }
});

$.get('http://' + location.hostname + ':5000/problems', function (result) {
    $.get('http://' + location.hostname + ':5000/search', function (content) {
        ReactDOM.render(
            <Sidebar games={result} active={document.body.id} searchContent={content} />,
            document.getElementById('sidebarBox')
        );
    });
});

ReactDOM.render(
    <NavBar githubID="7736334" logState={false} />,
    document.getElementById('navbarBox')
);
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var chai = chai || require('chai');
var sinon = sinon || require('sinon');
var should = chai.should();

var { Verifier } = require('../ts_build/lib/verifier');
var { Key } = require('../ts_build/lib/key');

const aKey = Key.fromMnemonic('abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about');

describe('Verifier', function () {

  describe('checkAddress', function () {

    it('should verify a BTC  address', () => {

      let cred = aKey.createCredentials(null, { coin: 'btc', network: 'livenet', account: 0, n: 1});
      cred.addWalletInfo(
        'id',
        'name',
        1,
        1,
        'copayer',
      );

      Verifier.checkAddress(cred, {
        address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',
        path: 'm/0/0',
        publicKeys: ['03aaeb52dd7494c361049de67cc680e83ebcbbbdbeb13637d92cd845f70308af5e'],
      }).should.be.true;
    })

    it('should verify a ETH  address', () => {
      let cred = aKey.createCredentials(null, { coin: 'eth', network: 'livenet', account: 0, n: 1});
      cred.addWalletInfo(
        'id',
        'name',
        1,
        1,
        'copayer',
      );

      Verifier.checkAddress(cred, {
        address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',
        path: 'm/0/0',
        publicKeys: ['0237b0bb7a8288d38ed49a524b5dc98cff3eb5ca824c9f9dc0dfdb3d9cd600f299'],
      }).should.be.true;
    })
  });

  describe('checkCopayers', function () {

    it('should verify copayers', () => {
      let cred = aKey.createCredentials(null, { coin: 'btc', network: 'livenet', account: 0, n: 1});
      cred.addWalletInfo(
        'id',
        'name',
        1,
        1,
        'copayer',
      );
      Verifier.checkCopayers(cred, {
        address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',
        path: 'm/0/0',
        publicKeys: ['0237b0bb7a8288d38ed49a524b5dc98cff3eb5ca824c9f9dc0dfdb3d9cd600f299'],
      }).should.be.true;
    });
  });
});

<commit_msg>rm unfinished tests<commit_after>'use strict';

var _ = require('lodash');
var chai = chai || require('chai');
var sinon = sinon || require('sinon');
var should = chai.should();

var { Verifier } = require('../ts_build/lib/verifier');
var { Key } = require('../ts_build/lib/key');

const aKey = Key.fromMnemonic('abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about');

describe('Verifier', function () {

  describe('checkAddress', function () {

    it('should verify a BTC  address', () => {

      let cred = aKey.createCredentials(null, { coin: 'btc', network: 'livenet', account: 0, n: 1});
      cred.addWalletInfo(
        'id',
        'name',
        1,
        1,
        'copayer',
      );

      Verifier.checkAddress(cred, {
        address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',
        path: 'm/0/0',
        publicKeys: ['03aaeb52dd7494c361049de67cc680e83ebcbbbdbeb13637d92cd845f70308af5e'],
      }).should.be.true;
    })

    it('should verify a ETH  address', () => {
      let cred = aKey.createCredentials(null, { coin: 'eth', network: 'livenet', account: 0, n: 1});
      cred.addWalletInfo(
        'id',
        'name',
        1,
        1,
        'copayer',
      );

      Verifier.checkAddress(cred, {
        address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',
        path: 'm/0/0',
        publicKeys: ['0237b0bb7a8288d38ed49a524b5dc98cff3eb5ca824c9f9dc0dfdb3d9cd600f299'],
      }).should.be.true;
    })
  });

});

<|endoftext|>


<commit_before>
// Initialise OCRJS namespace
if (OCRJS === undefined) {
    var OCRJS = {};
}

OCRJS.OcrBase = Base.extend({
    constructor: function(options) {
        this.options = {
            log: false,
        }
        $.extend(this.options, options);
    },

    _logger: function(text) {
        if (!this.options.log)
            return;
        var log = $("#logwin");
        if (!log.length) {
            log = $("").attr("id", "logwin");
            $("body").append(log);
        }
        log.text((new Date()).getTime() + ":   " + text);
    },
});

// Base widget for OCR items.  Just provides
// logging window facilities
OCRJS.OcrBaseWidget = OCRJS.OcrBase.extend({
    constructor: function(parent, options) {
        this.base(options);
        this.parent = parent;
        this.options = {
            log: false,
        }
        $.extend(this.options, options);
    },

    containerWidget: function() {
        return $(this.parent).closest(".widget");
    },
});
<commit_msg>Provide multi-line logging<commit_after>
// Initialise OCRJS namespace
if (OCRJS === undefined) {
    var OCRJS = {};
}

OCRJS.OcrBase = Base.extend({
    constructor: function(options) {
        this._log = [];
        this.options = {
            log: false,
        }
        $.extend(this.options, options);
    },

    _logger: function(text) {
        if (!this.options.log)
            return;
        this._log.push((new Date()).getTime() + ":  " + text);
        if (this._log.length > 5)
            this._log.shift();
        var log = $("#logwin");
        if (!log.length) {
            log = $("

")
                .attr("id", "logwin");

            $("body").append(log);
        }
        log.html("");
        $.each(this._log, function(i, t) {
            log.append($("
" + t + "
"));
        });
    },
});

// Base widget for OCR items.  Just provides
// logging window facilities
OCRJS.OcrBaseWidget = OCRJS.OcrBase.extend({
    constructor: function(parent, options) {
        this.base(options);
        this.parent = parent;
        this.options = {
            log: false,
        }
        $.extend(this.options, options);
    },

    containerWidget: function() {
        return $(this.parent).closest(".widget");
    },
});
<|endoftext|>


<commit_before>var majorScale = [0, 2, 4, 5, 7, 9, 11];

var semiTone = Math.pow(2, 1/12);

var ctx = new webkitAudioContext();

var settings = {
	tempo: 120
}

//Note numbering: A1 = 0, A#1 = 1, B1 = 2, C2 = 3....
var generateTones = function() {
	var tones = [];
	tones[0] = 55;
	for (var i = 1; i < 77; i++) {
		tones.push(tones[i - 1] * semiTone);
 	}
 	return tones;
}

var _tonesTable = generateTones();

//Phrase representation: tone: -4 - 12, schedule: 0 - 7}]

var playOsc = function(freq, dur, startTime) {
	osc = ctx.createOscillator();
	osc.frequency.value = freq;
	osc.type = "square";
	osc.connect(ctx.destination);
	osc.start(startTime);
	osc.stop(startTime + dur);
}

var playPhrase = function(phraseStartTime, phraseRoot, phrase) {
	var startTime = phraseStartTime;
	for (var i = 0; i < phrase.notes.length; i++) {
		var beatValue = (1 / (settings.tempo / 60)) * 4;
		var toneLookup = phraseRoot + phrase.notes[i].tone;
		var freq = _tonesTable[toneLookup];
    	var duration = beatValue / phrase.notes[i].noteValue;

		console.log(startTime);
		console.log(duration);

    	playOsc(freq, duration, startTime);
		var startTime = startTime + duration;
	}
}

function Note(tone, noteValue) {
	this.tone = tone;
	this.noteValue = noteValue;
}

function Phrase(notes) {
	this.notes = notes;
}

var theNotes = [new Note(0, 8), new Note(5, 8), new Note(8, 8), new Note(-4, 8)];

var aPhrase = new Phrase(theNotes);

playPhrase(0, 15, aPhrase);

<commit_msg>Added phrases<commit_after>

var majorScale = [0, 2, 4, 5, 7, 9, 11, 12];

var settings = {
	tempo: 120,
	scale: majorScale
}

var getNoteNumber = function(scaleDegree, rootValue) {
	var noteNumber;

	//Check for invalid input
	if (scaleDegree === 0 || scaleDegree === -1) {
		scaleDegree = 1;  //With invalid input, just play root tone
	}

	if (scaleDegree > 0) {
		var newDegree = scaleDegree - 1;
		noteNumber = rootValue + settings.scale[newDegree];
	} else {
		var newDegree = settings.scale.length + (scaleDegree - 1);
		noteNumber = (rootValue - 12) + settings.scale[newDegree];
	}
	return noteNumber;
}

var semiTone = Math.pow(2, 1/12);

var ctx = new webkitAudioContext();

//Note numbering: A1 = 0, A#1 = 1, B1 = 2, C2 = 3....
var generateTones = function() {
	var tones = [];
	tones[0] = 55;
	for (var i = 1; i < 77; i++) {
		tones.push(tones[i - 1] * semiTone);
 	}
 	return tones;
}

var _tonesTable = generateTones();

//Phrase representation: tone: -4 - 12, schedule: 0 - 7}]

var playOsc = function(freq, dur, startTime) {
	console.log("Hi");
	osc = ctx.createOscillator();
	osc.frequency.value = freq;
	osc.type = "square";
	osc.connect(ctx.destination);
	osc.start(startTime);
	osc.stop(startTime + dur);
}

var playPhrase = function(phraseStartTime, phraseRoot, phrase) {
	console.log("playPhrase");
	var startTime = phraseStartTime;
	for (var i = 0; i < phrase.notes.length; i++) {
		var beatValue = (1 / (settings.tempo / 60)) * 4;
		var toneLookup = getNoteNumber(phrase.notes[i].tone, phraseRoot);
		var freq = _tonesTable[toneLookup];
    	var duration = beatValue / phrase.notes[i].noteValue;
    	playOsc(freq, duration, startTime);
		var startTime = startTime + duration;
	}
}

function Note(tone, noteValue) {
	this.tone = tone;
	this.noteValue = noteValue;
}

function Phrase(notes) {
	this.notes = notes;
}

function makePhrase(notes) {
	tempPhrase = [];
	for (var i = 0; i < notes.length; i++) {
		var thisNote = new Note(notes[i][0], notes[i][1]);
		tempPhrase.push(thisNote);
	}
	return new Phrase(tempPhrase);
}

//Representing relative notes as scale degrees 1-7
var phrases = [
	makePhrase([[1, 2]]),
	makePhrase([[5, 4], [1, 4]]),
	makePhrase([[1, 8], [5, 8], [8, 8], [5, 8]]),
	makePhrase([[1, 8], [3, 8], [5, 8], [3, 8]]),
	makePhrase([[1, 8], [2, 8], [3, 8], [5, 8]]),
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])

	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])

	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	makePhrase([[1, 8], [3, 16], [-4, 16], [5, 16], [-3, 16], [6, 16], [-2, 16]])
	//makePhrase([[1, 8], [3, 8], [5, 8], [3, 8]]),
	//makePhrase([[1, 8], [3, 8], [5, 8], [3, 8]]),
	//makePhrase([[1, 8], [3, 8], [5, 8], [3, 8]])
]

var theNotes = [new Note(0, 8), new Note(5, 8), new Note(8, 8), new Note(-4, 8)];

var aPhrase = new Phrase(theNotes);

var playPhrases = function(phrases) {
	var startTime = ctx.currentTime;
	var beatValue = (1 / (settings.tempo / 60)) * 4;
	for (var i = 0; i < phrases.length; i++) {
		playPhrase(startTime, 15, phrases[i]);
		startTime = startTime + (beatValue / 2);
	}
}

//playPhrase(0, 15, aPhrase);

//playPhrase(0, 15, phrases[0]);
playPhrases(phrases);

<|endoftext|>


<commit_before>var map;
var polylines;

function initMap() {
    console.log('init called');
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
      center: {lat: 48.428611, lng: -123.365556},
      zoom: 14
    });
}

function mapRoute(routes) {
    console.log('mapRoute called');
    console.log(routes);

    for(var j = 0; j < routes.lenth; j++){
        latlngPoints = [];
        for(var i = 0; i < routes[j].length; i++) {
            latlngPoints.push({lat: routes[j][i][0], lng: routes[j][i][1]});
        }
        console.log(latlngPoints);
        var strokeColor = '#FF0000'
        if(j >= 1){
            strokeColor = '#0000FF'
        }

        var polyline = new google.maps.Polyline({
            path: latlngPoints,
            geodesic: true,
            strokeColor: '#FF0000',
            strokeOpacity: 0.5,
            strokeWeight: 2
        });

        polyline.setMap(map);
        polylines.push(polyline)
    }
}

function getRoutes(starting_point, ending_point) {
    console.log(starting_point);
    $.ajax({
      url: '/route',
      type: 'POST',
      data: { start: starting_point, end:ending_point},
      success: function(data) {
          routes = JSON.parse(data);
          console.log(routes);
          mapRoute(routes);
      }
    });
}

$("#bttn").click(function() {
    starting_point = $("#starting_point").val();
    ending_point = $("#ending_point").val();
    // Remove current path
    if(polyline) {
        polyline.setMap(null);
    }

    routes = getRoutes(starting_point, ending_point);
});
<commit_msg>js null fi<commit_after>var map;
var polylines;

function initMap() {
    console.log('init called');
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
      center: {lat: 48.428611, lng: -123.365556},
      zoom: 14
    });
}

function mapRoute(routes) {
    console.log('mapRoute called');
    console.log(routes);

    for(var j = 0; j < routes.lenth; j++){
        latlngPoints = [];
        for(var i = 0; i < routes[j].length; i++) {
            latlngPoints.push({lat: routes[j][i][0], lng: routes[j][i][1]});
        }
        console.log(latlngPoints);
        var strokeColor = '#FF0000'
        if(j >= 1){
            strokeColor = '#0000FF'
        }

        var polyline = new google.maps.Polyline({
            path: latlngPoints,
            geodesic: true,
            strokeColor: '#FF0000',
            strokeOpacity: 0.5,
            strokeWeight: 2
        });

        polyline.setMap(map);
        polylines.push(polyline)
    }
}

function getRoutes(starting_point, ending_point) {
    console.log(starting_point);
    $.ajax({
      url: '/route',
      type: 'POST',
      data: { start: starting_point, end:ending_point},
      success: function(data) {
          routes = JSON.parse(data);
          console.log(routes);
          mapRoute(routes);
      }
    });
}

$("#bttn").click(function() {
    starting_point = $("#starting_point").val();
    ending_point = $("#ending_point").val();
    // Remove current path
    if(!!polylines) {
        for(var i = 0; i < polylines.length; i++) {
            polylines[i].setMap(null);
        }
    }

    routes = getRoutes(starting_point, ending_point);
});
<|endoftext|>


<commit_before>export default function validate(formData, errors) {
    const sampleInformation = formData.Sample_Information;
    const organism = sampleInformation.Organism;
    const organismPart = sampleInformation.Organism_Part;
    const growthCondition = sampleInformation.Sample_Growth_Conditions;
    const organismPartErrors = validateOrganismPart(organism, organismPart);
    for (let i = 0; i < organismPartErrors.length; i++) {
        errors.Sample_Information.Organism_Part.addError(organismPartErrors[i]);
    }
    const growthConditionErrors = validateGrowthConditions(growthCondition, organism);
    for (let i = 0; i < growthConditionErrors.length; i++) {
        errors.Sample_Information.Sample_Growth_Conditions.addError(growthConditionErrors[i]);
    }

    const samplePrep = formData.Sample_Preparation;
    const matrix = samplePrep.MALDI_Matrix;
    const application = samplePrep.MALDI_Matrix_Application;
    const source = formData.MS_Analysis.Ionisation_Source;
    var maldiMatrixErrors = validateMaldiMatrix(matrix, source);
    for (let i = 0; i < maldiMatrixErrors.length; i++) {
        errors.Sample_Preparation.MALDI_Matrix.addError(maldiMatrixErrors[i]);
    }
    var maldiMatrixApplicationErrors = validateMaldiMatrixApplication(application, source);
    for (let i = 0; i < maldiMatrixApplicationErrors.length; i++) {
        errors.Sample_Preparation.MALDI_Matrix_Application.addError(maldiMatrixApplicationErrors[i]);
    }
    return errors;
}

function validateOrganismPart(organism, organismPart) {
    let errors = [];
    const plants = ["Arabidopsis_thaliana_(thale_cress)"];
    const notPlants = [
        "Homo_sapiens_(Human)",
        "Mus_musculus_(Mouse)",
        "Rattus_norvegicus_(Rat)",
        "Danio_rerio_(Zebrafish)"
    ];
    const plantParts = ["Leaf", "Stem", "Root"];
    const notPlantParts = [
        "Brain",
        "Kidney",
        "Eye",
        "Liver",
        "Ovary",
        "Pancreas",
        "Lung",
        "Lymph_Node",
        "Testis"
    ];
    if ((plants.indexOf(organism) !== -1 && notPlantParts.indexOf(organismPart) !== -1) ||
        (notPlants.indexOf(organism) !== -1 && plantParts.indexOf(organismPart) !== -1)) {
        errors = ["is not part of " + organism];
    }
    return errors;
}

function validateGrowthConditions(growthCondition, organism) {
    let errors = [];
    const notHumanConditions = [
        "Cultured_2D",
        "Cultured_3D",
        "Caged"
    ];
    const notCulturable = [
        "Homo_sapiens_(Human)",
        "Mus_musculus_(Mouse)",
        "Rattus_norvegicus_(Rat)",
        "Danio_rerio_(Zebrafish)",
        "Arabidopsis_thaliana_(thale_cress)"
    ];
    const notCageable = [
        "Homo_sapiens_(Human)",
        "Danio_rerio_(Zebrafish)",
        "Arabidopsis_thaliana_(thale_cress)"
    ];
    if ((organism == "Homo_sapiens_(Human)" && notHumanConditions.indexOf(growthCondition) !== -1) ||
        (["Cultured_2D", "Cultured_3D"].indexOf(growthCondition) !== -1 && notCulturable.indexOf(organism) !== -1) ||
        (growthCondition == "Caged" && notCageable.indexOf(organism) !== -1)) {
        errors.push("not applicable for " + organism);
    }
    return errors;
}

function validateMaldiMatrix(matrix, source) {
    if (source !== "MALDI" && matrix !== "none") {
        return ["Cannot have matrix without MALDI as the ionization source"];
    } else {
        return [];
    }
}

function validateMaldiMatrixApplication(application, source) {
    if (source !== "MALDI" && application !== "none") {
        return ["Cannot have matrix application without MALDI as the ionization source"];
    } else {
        return [];
    }
}
<commit_msg>less verbose validation code<commit_after>export default function validate(formData, errors) {
    function runChecks(validator, paths, errorDisplayIndex, subObj=(x) => x) {
        const field = (f) => (typeof f === 'string') ? (o) => o[f] : f;
        paths = paths.map(field);
        subObj = field(subObj);
        const data = paths.map((path) => path(subObj(formData)));
        let formErrors = paths[errorDisplayIndex](subObj(errors));
        validator(...data).forEach((e) => formErrors.addError(e));
    }

    runChecks(validateOrganismPart,
              ['Organism', 'Organism_Part'], 1,
              'Sample_Information');

    runChecks(validateGrowthConditions,
              ['Sample_Growth_Conditions', 'Organism'], 0,
              'Sample_Information');

    runChecks(validateMaldiMatrix, [
        (x) => x.Sample_Preparation.MALDI_Matrix,
        (x) => x.MS_Analysis.Ionisation_Source
    ], 0);

    runChecks(validateMaldiMatrixApplication, [
        (x) => x.Sample_Preparation.MALDI_Matrix_Application,
        (x) => x.MS_Analysis.Ionisation_Source
    ], 0);

    return errors;
}

function validateOrganismPart(organism, organismPart) {
    let errors = [];
    const plants = new Set(["Arabidopsis_thaliana_(thale_cress)"]);
    const notPlants = new Set([
        "Homo_sapiens_(Human)",
        "Mus_musculus_(Mouse)",
        "Rattus_norvegicus_(Rat)",
        "Danio_rerio_(Zebrafish)"
    ]);
    const plantParts = new Set(["Leaf", "Stem", "Root"]);
    const notPlantParts = new Set([
        "Brain",
        "Kidney",
        "Eye",
        "Liver",
        "Ovary",
        "Pancreas",
        "Lung",
        "Lymph_Node",
        "Testis"
    ]);
    if ((plants.has(organism) && notPlantParts.has(organismPart)) ||
        (notPlants.has(organism) && plantParts.has(organismPart)))
    {
        errors = ["is not part of " + organism];
    }
    return errors;
}

function validateGrowthConditions(growthCondition, organism) {
    let errors = [];
    const notHumanConditions = new Set([
        "Cultured_2D",
        "Cultured_3D",
        "Caged"
    ]);
    const notCulturable = new Set([
        "Homo_sapiens_(Human)",
        "Mus_musculus_(Mouse)",
        "Rattus_norvegicus_(Rat)",
        "Danio_rerio_(Zebrafish)",
        "Arabidopsis_thaliana_(thale_cress)"
    ]);
    const notCageable = new Set([
        "Homo_sapiens_(Human)",
        "Danio_rerio_(Zebrafish)",
        "Arabidopsis_thaliana_(thale_cress)"
    ]);

    if ((organism == "Homo_sapiens_(Human)" && notHumanConditions.has(growthCondition)) ||
        (growthCondition.startsWith("Cultured") && notCulturable.has(organism)) ||
        (growthCondition == "Caged" && notCageable.has(organism)))
    {
        errors.push("not applicable for " + organism);
    }
    return errors;
}

function validateMaldiMatrix(matrix, source) {
    if (source !== "MALDI" && matrix !== "none") {
        return ["Cannot have matrix without MALDI as the ionization source"];
    } else {
        return [];
    }
}

function validateMaldiMatrixApplication(application, source) {
    if (source !== "MALDI" && application !== "none") {
        return ["Cannot have matrix application without MALDI as the ionization source"];
    } else {
        return [];
    }
}
<|endoftext|>


<commit_before>var CENTER = [43.771473, 11.253766];
var BOUNDARY = [
    [43.763007, 11.267304],[43.77225, 11.29374],[43.78755, 11.25015],
    [43.77846, 11.23801],[43.76484, 11.24234], [43.763007, 11.267304]
];

///////////////////// INSERIMENTO DELLA MAPPA /////////////////////
var map = L.map('map')

// http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
var tiles = L.tileLayer(
    'http://otile4.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png',
    // 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
    {
        attribution: 'Map data © OpenStreetMap contributors',
        maxZoom: 30,
        reuseTiles: true
    }
)
tiles.addTo(map);

$(document).on('pageshow', '#home', function() {
    /**
     * this is needed due to a known bug which causes the map to disappear
     */
    tiles.redraw();
});

/////////////////////////// DA LONTANO ///////////////////////////
var introduction = "area degli scavi archeologici di firenze"

var big_line = L.polyline(
    BOUNDARY,
    {color: 'red'}
).bindPopup(introduction);

var cluster = L.polygon(
    BOUNDARY,
    {color: 'red'}
).bindPopup(introduction);
cluster.on("click", function() {
    map.setView(CENTER, 16);
});
cluster.on('mouseover', function (e) {
    this.openPopup();
});
cluster.on('mouseout', function (e) {
    this.closePopup();
});

var RedIcon = L.Icon.Default.extend(
    {
        options: {iconUrl: 'images/marker_icon_red.png'}
    }
);
var redIcon = new RedIcon();
var far_marker = L.marker(
    CENTER,
    {icon: redIcon}
).bindPopup(introduction);
far_marker.on("click",  function() {
    map.setView(CENTER, 16);
});
far_marker.on('mouseover', function (e) {
    this.openPopup();
});
far_marker.on('mouseout', function (e) {
    this.closePopup();
});

function onZoomend() {
    var zoom_now = map.getZoom();
    console.log("zoom: ", zoom_now);

    if(zoom_now >= 17) {
        map.removeLayer(big_line);
        map.removeLayer(far_marker);
        map.removeLayer(cluster);
    }
    else if((zoom_now < 17) && (zoom_now >= 14)) {
        big_line.addTo(map);
        map.removeLayer(far_marker);
        map.removeLayer(cluster);
    }
    else if((zoom_now < 13) && (zoom_now >= 10)) {
        map.removeLayer(big_line);
        map.removeLayer(far_marker);
        cluster.addTo(map);
    }
    else if(zoom_now < 10) {
        map.removeLayer(big_line);
        far_marker.addTo(map);
        map.removeLayer(cluster);
    }
};
map.on('zoomend', onZoomend);

///////////////////// LOCALIZZAZIONE INIZIALE /////////////////////
map.locate({setView: true, maxZoom: 16});

function onLocationFound(e) {
    var my_position = L.marker(e.latlng)
    // var my_position = L.marker([46.019853,5.74585]);     testing
    my_position.bindPopup("sei qui");
    my_position.addTo(map);
    var to_be_shown = new L.featureGroup([my_position, far_marker, boundary]);
    map.fitBounds(to_be_shown.getBounds());
    console.log(e);
}
map.on('locationfound', onLocationFound);

function onLocationError(e) {
    map.setView(CENTER, 18);
    console.log(e.message);
}
map.on('locationerror', onLocationError);

//////////// INSERIMENTO LAYER WMS SCAVI ARCHEOLOGICI ////////////
var layer_interventi = L.tileLayer.wms(
    'http://www.opengeo.eu:8080/geoserver/wms?', {
        layers: 'topp:interventi',
        format: 'image/png',
        transparent: true,
        attribution: "",
        maxZoom: '25',
        minZoom: '7'
    }
);
//////////// INSERIMENTO LAYER WMS SCAVI ARCHEOLOGICI ////////////
var layer_ritrovamenti_linee = L.tileLayer.wms(
    'http://www.opengeo.eu:8080/geoserver/wms?', {
        layers: 'topp:view_ritro_line',
        format: 'image/png',
        transparent: true,
        attribution: "",
        maxZoom: '25',
        minZoom: '19'
    }
);
//////////// INSERIMENTO LAYER WMS SCAVI ARCHEOLOGICI ////////////
var layer_ritrovamenti_punti = L.tileLayer.wms(
    'http://www.opengeo.eu:8080/geoserver/wms?', {
        layers: 'topp:view_ritro_punti',
        format: 'image/png',
        transparent: true,
        attribution: "",
        maxZoom: '25',
        minZoom: '19'
    }
);

layer_interventi.addTo(map);
layer_ritrovamenti_linee.addTo(map);
layer_ritrovamenti_punti.addTo(map);

/////// GESTIONE POPUP INFORMAZIONI TRAMITE CLICK SU MAPPA ///////
map.addEventListener('click', onMapClick);
popup = new L.Popup({ width: 50 });

function onMapClick(e) {
    // coordinate server ( long, lat ) coordinate standard ( lat, long)
    var bbox = map.getBounds()._southWest.lat + ","
            + map.getBounds()._southWest.lng + ","
            + map.getBounds()._northEast.lat + ","
            + map.getBounds()._northEast.lng;

    var width = map.getSize().x;
    var height = map.getSize().y;
    var x = map.layerPointToContainerPoint(e.layerPoint).x;
    var y = map.layerPointToContainerPoint(e.layerPoint).y;
    wms_proxy(bbox, width, height, x, y, e);
};
<commit_msg>event cluster in start feature group<commit_after>var CENTER = [43.771473, 11.253766];
var BOUNDARY = [
    [43.763007, 11.267304],[43.77225, 11.29374],[43.78755, 11.25015],
    [43.77846, 11.23801],[43.76484, 11.24234], [43.763007, 11.267304]
];

///////////////////// INSERIMENTO DELLA MAPPA /////////////////////
var map = L.map('map')

// http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
var tiles = L.tileLayer(
    'http://otile4.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png',
    // 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
    {
        attribution: 'Map data © OpenStreetMap contributors',
        maxZoom: 30,
        reuseTiles: true
    }
)
tiles.addTo(map);

$(document).on('pageshow', '#home', function() {
    /**
     * this is needed due to a known bug which causes the map to disappear
     */
    tiles.redraw();
});

/////////////////////////// DA LONTANO ///////////////////////////
var introduction = "area degli scavi archeologici di firenze"

var big_line = L.polyline(
    BOUNDARY,
    {color: 'red'}
).bindPopup(introduction);

var cluster = L.polygon(
    BOUNDARY,
    {color: 'red'}
).bindPopup(introduction);
cluster.on("click", function() {
    map.setView(CENTER, 16);
});
cluster.on('mouseover', function (e) {
    this.openPopup();
});
cluster.on('mouseout', function (e) {
    this.closePopup();
});

var RedIcon = L.Icon.Default.extend(
    {
        options: {iconUrl: 'images/marker_icon_red.png'}
    }
);
var redIcon = new RedIcon();
var far_marker = L.marker(
    CENTER,
    {icon: redIcon}
).bindPopup(introduction);
far_marker.on("click",  function() {
    map.setView(CENTER, 16);
});
far_marker.on('mouseover', function (e) {
    this.openPopup();
});
far_marker.on('mouseout', function (e) {
    this.closePopup();
});

function onZoomend() {
    var zoom_now = map.getZoom();
    console.log("zoom: ", zoom_now);

    if(zoom_now >= 17) {
        map.removeLayer(big_line);
        map.removeLayer(far_marker);
        map.removeLayer(cluster);
    }
    else if((zoom_now < 17) && (zoom_now >= 14)) {
        big_line.addTo(map);
        map.removeLayer(far_marker);
        map.removeLayer(cluster);
    }
    else if((zoom_now < 13) && (zoom_now >= 10)) {
        map.removeLayer(big_line);
        map.removeLayer(far_marker);
        cluster.addTo(map);
    }
    else if(zoom_now < 10) {
        map.removeLayer(big_line);
        far_marker.addTo(map);
        map.removeLayer(cluster);
    }
};
map.on('zoomend', onZoomend);

///////////////////// LOCALIZZAZIONE INIZIALE /////////////////////
map.locate({setView: true, maxZoom: 16});

function onLocationFound(e) {
    var my_position = L.marker(e.latlng)
    // var my_position = L.marker([46.019853,5.74585]);     testing
    my_position.bindPopup("sei qui");
    my_position.addTo(map);
    var to_be_shown = new L.featureGroup([my_position, far_marker, cluster, big_line]);
    map.fitBounds(to_be_shown.getBounds());
    console.log(e);
}
map.on('locationfound', onLocationFound);

function onLocationError(e) {
    map.setView(CENTER, 18);
    console.log(e.message);
}
map.on('locationerror', onLocationError);

//////////// INSERIMENTO LAYER WMS SCAVI ARCHEOLOGICI ////////////
var layer_interventi = L.tileLayer.wms(
    'http://www.opengeo.eu:8080/geoserver/wms?', {
        layers: 'topp:interventi',
        format: 'image/png',
        transparent: true,
        attribution: "",
        maxZoom: '25',
        minZoom: '7'
    }
);
//////////// INSERIMENTO LAYER WMS SCAVI ARCHEOLOGICI ////////////
var layer_ritrovamenti_linee = L.tileLayer.wms(
    'http://www.opengeo.eu:8080/geoserver/wms?', {
        layers: 'topp:view_ritro_line',
        format: 'image/png',
        transparent: true,
        attribution: "",
        maxZoom: '25',
        minZoom: '19'
    }
);
//////////// INSERIMENTO LAYER WMS SCAVI ARCHEOLOGICI ////////////
var layer_ritrovamenti_punti = L.tileLayer.wms(
    'http://www.opengeo.eu:8080/geoserver/wms?', {
        layers: 'topp:view_ritro_punti',
        format: 'image/png',
        transparent: true,
        attribution: "",
        maxZoom: '25',
        minZoom: '19'
    }
);

layer_interventi.addTo(map);
layer_ritrovamenti_linee.addTo(map);
layer_ritrovamenti_punti.addTo(map);

/////// GESTIONE POPUP INFORMAZIONI TRAMITE CLICK SU MAPPA ///////
map.addEventListener('click', onMapClick);
popup = new L.Popup({ width: 50 });

function onMapClick(e) {
    // coordinate server ( long, lat ) coordinate standard ( lat, long)
    var bbox = map.getBounds()._southWest.lat + ","
            + map.getBounds()._southWest.lng + ","
            + map.getBounds()._northEast.lat + ","
            + map.getBounds()._northEast.lng;

    var width = map.getSize().x;
    var height = map.getSize().y;
    var x = map.layerPointToContainerPoint(e.layerPoint).x;
    var y = map.layerPointToContainerPoint(e.layerPoint).y;
    wms_proxy(bbox, width, height, x, y, e);
};
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   Ember - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2011 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

var get = Ember.get, set = Ember.set;

/**
  @class

  An Ember.Application instance serves as the namespace in which you define your
  application's classes. You can also override the configuration of your
  application.

  By default, Ember.Application will begin listening for events on the document.
  If your application is embedded inside a page, instead of controlling the
  entire document, you can specify which DOM element to attach to by setting
  the `rootElement` property:

      MyApp = Ember.Application.create({
        rootElement: $('#my-app')
      });

  The root of an Ember.Application must not be removed during the course of the
  page's lifetime. If you have only a single conceptual application for the
  entire page, and are not embedding any third-party Ember applications
  in your page, use the default document root for your application.

  You only need to specify the root if your page contains multiple instances
  of Ember.Application.

  @extends Ember.Object
*/
Ember.Application = Ember.Namespace.extend(
/** @scope Ember.Application.prototype */{

  /**
    The root DOM element of the Application.

    Can be specified as DOMElement or a selector string.

    @type DOMElement
    @default 'body'
  */
  rootElement: 'body',

  /**
    @type Ember.EventDispatcher
    @default null
  */
  eventDispatcher: null,

  /**
    @type Object
    @default null
  */
  customEvents: null,

  /** @private */
  init: function() {
    var eventDispatcher,
        rootElement = get(this, 'rootElement');
    this._super();

    eventDispatcher = Ember.EventDispatcher.create({
      rootElement: rootElement
    });

    set(this, 'eventDispatcher', eventDispatcher);

    // jQuery 1.7 doesn't call the ready callback if already ready
    if (Ember.$.isReady) {
      Ember.run.once(this, this.didBecomeReady);
    } else {
      var self = this;
      Ember.$(document).ready(function() {
        Ember.run.once(self, self.didBecomeReady);
      });
    }
  },

  /**
    Instantiate all controllers currently available on the namespace
    and inject them onto a router.

    Example:

        App.PostsController = Ember.ArrayController.extend();
        App.CommentsController = Ember.ArrayController.extend();

        var router = Ember.Router.create({
          ...
        });

        App.initialize(router);

        router.get('postsController')     // <App.PostsController:ember1234>
        router.get('commentsController')  // <App.CommentsController:ember1235>

        router.get('postsController.router') // router
  */
  initialize: function(router) {
    var properties = Ember.A(Ember.keys(this)),
        injections = get(this.constructor, 'injections'),
        namespace = this, controller, name;

    if (!router && Ember.Router.detect(namespace['Router'])) {
      router = namespace['Router'].create();
      this._createdRouter = router;
    }

    if (router) {
      set(this, 'router', router);

      // By default, the router's namespace is the current application.
      //
      // This allows it to find model classes when a state has a
      // route like `/posts/:post_id`. In that case, it would first
      // convert `post_id` into `Post`, and then look it up on its
      // namespace.
      set(router, 'namespace', this);
    }

    Ember.runLoadHooks('application', this);

    injections.forEach(function(injection) {
      properties.forEach(function(property) {
        injection[1](namespace, router, property);
      });
    });

    if (router && router instanceof Ember.Router) {
      this.startRouting(router);
    }
  },

  /** @private */
  didBecomeReady: function() {
    var eventDispatcher = get(this, 'eventDispatcher'),
        customEvents    = get(this, 'customEvents');

    eventDispatcher.setup(customEvents);

    this.ready();
  },

  /**
    @private

    If the application has a router, use it to route to the current URL, and
    trigger a new call to `route` whenever the URL changes.
  */
  startRouting: function(router) {
    var location = get(router, 'location'),
        rootElement = get(this, 'rootElement'),
        applicationController = get(router, 'applicationController');

    Ember.assert("ApplicationView and ApplicationController must be defined on your application", (this.ApplicationView && applicationController) );

    var applicationView = this.ApplicationView.create({
      controller: applicationController
    });
    this._createdApplicationView = applicationView;

    applicationView.appendTo(rootElement);

    router.route(location.getURL());
    location.onUpdateURL(function(url) {
      router.route(url);
    });
  },

  /**
    Called when the Application has become ready.
    The call will be delayed until the DOM has become ready.
  */
  ready: Ember.K,

  /** @private */
  willDestroy: function() {
    get(this, 'eventDispatcher').destroy();
    if (this._createdRouter)          { this._createdRouter.destroy(); }
    if (this._createdApplicationView) { this._createdApplicationView.destroy(); }
  },

  registerInjection: function(options) {
    this.constructor.registerInjection(options);
  }
});

Ember.Application.reopenClass({
  concatenatedProperties: ['injections'],
  injections: Ember.A(),
  registerInjection: function(options) {
    var injections = get(this, 'injections'),
        before = options.before,
        name = options.name,
        injection = options.injection,
        location;

    if (before) {
      location = injections.find(function(item) {
        if (item[0] === before) { return true; }
      });
      location = injections.indexOf(location);
    } else {
      location = get(injections, 'length');
    }

    injections.splice(location, 0, [name, injection]);
  }
});

Ember.Application.registerInjection({
  name: 'controllers',
  injection: function(app, router, property) {
    if (!/^[A-Z].*Controller$/.test(property)) { return; }

    var name = property.charAt(0).toLowerCase() + property.substr(1),
        controller = app[property].create();

    router.set(name, controller);

    controller.setProperties({
      target: router,
      controllers: router,
      namespace: app
    });
  }
});
<commit_msg>Corrects documentation about rootElement.<commit_after>// ==========================================================================
// Project:   Ember - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2011 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

var get = Ember.get, set = Ember.set;

/**
  @class

  An Ember.Application instance serves as the namespace in which you define your
  application's classes. You can also override the configuration of your
  application.

  By default, Ember.Application will begin listening for events on the document.
  If your application is embedded inside a page, instead of controlling the
  entire document, you can specify which DOM element to attach to by setting
  the `rootElement` property to a CSS selector.

      MyApp = Ember.Application.create({
        rootElement: '#my-app'
      });

  The root of an Ember.Application must not be removed during the course of the
  page's lifetime. If you have only a single conceptual application for the
  entire page, and are not embedding any third-party Ember applications
  in your page, use the default document root for your application.

  You only need to specify the root if your page contains multiple instances
  of Ember.Application.

  @extends Ember.Object
*/
Ember.Application = Ember.Namespace.extend(
/** @scope Ember.Application.prototype */{

  /**
    The root DOM element of the Application.

    Can be specified as DOMElement or a selector string.

    @type DOMElement
    @default 'body'
  */
  rootElement: 'body',

  /**
    @type Ember.EventDispatcher
    @default null
  */
  eventDispatcher: null,

  /**
    @type Object
    @default null
  */
  customEvents: null,

  /** @private */
  init: function() {
    var eventDispatcher,
        rootElement = get(this, 'rootElement');
    this._super();

    eventDispatcher = Ember.EventDispatcher.create({
      rootElement: rootElement
    });

    set(this, 'eventDispatcher', eventDispatcher);

    // jQuery 1.7 doesn't call the ready callback if already ready
    if (Ember.$.isReady) {
      Ember.run.once(this, this.didBecomeReady);
    } else {
      var self = this;
      Ember.$(document).ready(function() {
        Ember.run.once(self, self.didBecomeReady);
      });
    }
  },

  /**
    Instantiate all controllers currently available on the namespace
    and inject them onto a router.

    Example:

        App.PostsController = Ember.ArrayController.extend();
        App.CommentsController = Ember.ArrayController.extend();

        var router = Ember.Router.create({
          ...
        });

        App.initialize(router);

        router.get('postsController')     // <App.PostsController:ember1234>
        router.get('commentsController')  // <App.CommentsController:ember1235>

        router.get('postsController.router') // router
  */
  initialize: function(router) {
    var properties = Ember.A(Ember.keys(this)),
        injections = get(this.constructor, 'injections'),
        namespace = this, controller, name;

    if (!router && Ember.Router.detect(namespace['Router'])) {
      router = namespace['Router'].create();
      this._createdRouter = router;
    }

    if (router) {
      set(this, 'router', router);

      // By default, the router's namespace is the current application.
      //
      // This allows it to find model classes when a state has a
      // route like `/posts/:post_id`. In that case, it would first
      // convert `post_id` into `Post`, and then look it up on its
      // namespace.
      set(router, 'namespace', this);
    }

    Ember.runLoadHooks('application', this);

    injections.forEach(function(injection) {
      properties.forEach(function(property) {
        injection[1](namespace, router, property);
      });
    });

    if (router && router instanceof Ember.Router) {
      this.startRouting(router);
    }
  },

  /** @private */
  didBecomeReady: function() {
    var eventDispatcher = get(this, 'eventDispatcher'),
        customEvents    = get(this, 'customEvents');

    eventDispatcher.setup(customEvents);

    this.ready();
  },

  /**
    @private

    If the application has a router, use it to route to the current URL, and
    trigger a new call to `route` whenever the URL changes.
  */
  startRouting: function(router) {
    var location = get(router, 'location'),
        rootElement = get(this, 'rootElement'),
        applicationController = get(router, 'applicationController');

    Ember.assert("ApplicationView and ApplicationController must be defined on your application", (this.ApplicationView && applicationController) );

    var applicationView = this.ApplicationView.create({
      controller: applicationController
    });
    this._createdApplicationView = applicationView;

    applicationView.appendTo(rootElement);

    router.route(location.getURL());
    location.onUpdateURL(function(url) {
      router.route(url);
    });
  },

  /**
    Called when the Application has become ready.
    The call will be delayed until the DOM has become ready.
  */
  ready: Ember.K,

  /** @private */
  willDestroy: function() {
    get(this, 'eventDispatcher').destroy();
    if (this._createdRouter)          { this._createdRouter.destroy(); }
    if (this._createdApplicationView) { this._createdApplicationView.destroy(); }
  },

  registerInjection: function(options) {
    this.constructor.registerInjection(options);
  }
});

Ember.Application.reopenClass({
  concatenatedProperties: ['injections'],
  injections: Ember.A(),
  registerInjection: function(options) {
    var injections = get(this, 'injections'),
        before = options.before,
        name = options.name,
        injection = options.injection,
        location;

    if (before) {
      location = injections.find(function(item) {
        if (item[0] === before) { return true; }
      });
      location = injections.indexOf(location);
    } else {
      location = get(injections, 'length');
    }

    injections.splice(location, 0, [name, injection]);
  }
});

Ember.Application.registerInjection({
  name: 'controllers',
  injection: function(app, router, property) {
    if (!/^[A-Z].*Controller$/.test(property)) { return; }

    var name = property.charAt(0).toLowerCase() + property.substr(1),
        controller = app[property].create();

    router.set(name, controller);

    controller.setProperties({
      target: router,
      controllers: router,
      namespace: app
    });
  }
});
<|endoftext|>