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

type ElementState = {
  tagExpr: Object, // tag node
  tagName: ?string, // raw string tag name
  args: Array<Object>, // array of call arguments
  call?: Object, // optional call property that can be set to override the call expression returned
};

export default function(opts) {
  const visitor = {};

  visitor.JSXNamespacedName = function(path) {
    if (opts.throwIfNamespace) {
      throw path.buildCodeFrameError(
        `Namespace tags are not supported by default. React's JSX doesn't support namespace tags. \
You can turn on the 'throwIfNamespace' flag to bypass this warning.`,
      );
    }
  };

  visitor.JSXSpreadChild = function(path) {
    throw path.buildCodeFrameError(
      "Spread children are not supported in React.",
    );
  };

  visitor.JSXElement = {
    exit(path, file) {
      const callExpr = buildElementCall(path, file);
      if (callExpr) {
        path.replaceWith(t.inherits(callExpr, path.node));
      }
    },
  };

  visitor.JSXFragment = {
    exit(path, file) {
      if (opts.compat) {
        throw path.buildCodeFrameError(
          "Fragment tags are only supported in React 16 and up.",
        );
      }
      const callExpr = buildFragmentCall(path, file);
      if (callExpr) {
        path.replaceWith(t.inherits(callExpr, path.node));
      }
    },
  };

  return visitor;

  function convertJSXIdentifier(node, parent) {
    if (t.isJSXIdentifier(node)) {
      if (node.name === "this" && t.isReferenced(node, parent)) {
        return t.thisExpression();
      } else if (esutils.keyword.isIdentifierNameES6(node.name)) {
        node.type = "Identifier";
      } else {
        return t.stringLiteral(node.name);
      }
    } else if (t.isJSXMemberExpression(node)) {
      return t.memberExpression(
        convertJSXIdentifier(node.object, node),
        convertJSXIdentifier(node.property, node),
      );
    } else if (t.isJSXNamespacedName(node)) {
      /**
       * If there is flag "throwIfNamespace"
       * print XMLNamespace like string literal
       */
      return t.stringLiteral(`${node.namespace.name}:${node.name.name}`);
    }

    return node;
  }

  function convertAttributeValue(node) {
    if (t.isJSXExpressionContainer(node)) {
      return node.expression;
    } else {
      return node;
    }
  }

  function convertAttribute(node) {
    const value = convertAttributeValue(node.value || t.booleanLiteral(true));

    if (t.isStringLiteral(value) && !t.isJSXExpressionContainer(node.value)) {
      value.value = value.value.replace(/\n\s+/g, " ");

      // "raw" JSXText should not be used from a StringLiteral because it needs to be escaped.
      if (value.extra && value.extra.raw) {
        delete value.extra.raw;
      }
    }

    if (t.isJSXNamespacedName(node.name)) {
      node.name = t.stringLiteral(
        node.name.namespace.name + ":" + node.name.name.name,
      );
    } else if (esutils.keyword.isIdentifierNameES6(node.name.name)) {
      node.name.type = "Identifier";
    } else {
      node.name = t.stringLiteral(node.name.name);
    }

    return t.inherits(t.objectProperty(node.name, value), node);
  }

  function buildElementCall(path, file) {
    if (opts.filter && !opts.filter(path.node, file)) return;

    const openingPath = path.get("openingElement");
    openingPath.parent.children = t.react.buildChildren(openingPath.parent);

    const tagExpr = convertJSXIdentifier(
      openingPath.node.name,
      openingPath.node,
    );
    const args = [];

    let tagName;
    if (t.isIdentifier(tagExpr)) {
      tagName = tagExpr.name;
    } else if (t.isLiteral(tagExpr)) {
      tagName = tagExpr.value;
    }

    const state: ElementState = {
      tagExpr: tagExpr,
      tagName: tagName,
      args: args,
    };

    if (opts.pre) {
      opts.pre(state, file);
    }

    let attribs = openingPath.node.attributes;
    if (attribs.length) {
      attribs = buildOpeningElementAttributes(attribs, file);
    } else {
      attribs = t.nullLiteral();
    }

    args.push(attribs, ...path.node.children);

    if (opts.post) {
      opts.post(state, file);
    }

    return state.call || t.callExpression(state.callee, args);
  }

  function pushProps(_props, objs) {
    if (!_props.length) return _props;

    objs.push(t.objectExpression(_props));
    return [];
  }

  /**
   * The logic for this is quite terse. It's because we need to
   * support spread elements. We loop over all attributes,
   * breaking on spreads, we then push a new object containing
   * all prior attributes to an array for later processing.
   */

  function buildOpeningElementAttributes(attribs, file) {
    let _props = [];
    const objs = [];

    const useBuiltIns = file.opts.useBuiltIns || false;
    if (typeof useBuiltIns !== "boolean") {
      throw new Error(
        "transform-react-jsx currently only accepts a boolean option for " +
          "useBuiltIns (defaults to false)",
      );
    }

    while (attribs.length) {
      const prop = attribs.shift();
      if (t.isJSXSpreadAttribute(prop)) {
        _props = pushProps(_props, objs);
        objs.push(prop.argument);
      } else {
        _props.push(convertAttribute(prop));
      }
    }

    pushProps(_props, objs);

    if (objs.length === 1) {
      // only one object
      attribs = objs[0];
    } else {
      // looks like we have multiple objects
      if (!t.isObjectExpression(objs[0])) {
        objs.unshift(t.objectExpression([]));
      }

      const helper = useBuiltIns
        ? t.memberExpression(t.identifier("Object"), t.identifier("assign"))
        : file.addHelper("extends");

      // spread it
      attribs = t.callExpression(helper, objs);
    }

    return attribs;
  }

  function buildFragmentCall(path, file) {
    if (opts.filter && !opts.filter(path.node, file)) return;

    const openingPath = path.get("openingElement");
    openingPath.parent.children = t.react.buildChildren(openingPath.parent);

    const args = [];
    const tagName = null;
    const tagExpr = file.get("jsxFragIdentifier")();

    const state: ElementState = {
      tagExpr: tagExpr,
      tagName: tagName,
      args: args,
    };

    if (opts.pre) {
      opts.pre(state, file);
    }

    // no attributes are allowed with <> syntax
    args.push(t.nullLiteral(), ...path.node.children);

    if (opts.post) {
      opts.post(state, file);
    }

    file.set("usedFragment", true);
    return state.call || t.callExpression(state.callee, args);
  }
}
<commit_msg>Nit: Use ?.  in the example used by the proposal readme (#10604)<commit_after>import esutils from "esutils";
import * as t from "@babel/types";

type ElementState = {
  tagExpr: Object, // tag node
  tagName: ?string, // raw string tag name
  args: Array<Object>, // array of call arguments
  call?: Object, // optional call property that can be set to override the call expression returned
};

export default function(opts) {
  const visitor = {};

  visitor.JSXNamespacedName = function(path) {
    if (opts.throwIfNamespace) {
      throw path.buildCodeFrameError(
        `Namespace tags are not supported by default. React's JSX doesn't support namespace tags. \
You can turn on the 'throwIfNamespace' flag to bypass this warning.`,
      );
    }
  };

  visitor.JSXSpreadChild = function(path) {
    throw path.buildCodeFrameError(
      "Spread children are not supported in React.",
    );
  };

  visitor.JSXElement = {
    exit(path, file) {
      const callExpr = buildElementCall(path, file);
      if (callExpr) {
        path.replaceWith(t.inherits(callExpr, path.node));
      }
    },
  };

  visitor.JSXFragment = {
    exit(path, file) {
      if (opts.compat) {
        throw path.buildCodeFrameError(
          "Fragment tags are only supported in React 16 and up.",
        );
      }
      const callExpr = buildFragmentCall(path, file);
      if (callExpr) {
        path.replaceWith(t.inherits(callExpr, path.node));
      }
    },
  };

  return visitor;

  function convertJSXIdentifier(node, parent) {
    if (t.isJSXIdentifier(node)) {
      if (node.name === "this" && t.isReferenced(node, parent)) {
        return t.thisExpression();
      } else if (esutils.keyword.isIdentifierNameES6(node.name)) {
        node.type = "Identifier";
      } else {
        return t.stringLiteral(node.name);
      }
    } else if (t.isJSXMemberExpression(node)) {
      return t.memberExpression(
        convertJSXIdentifier(node.object, node),
        convertJSXIdentifier(node.property, node),
      );
    } else if (t.isJSXNamespacedName(node)) {
      /**
       * If there is flag "throwIfNamespace"
       * print XMLNamespace like string literal
       */
      return t.stringLiteral(`${node.namespace.name}:${node.name.name}`);
    }

    return node;
  }

  function convertAttributeValue(node) {
    if (t.isJSXExpressionContainer(node)) {
      return node.expression;
    } else {
      return node;
    }
  }

  function convertAttribute(node) {
    const value = convertAttributeValue(node.value || t.booleanLiteral(true));

    if (t.isStringLiteral(value) && !t.isJSXExpressionContainer(node.value)) {
      value.value = value.value.replace(/\n\s+/g, " ");

      // "raw" JSXText should not be used from a StringLiteral because it needs to be escaped.
      delete value.extra?.raw;
    }

    if (t.isJSXNamespacedName(node.name)) {
      node.name = t.stringLiteral(
        node.name.namespace.name + ":" + node.name.name.name,
      );
    } else if (esutils.keyword.isIdentifierNameES6(node.name.name)) {
      node.name.type = "Identifier";
    } else {
      node.name = t.stringLiteral(node.name.name);
    }

    return t.inherits(t.objectProperty(node.name, value), node);
  }

  function buildElementCall(path, file) {
    if (opts.filter && !opts.filter(path.node, file)) return;

    const openingPath = path.get("openingElement");
    openingPath.parent.children = t.react.buildChildren(openingPath.parent);

    const tagExpr = convertJSXIdentifier(
      openingPath.node.name,
      openingPath.node,
    );
    const args = [];

    let tagName;
    if (t.isIdentifier(tagExpr)) {
      tagName = tagExpr.name;
    } else if (t.isLiteral(tagExpr)) {
      tagName = tagExpr.value;
    }

    const state: ElementState = {
      tagExpr: tagExpr,
      tagName: tagName,
      args: args,
    };

    if (opts.pre) {
      opts.pre(state, file);
    }

    let attribs = openingPath.node.attributes;
    if (attribs.length) {
      attribs = buildOpeningElementAttributes(attribs, file);
    } else {
      attribs = t.nullLiteral();
    }

    args.push(attribs, ...path.node.children);

    if (opts.post) {
      opts.post(state, file);
    }

    return state.call || t.callExpression(state.callee, args);
  }

  function pushProps(_props, objs) {
    if (!_props.length) return _props;

    objs.push(t.objectExpression(_props));
    return [];
  }

  /**
   * The logic for this is quite terse. It's because we need to
   * support spread elements. We loop over all attributes,
   * breaking on spreads, we then push a new object containing
   * all prior attributes to an array for later processing.
   */

  function buildOpeningElementAttributes(attribs, file) {
    let _props = [];
    const objs = [];

    const useBuiltIns = file.opts.useBuiltIns || false;
    if (typeof useBuiltIns !== "boolean") {
      throw new Error(
        "transform-react-jsx currently only accepts a boolean option for " +
          "useBuiltIns (defaults to false)",
      );
    }

    while (attribs.length) {
      const prop = attribs.shift();
      if (t.isJSXSpreadAttribute(prop)) {
        _props = pushProps(_props, objs);
        objs.push(prop.argument);
      } else {
        _props.push(convertAttribute(prop));
      }
    }

    pushProps(_props, objs);

    if (objs.length === 1) {
      // only one object
      attribs = objs[0];
    } else {
      // looks like we have multiple objects
      if (!t.isObjectExpression(objs[0])) {
        objs.unshift(t.objectExpression([]));
      }

      const helper = useBuiltIns
        ? t.memberExpression(t.identifier("Object"), t.identifier("assign"))
        : file.addHelper("extends");

      // spread it
      attribs = t.callExpression(helper, objs);
    }

    return attribs;
  }

  function buildFragmentCall(path, file) {
    if (opts.filter && !opts.filter(path.node, file)) return;

    const openingPath = path.get("openingElement");
    openingPath.parent.children = t.react.buildChildren(openingPath.parent);

    const args = [];
    const tagName = null;
    const tagExpr = file.get("jsxFragIdentifier")();

    const state: ElementState = {
      tagExpr: tagExpr,
      tagName: tagName,
      args: args,
    };

    if (opts.pre) {
      opts.pre(state, file);
    }

    // no attributes are allowed with <> syntax
    args.push(t.nullLiteral(), ...path.node.children);

    if (opts.post) {
      opts.post(state, file);
    }

    file.set("usedFragment", true);
    return state.call || t.callExpression(state.callee, args);
  }
}
<|endoftext|>


<commit_before>import { localizedRoute as localizedRouteHelper, localizedDispatcherRoute as localizedDispatcherRouteHelper, currentStoreView } from '@vue-storefront/core/lib/multistore'

export const multistore = {
  methods: {
    /**
     * Return localized route params
     * @param {String} relativeUrl
     * @param {Int} width
     * @param {Int} height
     */
    localizedRoute (routeObj) {
      const storeView = currentStoreView()
      return localizedRouteHelper(routeObj, storeView.storeCode)
    },
    /**
     * Return localized route params for URL Dispatcher
     * @param {String} relativeUrl
     * @param {Int} width
     * @param {Int} height
     */
    localizedDispatcherRoute (routeObj) {
      const storeView = currentStoreView()
      return localizedDispatcherRouteHelper(routeObj, storeView.storeCode)
    }
  }
}
<commit_msg>Fix outdated references of multistore mixin in SSR<commit_after>export const multistore = {
  methods: {
    /**
     * Return localized route params
     * @param {String} relativeUrl
     * @param {Int} width
     * @param {Int} height
     */
    async localizedRoute (routeObj) {
      // importing this way is crucial to always have a fresh multistore instance reference to store in SSR
      const {localizedRoute, currentStoreView} = await import('@vue-storefront/core/lib/multistore')
      const storeView = currentStoreView()
      return localizedRoute(routeObj, storeView.storeCode)
    },
    /**
     * Return localized route params for URL Dispatcher
     * @param {String} relativeUrl
     * @param {Int} width
     * @param {Int} height
     */
    async localizedDispatcherRoute (routeObj) {
      const {localizedDispatcherRoute, currentStoreView} = await import('@vue-storefront/core/lib/multistore')
      const storeView = currentStoreView()
      return localizedDispatcherRoute(routeObj, storeView.storeCode)
    }
  }
}
<|endoftext|>


<commit_before>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global createEmptyObject, Multiname, TelemetryService, SHAREDOBJECT_FEATURE, sessionStorage */

var SharedObjectDefinition = (function () {

  var _defaultObjectEncoding = 3;

  var sharedObjects = createEmptyObject();

  function invokeWithArgsArray(index, args) {
    var simulated = false, result;
    switch (index) {
    case 4: // get size()
      result = JSON.stringify(this._data).length - 2;
      simulated = true;
      break;
    case 6: // clear
      this._data = {};
      sessionStorage.removeItem(this._path);
      simulated = true;
      break;
    case 2: // flush
      sessionStorage.setItem(this._path, JSON.stringify(this._data));
      simulated = true;
      result = true;
      break;
    case 3: // close
      simulated = true;
      break;
    }
    (simulated ? somewhatImplemented : notImplemented)(
      "SharedObject.invoke (" + index + ")");
    return result;
  }

  return {
    // ()
    __class__: "flash.net.SharedObject",
    initialize: function () {
      this._path = null;
      this._data = null;
      this._objectEncoding = _defaultObjectEncoding;

      TelemetryService.reportTelemetry({topic: 'feature', feature: SHAREDOBJECT_FEATURE});
    },
    __glue__: {
      native: {
        static: {
          deleteAll: function deleteAll(url) { // (url:String) -> int
            notImplemented("SharedObject.deleteAll");
          },
          getDiskUsage: function getDiskUsage(url) { // (url:String) -> int
            notImplemented("SharedObject.getDiskUsage");
          },
          getLocal: function getLocal(name, localPath, secure) { // (name:String, localPath:String = null, secure:Boolean = false) -> SharedObject
            var path = (localPath || '') + '/' + name;
            if (sharedObjects[path]) {
              return sharedObjects[path];
            }
            var so = new flash.net.SharedObject();
            so._path = path;
            var data = sessionStorage.getItem(path);
            so._data = data ? JSON.parse(data) : {};
            so._data[Multiname.getPublicQualifiedName("cookie")] = {};
            so._data[Multiname.getPublicQualifiedName("cookie")][Multiname.getPublicQualifiedName("lc")] = 32;
            so._data[Multiname.getPublicQualifiedName("levelCompleted")] = 32;
            so._data[Multiname.getPublicQualifiedName("completeLevels")] = 32;
            return so;
          },
          getRemote: function getRemote(name, remotePath, persistence, secure) { // (name:String, remotePath:String = null, persistence:Object = false, secure:Boolean = false) -> SharedObject
            notImplemented("SharedObject.getRemote");
          },
          defaultObjectEncoding: {
            get: function defaultObjectEncoding() { // (void) -> uint
              return _defaultObjectEncoding;
            },
            set: function defaultObjectEncoding(version) { // (version:uint) -> void
              _defaultObjectEncoding = version;
            }
          }
        },
        instance: {
          setDirty: function setDirty(propertyName) { // (propertyName:String) -> void
            somewhatImplemented("SharedObject.setDirty");
          },
          invoke: function invoke(index) { // (index:uint) -> any
            return invokeWithArgsArray.call(this, index,
              Array.prototype.slice.call(arguments, 1));
          },
          invokeWithArgsArray: function invokeWithArgsArray(index, args) { // (index:uint, args:Array) -> any
            return invokeWithArgsArray.call(this, index, args);
          },
          data: {
            get: function data() { // (void) -> Object
              return this._data;
            }
          },
          objectEncoding: {
            get: function objectEncoding() { // (void) -> uint
              return this._objectEncoding;
            },
            set: function objectEncoding(version) { // (version:uint) -> void
              this._objectEncoding = version;
            }
          },
          client: {
            get: function client() { // (void) -> Object
              notImplemented("SharedObject.client");
              return this._client;
            },
            set: function client(object) { // (object:Object) -> void
              notImplemented("SharedObject.client");
              this._client = object;
            }
          }
        }
      }
    }
  };
}).call(this);
<commit_msg>Comment out default shared object values.<commit_after>/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
 * Copyright 2013 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*global createEmptyObject, Multiname, TelemetryService, SHAREDOBJECT_FEATURE, sessionStorage */

var SharedObjectDefinition = (function () {

  var _defaultObjectEncoding = 3;

  var sharedObjects = createEmptyObject();

  function invokeWithArgsArray(index, args) {
    var simulated = false, result;
    switch (index) {
    case 4: // get size()
      result = JSON.stringify(this._data).length - 2;
      simulated = true;
      break;
    case 6: // clear
      this._data = {};
      sessionStorage.removeItem(this._path);
      simulated = true;
      break;
    case 2: // flush
      sessionStorage.setItem(this._path, JSON.stringify(this._data));
      simulated = true;
      result = true;
      break;
    case 3: // close
      simulated = true;
      break;
    }
    (simulated ? somewhatImplemented : notImplemented)(
      "SharedObject.invoke (" + index + ")");
    return result;
  }

  return {
    // ()
    __class__: "flash.net.SharedObject",
    initialize: function () {
      this._path = null;
      this._data = null;
      this._objectEncoding = _defaultObjectEncoding;

      TelemetryService.reportTelemetry({topic: 'feature', feature: SHAREDOBJECT_FEATURE});
    },
    __glue__: {
      native: {
        static: {
          deleteAll: function deleteAll(url) { // (url:String) -> int
            notImplemented("SharedObject.deleteAll");
          },
          getDiskUsage: function getDiskUsage(url) { // (url:String) -> int
            notImplemented("SharedObject.getDiskUsage");
          },
          getLocal: function getLocal(name, localPath, secure) { // (name:String, localPath:String = null, secure:Boolean = false) -> SharedObject
            var path = (localPath || '') + '/' + name;
            if (sharedObjects[path]) {
              return sharedObjects[path];
            }
            var so = new flash.net.SharedObject();
            so._path = path;
            var data = sessionStorage.getItem(path);
            so._data = data ? JSON.parse(data) : {};
            // so._data[Multiname.getPublicQualifiedName("cookie")] = {};
            // so._data[Multiname.getPublicQualifiedName("cookie")][Multiname.getPublicQualifiedName("lc")] = 32;
            // so._data[Multiname.getPublicQualifiedName("levelCompleted")] = 32;
            // so._data[Multiname.getPublicQualifiedName("completeLevels")] = 32;
            return so;
          },
          getRemote: function getRemote(name, remotePath, persistence, secure) { // (name:String, remotePath:String = null, persistence:Object = false, secure:Boolean = false) -> SharedObject
            notImplemented("SharedObject.getRemote");
          },
          defaultObjectEncoding: {
            get: function defaultObjectEncoding() { // (void) -> uint
              return _defaultObjectEncoding;
            },
            set: function defaultObjectEncoding(version) { // (version:uint) -> void
              _defaultObjectEncoding = version;
            }
          }
        },
        instance: {
          setDirty: function setDirty(propertyName) { // (propertyName:String) -> void
            somewhatImplemented("SharedObject.setDirty");
          },
          invoke: function invoke(index) { // (index:uint) -> any
            return invokeWithArgsArray.call(this, index,
              Array.prototype.slice.call(arguments, 1));
          },
          invokeWithArgsArray: function invokeWithArgsArray(index, args) { // (index:uint, args:Array) -> any
            return invokeWithArgsArray.call(this, index, args);
          },
          data: {
            get: function data() { // (void) -> Object
              return this._data;
            }
          },
          objectEncoding: {
            get: function objectEncoding() { // (void) -> uint
              return this._objectEncoding;
            },
            set: function objectEncoding(version) { // (version:uint) -> void
              this._objectEncoding = version;
            }
          },
          client: {
            get: function client() { // (void) -> Object
              notImplemented("SharedObject.client");
              return this._client;
            },
            set: function client(object) { // (object:Object) -> void
              notImplemented("SharedObject.client");
              this._client = object;
            }
          }
        }
      }
    }
  };
}).call(this);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

/**
 * Time To Live (TTL) Caching DAO only caches find() operations
 * for a limited amount of time.
*/
foam.CLASS({
  package: 'foam.dao',
  name: 'TTLCachingDAO',
  extends: 'foam.dao.ProxyDAO',

  requires: [
    'foam.dao.DAOSink',
    'foam.dao.PromisedDAO',
    'foam.dao.QuickSink'
  ],

  properties: [
    {
      /** The cache to read items quickly. */
      name: 'cache'
    },
    {
      class: 'Long',
      name: 'purgeTime'
    },
  ],

  methods: [
    function find_(x, key) {
      var id = this.of.isInstance(key) ? key.id : key;
      var cachedValue = this.cache[id];
      var self = this;

      if ( foam.Undefined.isInstance(cachedValue) ) {
        this.delegate.find_(x, key).then(function(o) {
          self.cache[id] = o;
          return o;
        });
      } else {
        console.log('********************************** CACHED VALUE', id);
        return Promise.resolve(cachedValue);
      }
    },

    /** Puts are sent to the cache and to the source, ensuring both
      are up to date. */
    function put_(x, o) {
      var self = this;
      // ensure the returned object from src is cached.
      return self.delegate.put(o).then(function(srcObj) {
        self.cache[o.id] = srcObj;
        return srcObj;
      });
    },

    function select_(x, sink) {
      var self = this;

      return new Promise(function (resolve, reject) {
        this.delegate.sink(x, sink).then(function(s) {
          if ( foam.dao.ArraySink.isInstance(s) ) {
            var a = s.array;
            for ( var i = 0 ; i < a.length ; i++ ) {
              var o = a[i];
              console.log('***** caching ', o.id);
              self.cache[o.id] = o;
            }
          }
          promise.resolve(s);
        });
      });
    },

    /** Removes are sent to the cache and to the source, ensuring both
      are up to date. */
    function remove_(x, o) {
      var self = this;
      return self.delegate.remove(o).then(function() {
        self.cache.remove(o);
        return o;
      });
    },

    /** removeAll is executed on the cache and the source, ensuring both
      are up to date. */
    function removeAll_(x, skip, limit, order, predicate) {
      var self = this;
      return self.src.removeAll_(x, skip, limit, order, predicate).then(function() {
        self.cache = {};
        return;
      });
    }
  ],

  listeners: [
    {
      name: 'purgeCache',
      isMerged: true,
      mergeDelay: this.purgeTime,
      code: function() {
        this.cache = {};
        this.purgeCache();
      }
    }
  ]
});
<commit_msg>Update src/foam/dao/TTLCachingDAO.js<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

/**
 * Time To Live (TTL) Caching DAO only caches find() operations
 * for a limited amount of time.
*/
foam.CLASS({
  package: 'foam.dao',
  name: 'TTLCachingDAO',
  extends: 'foam.dao.ProxyDAO',

  requires: [
    'foam.dao.DAOSink',
    'foam.dao.PromisedDAO',
    'foam.dao.QuickSink'
  ],

  properties: [
    {
      /** The cache to read items quickly. */
      name: 'cache'
    },
    {
      class: 'Long',
      name: 'purgeTime'
      value: 15000
    },
  ],

  methods: [
    function find_(x, key) {
      var id = this.of.isInstance(key) ? key.id : key;
      var cachedValue = this.cache[id];
      var self = this;

      if ( foam.Undefined.isInstance(cachedValue) ) {
        this.delegate.find_(x, key).then(function(o) {
          self.cache[id] = o;
          return o;
        });
      } else {
        console.log('********************************** CACHED VALUE', id);
        return Promise.resolve(cachedValue);
      }
    },

    /** Puts are sent to the cache and to the source, ensuring both
      are up to date. */
    function put_(x, o) {
      var self = this;
      // ensure the returned object from src is cached.
      return self.delegate.put(o).then(function(srcObj) {
        self.cache[o.id] = srcObj;
        return srcObj;
      });
    },

    function select_(x, sink) {
      var self = this;

      return new Promise(function (resolve, reject) {
        this.delegate.sink(x, sink).then(function(s) {
          if ( foam.dao.ArraySink.isInstance(s) ) {
            var a = s.array;
            for ( var i = 0 ; i < a.length ; i++ ) {
              var o = a[i];
              console.log('***** caching ', o.id);
              self.cache[o.id] = o;
            }
          }
          promise.resolve(s);
        });
      });
    },

    /** Removes are sent to the cache and to the source, ensuring both
      are up to date. */
    function remove_(x, o) {
      var self = this;
      return self.delegate.remove(o).then(function() {
        self.cache.remove(o);
        return o;
      });
    },

    /** removeAll is executed on the cache and the source, ensuring both
      are up to date. */
    function removeAll_(x, skip, limit, order, predicate) {
      var self = this;
      return self.src.removeAll_(x, skip, limit, order, predicate).then(function() {
        self.cache = {};
        return;
      });
    }
  ],

  listeners: [
    {
      name: 'purgeCache',
      isMerged: true,
      mergeDelay: this.purgeTime,
      code: function() {
        this.cache = {};
        this.purgeCache();
      }
    }
  ]
});
<|endoftext|>


<commit_before>(function () {
    var replay = glinamespace("gli.replay");

    var Controller = function () {
        this.output = {};

        this.currentFrame = null;
        this.callIndex = 0;
        this.stepping = false;

        this.stepCompleted = new gli.EventSource("stepCompleted");
    };

    Controller.prototype.setOutput = function (canvas) {
        this.output.canvas = canvas;
        try {
            if (canvas.getContextRaw) {
                this.output.gl = canvas.getContextRaw("experimental-webgl");
            } else {
                this.output.gl = canvas.getContext("experimental-webgl");
            }
        } catch (e) {
            // ?
            alert("Unable to create replay canvas: " + e);
        }
        gli.hacks.installAll(this.output.gl);
        gli.info.initialize(this.output.gl);
    };

    Controller.prototype.reset = function () {
        this.currentFrame = null;
        this.callIndex = 0;
        this.stepping = false;
    };

    Controller.prototype.getCurrentState = function () {
        return new gli.host.StateSnapshot(this.output.gl);
    };

    Controller.prototype.openFrame = function (frame) {
        var gl = this.output.gl;

        this.currentFrame = frame;

        frame.makeActive(gl);

        this.beginStepping();
        this.callIndex = 0;
        this.endStepping();
    };

    function emitMark(mark) {
        console.log("mark hit");
    };

    function emitCall(gl, call) {
        var args = [];
        for (var n = 0; n < call.args.length; n++) {
            args[n] = call.args[n];

            if (args[n]) {
                if (args[n].mirror) {
                    // Translate from resource -> mirror target
                    args[n] = args[n].mirror.target;
                } else if (args[n].sourceUniformName) {
                    // Get valid uniform location on new context
                    args[n] = gl.getUniformLocation(args[n].sourceProgram.mirror.target, args[n].sourceUniformName);
                }
            }
        }

        // TODO: handle result?
        gl[call.name].apply(gl, args);
        //console.log("call " + call.name);
    };

    Controller.prototype.issueCall = function (callIndex) {
        var gl = this.output.gl;

        if (this.currentFrame == null) {
            return false;
        }
        if (this.callIndex + 1 > this.currentFrame.calls.length) {
            return false;
        }

        if (callIndex >= 0) {
            this.callIndex = callIndex;
        } else {
            callIndex = this.callIndex;
        }

        var call = this.currentFrame.calls[callIndex];

        switch (call.type) {
            case 0: // MARK
                emitMark(call);
                break;
            case 1: // GL
                emitCall(gl, call);
                break;
        }

        return true;
    };

    Controller.prototype.beginStepping = function () {
        this.stepping = true;
    };

    Controller.prototype.endStepping = function () {
        this.stepping = false;
        this.stepCompleted.fire();
    };

    Controller.prototype.stepUntil = function (callIndex) {
        if (this.callIndex > callIndex) {
            var frame = this.currentFrame;
            this.reset();
            this.openFrame(frame);
        }
        this.beginStepping();
        while (this.callIndex <= callIndex) {
            if (this.issueCall()) {
                this.callIndex++;
            } else {
                this.endStepping();
                return false;
            }
        }
        this.endStepping();
        return true;
    };

    Controller.prototype.stepForward = function () {
        return this.stepUntil(this.callIndex);
    };

    Controller.prototype.stepBackward = function () {
        if (this.callIndex == 0) {
            return false;
        }
        return this.stepUntil(this.callIndex - 2);
    };

    Controller.prototype.stepUntilError = function () {
        //
    };

    Controller.prototype.stepUntilDraw = function () {
        this.beginStepping();
        while (this.issueCall()) {
            var call = this.currentFrame.calls[this.callIndex];
            var info = gli.info.functions[call.name];
            if (info.type == gli.FunctionType.DRAW) {
                this.callIndex++;
                break;
            } else {
                this.callIndex++;
            }
        }
        this.endStepping();
    };

    Controller.prototype.stepUntilEnd = function () {
        this.beginStepping();
        while (this.stepForward());
        this.endStepping();
    };

    Controller.prototype.runFrame = function (frame) {
        this.openFrame(frame);
        this.stepUntilEnd();
    };

    Controller.prototype.runIsolatedDraw = function (frame, targetCall) {
        this.openFrame(frame);

        var gl = this.output.gl;

        this.beginStepping();
        while (true) {
            var call = this.currentFrame.calls[this.callIndex];
            var shouldExec = false;

            if (call.name == "clear") {
                // Allow clear calls
                shouldExec = true;
            } else if (call == targetCall) {
                // The target call
                shouldExec = true;

                // Before executing the call, clear the color buffer
                var oldColorClearValue = gl.getParameter(gl.COLOR_CLEAR_VALUE);
                gl.colorMask(true, true, true, true);
                gl.clearColor(0, 0, 0, 0);
                gl.clear(gl.COLOR_BUFFER_BIT);
                gl.clearColor(oldColorClearValue[0], oldColorClearValue[1], oldColorClearValue[2], oldColorClearValue[3]);
            } else {
                var info = gli.info.functions[call.name];
                if (info.type == gli.FunctionType.DRAW) {
                    // Ignore all other draws
                    shouldExec = false;
                } else {
                    shouldExec = true;
                }
            }

            if (shouldExec) {
                if (!this.issueCall()) {
                    break;
                }
            }

            this.callIndex++;
            if (call == targetCall) {
                break;
            }
        }
        this.openFrame(frame);
        this.endStepping();
    };

    replay.Controller = Controller;

})();
<commit_msg>greatly speed up initial frame playback but not firing events on each call<commit_after>(function () {
    var replay = glinamespace("gli.replay");

    var Controller = function () {
        this.output = {};

        this.currentFrame = null;
        this.callIndex = 0;
        this.stepping = false;

        this.stepCompleted = new gli.EventSource("stepCompleted");
    };

    Controller.prototype.setOutput = function (canvas) {
        this.output.canvas = canvas;
        try {
            if (canvas.getContextRaw) {
                this.output.gl = canvas.getContextRaw("experimental-webgl");
            } else {
                this.output.gl = canvas.getContext("experimental-webgl");
            }
        } catch (e) {
            // ?
            alert("Unable to create replay canvas: " + e);
        }
        gli.hacks.installAll(this.output.gl);
        gli.info.initialize(this.output.gl);
    };

    Controller.prototype.reset = function () {
        this.currentFrame = null;
        this.callIndex = 0;
        this.stepping = false;
    };

    Controller.prototype.getCurrentState = function () {
        return new gli.host.StateSnapshot(this.output.gl);
    };

    Controller.prototype.openFrame = function (frame) {
        var gl = this.output.gl;

        this.currentFrame = frame;

        frame.makeActive(gl);

        this.beginStepping();
        this.callIndex = 0;
        this.endStepping();
    };

    function emitMark(mark) {
        console.log("mark hit");
    };

    function emitCall(gl, call) {
        var args = [];
        for (var n = 0; n < call.args.length; n++) {
            args[n] = call.args[n];

            if (args[n]) {
                if (args[n].mirror) {
                    // Translate from resource -> mirror target
                    args[n] = args[n].mirror.target;
                } else if (args[n].sourceUniformName) {
                    // Get valid uniform location on new context
                    args[n] = gl.getUniformLocation(args[n].sourceProgram.mirror.target, args[n].sourceUniformName);
                }
            }
        }

        // TODO: handle result?
        gl[call.name].apply(gl, args);
        //console.log("call " + call.name);
    };

    Controller.prototype.issueCall = function (callIndex) {
        var gl = this.output.gl;

        if (this.currentFrame == null) {
            return false;
        }
        if (this.callIndex + 1 > this.currentFrame.calls.length) {
            return false;
        }

        if (callIndex >= 0) {
            this.callIndex = callIndex;
        } else {
            callIndex = this.callIndex;
        }

        var call = this.currentFrame.calls[callIndex];

        switch (call.type) {
            case 0: // MARK
                emitMark(call);
                break;
            case 1: // GL
                emitCall(gl, call);
                break;
        }

        return true;
    };

    Controller.prototype.beginStepping = function () {
        this.stepping = true;
    };

    Controller.prototype.endStepping = function () {
        this.stepping = false;
        this.stepCompleted.fire();
    };

    Controller.prototype.stepUntil = function (callIndex) {
        if (this.callIndex > callIndex) {
            var frame = this.currentFrame;
            this.reset();
            this.openFrame(frame);
        }
        var wasStepping = this.stepping;
        if (!wasStepping) {
            this.beginStepping();
        }
        while (this.callIndex <= callIndex) {
            if (this.issueCall()) {
                this.callIndex++;
            } else {
                this.endStepping();
                return false;
            }
        }
        if (!wasStepping) {
            this.endStepping();
        }
        return true;
    };

    Controller.prototype.stepForward = function () {
        return this.stepUntil(this.callIndex);
    };

    Controller.prototype.stepBackward = function () {
        if (this.callIndex == 0) {
            return false;
        }
        return this.stepUntil(this.callIndex - 2);
    };

    Controller.prototype.stepUntilError = function () {
        //
    };

    Controller.prototype.stepUntilDraw = function () {
        this.beginStepping();
        while (this.issueCall()) {
            var call = this.currentFrame.calls[this.callIndex];
            var info = gli.info.functions[call.name];
            if (info.type == gli.FunctionType.DRAW) {
                this.callIndex++;
                break;
            } else {
                this.callIndex++;
            }
        }
        this.endStepping();
    };

    Controller.prototype.stepUntilEnd = function () {
        this.beginStepping();
        while (this.stepForward());
        this.endStepping();
    };

    Controller.prototype.runFrame = function (frame) {
        this.openFrame(frame);
        this.stepUntilEnd();
    };

    Controller.prototype.runIsolatedDraw = function (frame, targetCall) {
        this.openFrame(frame);

        var gl = this.output.gl;

        this.beginStepping();
        while (true) {
            var call = this.currentFrame.calls[this.callIndex];
            var shouldExec = false;

            if (call.name == "clear") {
                // Allow clear calls
                shouldExec = true;
            } else if (call == targetCall) {
                // The target call
                shouldExec = true;

                // Before executing the call, clear the color buffer
                var oldColorClearValue = gl.getParameter(gl.COLOR_CLEAR_VALUE);
                gl.colorMask(true, true, true, true);
                gl.clearColor(0, 0, 0, 0);
                gl.clear(gl.COLOR_BUFFER_BIT);
                gl.clearColor(oldColorClearValue[0], oldColorClearValue[1], oldColorClearValue[2], oldColorClearValue[3]);
            } else {
                var info = gli.info.functions[call.name];
                if (info.type == gli.FunctionType.DRAW) {
                    // Ignore all other draws
                    shouldExec = false;
                } else {
                    shouldExec = true;
                }
            }

            if (shouldExec) {
                if (!this.issueCall()) {
                    break;
                }
            }

            this.callIndex++;
            if (call == targetCall) {
                break;
            }
        }
        this.openFrame(frame);
        this.endStepping();
    };

    replay.Controller = Controller;

})();
<|endoftext|>


<commit_before>
/*!
 * Module dependencies
 */

var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Feature schema
 */

var FeatureSchema = new Schema({
	creator: { type: Schema.ObjectId, ref: 'User'},
	contents: [{ type: Schema.ObjectId, ref: 'Conent'}],
	visibility: { type: String, enum: ['Public', 'Visible', 'Private'], default: 'Private'},
	title: { type: String, required: true },
	description: { type: String },
	geometry: { type: {type: String}, coordinates: []},
	version: { type: Number, default: 1},
	createdAt: {type: Date, default: Date.now},
	updateAt: {type: Date, default: Date.now},
	tags: [String]
})

/**
 * Geo index
 **/

FeatureSchema.index({ loc: '2dsphere' })

/**
 * Statics
 */

FeatureSchema.statics = {

	/**
	 * Find feature by id
	 *
	 * @param {ObjectId} id
	 * @param {Function} cb
	 * @api private
	 */

	load: function (id, cb) {
		this.findOne({ _id : id })
			.populate('creator')
			.exec(cb)
	},

	/**
	 * List feature
	 *
	 * @param {Object} options
	 * @param {Function} cb
	 * @api private
	 */

	list: function (options, cb) {
		var criteria = options.criteria || {}

		this.find(criteria)
			.sort({'createdAt': -1}) // sort by date
			.limit(options.perPage)
			.skip(options.perPage * options.page)
		.exec(cb)
	}

}

mongoose.model('Feature', FeatureSchema)<commit_msg>layer and creator are required attributes for feature<commit_after>
/*!
 * Module dependencies
 */

var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Feature schema
 */

var FeatureSchema = new Schema({
	creator: { type: Schema.ObjectId, ref: 'User', required: true},
	layer: { type: Schema.ObjectId, ref: 'layer', required: true},
	contents: [{ type: Schema.ObjectId, ref: 'Conent'}],
	visibility: { type: String, enum: ['Public', 'Visible', 'Private'], default: 'Private'},
	title: { type: String, required: true },
	description: { type: String },
	geometry: { type: {type: String}, coordinates: []},
	version: { type: Number, default: 1},
	createdAt: {type: Date, default: Date.now},
	updateAt: {type: Date, default: Date.now},
	tags: [String]
})

/**
 * Geo index
 **/

FeatureSchema.index({ loc: '2dsphere' })

/**
 * Statics
 */

FeatureSchema.statics = {

	/**
	 * Find feature by id
	 *
	 * @param {ObjectId} id
	 * @param {Function} cb
	 * @api private
	 */

	load: function (id, cb) {
		this.findOne({ _id : id })
			.populate('creator')
			.exec(cb)
	},

	/**
	 * List feature
	 *
	 * @param {Object} options
	 * @param {Function} cb
	 * @api private
	 */

	list: function (options, cb) {
		var criteria = options.criteria || {}

		this.find(criteria)
			.sort({'createdAt': -1}) // sort by date
			.limit(options.perPage)
			.skip(options.perPage * options.page)
		.exec(cb)
	}

}

mongoose.model('Feature', FeatureSchema)<|endoftext|>


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

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TableCellPropertyRefinement',

  refines: 'foam.core.Property',

  properties: [
    {
      name: 'tableHeaderFormatter',
      value: function(axiom) {
        this.add(axiom.label);
      }
    },
    {
      name: 'tableCellFormatter',
      value: function(value, obj, axiom) {
        this.add(value);
      }
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Action',

  properties: [
    {
      name: 'tableCellFormatter',
      value: function(_, obj, axiom) {
        this.
          startContext({ data: obj }).
          add(axiom).
          endContext();
      }
    },
    {
      name: 'tableHeaderFormatter',
      value: function(axiom) {
        this.add(axiom.label);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TableView',
  extends: 'foam.u2.Element',

  implements: [ 'foam.mlang.Expressions' ],

  exports: [
    'columns',
    'selection',
    'hoverSelection'
  ],

  imports: [
    'editRecord?',
    'selection? as importSelection'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function CSS() {/*
        ^ th {
          text-align: left;
          white-space: nowrap;
        }

        ^row:hover {
          background: #eee;
        }

        ^selected {
          background: #eee;
          outline: 1px solid #f00;
        }
    */}
    })
  ],

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'data',
      postSet: function(_, data) {
        if ( ! this.of && data ) this.of = data.of;
      }
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'orderedDAO',
      expression: function(data, order) {
        return data ? data.orderBy(order) : foam.dao.NullDAO.create();
      }
    },
    {
      name: 'order'
    },
    {
      name: 'columns_',
      expression: function(columns, of) {
        var of = this.of;
        if ( ! of ) return [];

        return columns.map(function(p) {
          var c = typeof p == 'string' ?
            of.getAxiomByName(p) :
            p ;

           if ( ! c ) {
             console.error('Unknown table column: ', p);
           }

          return c;
        }).filter(function(c) { return c; });
      }
    },
    {
      name: 'columns',
      expression: function(of) {
        var of = this.of;
        if ( ! of ) return [];

        var tableColumns = of.getAxiomByName('tableColumns');

        if ( tableColumns ) return tableColumns.columns;

        return of.getAxiomsByClass(foam.core.Property).
            filter(function(p) { return ! p.hidden; }).
            map(foam.core.Property.NAME.f);
      }
    },
    'selection',
    'hoverSelection'
  ],

  methods: [
    function sortBy(column) {
      this.order = this.order === column ?
        this.DESC(column) :
        column;
    },

    function initE() {
      var view = this;

      this.
        addClass(this.myClass()).
        setNodeName('table').
        start('thead').
          add(this.slot(function(columns_) {
            return this.E('tr').
              forEach(columns_, function(column) {
                this.start('th').
                  addClass(view.myClass('th-' + column.name)).
                  on('click', function(e) { view.sortBy(column); }).
                  call(column.tableHeaderFormatter, [column]).
                  add(' ', this.slot(function(order) {
                    return column === order ? this.Entity.create({ name: '#9651' }) :
                        (view.Desc.isInstance(order) && order.arg1 === column) ? this.Entity.create({ name: '#9661' }) :
                        ''
                  }, view.order$)).
                end();
              });
          })).
          add(this.slot(function(columns_) {
            return this.
              E('tbody').
              select(this.orderedDAO$proxy, function(obj) {
                return this.
                  E('tr').
                    start('tr').
                      on('mouseover', function() { view.hoverSelection = obj; }).
                      on('click', function() {
                        view.selection = obj;
                        if ( view.importSelection$ ) view.importSelection = obj;
                        if ( view.editRecord$ ) view.editRecord(obj);
                      }).
                      addClass(this.slot(function(selection) {
                        if ( obj === selection ) return view.myClass('selected');
                        return '';
                      }, view.selection$)).
                      addClass(view.myClass('row')).
                      forEach(columns_, function(column) {
                        this.
                          start('td').
                          call(column.tableCellFormatter, [
                            column.f ? column.f(obj) : null, obj, column
                          ]).
                          end();
                      });
              });
          }));
    }
  ]
});
<commit_msg>TableView includes 'of' id in CSS class.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TableCellPropertyRefinement',

  refines: 'foam.core.Property',

  properties: [
    {
      name: 'tableHeaderFormatter',
      value: function(axiom) {
        this.add(axiom.label);
      }
    },
    {
      name: 'tableCellFormatter',
      value: function(value, obj, axiom) {
        this.add(value);
      }
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Action',

  properties: [
    {
      name: 'tableCellFormatter',
      value: function(_, obj, axiom) {
        this.
          startContext({ data: obj }).
          add(axiom).
          endContext();
      }
    },
    {
      name: 'tableHeaderFormatter',
      value: function(axiom) {
        this.add(axiom.label);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2.view',
  name: 'TableView',
  extends: 'foam.u2.Element',

  implements: [ 'foam.mlang.Expressions' ],

  exports: [
    'columns',
    'selection',
    'hoverSelection'
  ],

  imports: [
    'editRecord?',
    'selection? as importSelection'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function CSS() {/*
        ^ th {
          text-align: left;
          white-space: nowrap;
        }

        ^row:hover {
          background: #eee;
        }

        ^selected {
          background: #eee;
          outline: 1px solid #f00;
        }
    */}
    })
  ],

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'data',
      postSet: function(_, data) {
        if ( ! this.of && data ) this.of = data.of;
      }
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'orderedDAO',
      expression: function(data, order) {
        return data ? data.orderBy(order) : foam.dao.NullDAO.create();
      }
    },
    {
      name: 'order'
    },
    {
      name: 'columns_',
      expression: function(columns, of) {
        var of = this.of;
        if ( ! of ) return [];

        return columns.map(function(p) {
          var c = typeof p == 'string' ?
            of.getAxiomByName(p) :
            p ;

           if ( ! c ) {
             console.error('Unknown table column: ', p);
           }

          return c;
        }).filter(function(c) { return c; });
      }
    },
    {
      name: 'columns',
      expression: function(of) {
        var of = this.of;
        if ( ! of ) return [];

        var tableColumns = of.getAxiomByName('tableColumns');

        if ( tableColumns ) return tableColumns.columns;

        return of.getAxiomsByClass(foam.core.Property).
            filter(function(p) { return ! p.hidden; }).
            map(foam.core.Property.NAME.f);
      }
    },
    'selection',
    'hoverSelection'
  ],

  methods: [
    function sortBy(column) {
      this.order = this.order === column ?
        this.DESC(column) :
        column;
    },

    function initE() {
      var view = this;

      this.
        addClass(this.myClass()).
        addClass(this.myClass(this.of.id.replace(/\./g,'-'))).
        setNodeName('table').
        start('thead').
          add(this.slot(function(columns_) {
            return this.E('tr').
              forEach(columns_, function(column) {
                this.start('th').
                  addClass(view.myClass('th-' + column.name)).
                  on('click', function(e) { view.sortBy(column); }).
                  call(column.tableHeaderFormatter, [column]).
                  add(' ', this.slot(function(order) {
                    return column === order ? this.Entity.create({ name: '#9651' }) :
                        (view.Desc.isInstance(order) && order.arg1 === column) ? this.Entity.create({ name: '#9661' }) :
                        ''
                  }, view.order$)).
                end();
              });
          })).
          add(this.slot(function(columns_) {
            return this.
              E('tbody').
              select(this.orderedDAO$proxy, function(obj) {
                return this.
                  E('tr').
                    start('tr').
                      on('mouseover', function() { view.hoverSelection = obj; }).
                      on('click', function() {
                        view.selection = obj;
                        if ( view.importSelection$ ) view.importSelection = obj;
                        if ( view.editRecord$ ) view.editRecord(obj);
                      }).
                      addClass(this.slot(function(selection) {
                        if ( obj === selection ) return view.myClass('selected');
                        return '';
                      }, view.selection$)).
                      addClass(view.myClass('row')).
                      forEach(columns_, function(column) {
                        this.
                          start('td').
                          call(column.tableCellFormatter, [
                            column.f ? column.f(obj) : null, obj, column
                          ]).
                          end();
                      });
              });
          }));
    }
  ]
});
<|endoftext|>


<commit_before>import DS from 'ember-data';

var attr = DS.attr,
    belongsTo = DS.belongsTo;

export default DS.Model.extend({
  quantity:        attr('number'),
  length:          attr('number'),
  width:           attr('number'),
  height:          attr('number'),
  notes:           attr('string'),
  state:           attr('string', {defaultValue:'expecting'}),
  state_event:     attr('string'),
  receivedAt:      attr('date'),
  rejectedAt:      attr('date'),
  createdAt:       attr('date'),
  updatedAt:       attr('date'),
  item:            belongsTo('item', { async: true }),
  packageType:     belongsTo('package_type', { async: true }),
  imageId:         attr('number'),
  offerId:         attr('number'),

  packageName: function() {
    return this.get('packageType.name');
  }.property('packageType'),

  packageTypeObject: function() {
    var obj = this.get('packageType').getProperties('id', 'name', 'isItemTypeNode');
    obj.id = obj.packageTypeId = parseInt(obj.id);
    return obj;
  }.property('packageType'),

  dimensions: function() {
    var res = '';
    var append = val => {
      if (val) { res += !res ? val : ' x ' + val; }
    }
    append(this.get('width'));
    append(this.get('height'));
    append(this.get('length'));
    return !res ? '' : res + 'cm';
  }.property('width', 'height', 'length'),

  image: function() {
    return this.store.getById("image", this.get("imageId"));
  }.property("imageId"),

  displayImageUrl: function() {
    return this.get("image") ? this.get("image.thumbImageUrl") : this.get("item.displayImageUrl");
  }.property("image", "item.displayImageUrl")
});
<commit_msg>GCW-370 the fact package.item was async caused package.item.isRejected to return incorrect value not sure why (package.item.content.isRejected was correct)<commit_after>import DS from 'ember-data';

var attr = DS.attr,
    belongsTo = DS.belongsTo;

export default DS.Model.extend({
  quantity:        attr('number'),
  length:          attr('number'),
  width:           attr('number'),
  height:          attr('number'),
  notes:           attr('string'),
  state:           attr('string', {defaultValue:'expecting'}),
  state_event:     attr('string'),
  receivedAt:      attr('date'),
  rejectedAt:      attr('date'),
  createdAt:       attr('date'),
  updatedAt:       attr('date'),
  item:            belongsTo('item'),
  packageType:     belongsTo('package_type'),
  imageId:         attr('number'),
  offerId:         attr('number'),

  packageName: function() {
    return this.get('packageType.name');
  }.property('packageType'),

  packageTypeObject: function() {
    var obj = this.get('packageType').getProperties('id', 'name', 'isItemTypeNode');
    obj.id = obj.packageTypeId = parseInt(obj.id);
    return obj;
  }.property('packageType'),

  dimensions: function() {
    var res = '';
    var append = val => {
      if (val) { res += !res ? val : ' x ' + val; }
    }
    append(this.get('width'));
    append(this.get('height'));
    append(this.get('length'));
    return !res ? '' : res + 'cm';
  }.property('width', 'height', 'length'),

  image: function() {
    return this.store.getById("image", this.get("imageId"));
  }.property("imageId"),

  displayImageUrl: function() {
    return this.get("image") ? this.get("image.thumbImageUrl") : this.get("item.displayImageUrl");
  }.property("image", "item.displayImageUrl")
});
<|endoftext|>


<commit_before>define(['goo/entities/World', 'goo/entities/systems/TransformSystem', 'goo/entities/systems/RenderSystem', 'goo/entities/systems/PartitioningSystem',
		'goo/renderer/Renderer', 'goo/entities/systems/BoundingUpdateSystem', 'goo/entities/systems/ScriptSystem',
		'goo/entities/systems/LightingSystem', 'goo/renderer/SimplePartitioner', 'goo/entities/managers/LightManager',
		'goo/entities/systems/CameraSystem', 'goo/renderer/Camera', 'goo/entities/components/CameraComponent', 'goo/util/Stats',
		"goo/entities/systems/CSSTransformSystem", 'goo/util/GameUtils'],
/** @lends GooRunner */
function (World, TransformSystem, RenderSystem, PartitioningSystem, Renderer, BoundingUpdateSystem, ScriptSystem, LightingSystem, SimplePartitioner,
	LightManager, CameraSystem, Camera, CameraComponent, Stats, CSSTransformSystem, GameUtils) {
	"use strict";

	/**
	 * Standard setup of entity system to use as base for small projects/demos It accepts a JSON object containing the settings for the Renderer
	 * class.

	 * default = {
	 *     alpha : false,
	 *     premultipliedAlpha : true,
	 *     antialias : false,
	 *     stencil : false,
	 *     preserveDrawingBuffer : false,
	 *     showStats : false,
	 *      manuallyStartGameLoop : false
	 * }
	 *
	 * @constructor
	 * @param {Object} parameters GooRunner settings passed in a JSON object.
	 */
	function GooRunner (parameters) {
		parameters = parameters || {};

		this.world = new World();
		this.renderer = new Renderer(parameters);

		// this.world.setManager(new TagManager());
		this.world.setManager(new LightManager());

		// this.world.setSystem(new LoadingSystem());
		this.world.setSystem(new ScriptSystem());
		this.world.setSystem(new TransformSystem());
		this.world.setSystem(new CSSTransformSystem(this.renderer));
		this.world.setSystem(new CameraSystem());
		this.world.setSystem(new BoundingUpdateSystem());
		this.world.setSystem(new LightingSystem());

		var partitioningSystem = new PartitioningSystem();
		partitioningSystem.partitioner = new SimplePartitioner();
		this.world.setSystem(partitioningSystem);

		var renderSystem = new RenderSystem(partitioningSystem.renderList);
		this.world.setSystem(renderSystem);

		GameUtils.initAllShims();

		if (parameters.showStats) {
			this.stats = new Stats();
			this.stats.domElement.style.position = 'absolute';
			this.stats.domElement.style.left = '10px';
			this.stats.domElement.style.top = '10px';
			// document.getElementById( 'container' ).appendChild(stats.domElement);
			document.body.appendChild(this.stats.domElement);
		}

		this.callbacks = [];
		this.callbacksPreProcess = [];
		this.callbacksPreRender = [];

		var that = this;
		this.start = -1;
		this.run = function (time) {
			try {
				if (that.start < 0) {
					that.start = time;
				}
				that.world.tpf = (time - that.start) / 1000.0;
				that.world.time += that.world.tpf;
				World.time = that.world.time;
				that.start = time;
				if (that.world.tpf < 0) {// skip a loop - original start time probably bad.
					that.world.time = 0;
					that.world.tpf = 0;
					World.time = 0;
					that.animationId = window.requestAnimationFrame(that.run);
					return;
				}

				for ( var i in that.callbacksPreProcess) {
					that.callbacksPreProcess[i](that.world.tpf);
				}

				that.world.process();

				for ( var i in that.callbacksPreRender) {
					that.callbacksPreRender[i](that.world.tpf);
				}

				that.renderer.info.reset();

				renderSystem.render(that.renderer);

				for ( var i in that.callbacks) {
					that.callbacks[i](that.world.tpf);
				}

				if (that.stats) {
					that.stats.update(that.renderer.info);
				}

				that.animationId = window.requestAnimationFrame(that.run);
			} catch (e) {
				if (e instanceof Error) {
					console.error(e.stack);
				} else {
					console.error(e);
				}
			}
		};

		this.animationId = -1;
		if (!parameters.manuallyStartGameLoop) {
			this.startGameLoop(this.run);
		}

		//TODO: Temporary shift+space for fullscreen and shift+enter for mouselock
		var isCtrl = false;
		document.onkeyup = function (e) {
			if (e.which === 17) {
				isCtrl = false;
			}
		};
		document.onkeydown = function (e) {
			if (e.which === 17) {
				isCtrl = true;
			} else if (e.which === 32 && isCtrl) {
				GameUtils.toggleFullScreen();
			} else if (e.which === 13 && isCtrl) {
				GameUtils.togglePointerLock();
			}
		};
	}

	GooRunner.prototype.startGameLoop = function () {
		this.start = -1;
		this.animationId = window.requestAnimationFrame(this.run);
	};

	GooRunner.prototype.stopGameLoop = function () {
		window.cancelAnimationFrame(this.animationId);
	};

	return GooRunner;
});<commit_msg>Fixed tpf bug when tab unfocused for a long time<commit_after>define(['goo/entities/World', 'goo/entities/systems/TransformSystem', 'goo/entities/systems/RenderSystem', 'goo/entities/systems/PartitioningSystem',
		'goo/renderer/Renderer', 'goo/entities/systems/BoundingUpdateSystem', 'goo/entities/systems/ScriptSystem',
		'goo/entities/systems/LightingSystem', 'goo/renderer/SimplePartitioner', 'goo/entities/managers/LightManager',
		'goo/entities/systems/CameraSystem', 'goo/renderer/Camera', 'goo/entities/components/CameraComponent', 'goo/util/Stats',
		"goo/entities/systems/CSSTransformSystem", 'goo/util/GameUtils'],
/** @lends GooRunner */
function (World, TransformSystem, RenderSystem, PartitioningSystem, Renderer, BoundingUpdateSystem, ScriptSystem, LightingSystem, SimplePartitioner,
	LightManager, CameraSystem, Camera, CameraComponent, Stats, CSSTransformSystem, GameUtils) {
	"use strict";

	/**
	 * Standard setup of entity system to use as base for small projects/demos It accepts a JSON object containing the settings for the Renderer
	 * class.

	 * default = {
	 *     alpha : false,
	 *     premultipliedAlpha : true,
	 *     antialias : false,
	 *     stencil : false,
	 *     preserveDrawingBuffer : false,
	 *     showStats : false,
	 *      manuallyStartGameLoop : false
	 * }
	 *
	 * @constructor
	 * @param {Object} parameters GooRunner settings passed in a JSON object.
	 */
	function GooRunner (parameters) {
		parameters = parameters || {};

		this.world = new World();
		this.renderer = new Renderer(parameters);

		// this.world.setManager(new TagManager());
		this.world.setManager(new LightManager());

		// this.world.setSystem(new LoadingSystem());
		this.world.setSystem(new ScriptSystem());
		this.world.setSystem(new TransformSystem());
		this.world.setSystem(new CSSTransformSystem(this.renderer));
		this.world.setSystem(new CameraSystem());
		this.world.setSystem(new BoundingUpdateSystem());
		this.world.setSystem(new LightingSystem());

		var partitioningSystem = new PartitioningSystem();
		partitioningSystem.partitioner = new SimplePartitioner();
		this.world.setSystem(partitioningSystem);

		var renderSystem = new RenderSystem(partitioningSystem.renderList);
		this.world.setSystem(renderSystem);

		GameUtils.initAllShims();

		if (parameters.showStats) {
			this.stats = new Stats();
			this.stats.domElement.style.position = 'absolute';
			this.stats.domElement.style.left = '10px';
			this.stats.domElement.style.top = '10px';
			// document.getElementById( 'container' ).appendChild(stats.domElement);
			document.body.appendChild(this.stats.domElement);
		}

		this.callbacks = [];
		this.callbacksPreProcess = [];
		this.callbacksPreRender = [];

		var that = this;
		this.start = -1;
		this.run = function (time) {
			try {
				if (that.start < 0) {
					that.start = time;
				}
				that.world.tpf = (time - that.start) / 1000.0;
				that.world.time += that.world.tpf;
				World.time = that.world.time;
				that.start = time;
				if (that.world.tpf < 0) {// skip a loop - original start time probably bad.
					that.world.time = 0;
					that.world.tpf = 0;
					World.time = 0;
					that.animationId = window.requestAnimationFrame(that.run);
					return;
				} else if (that.world.tpf > 0.5) {
					that.animationId = window.requestAnimationFrame(that.run);
					return;
				}

				for ( var i in that.callbacksPreProcess) {
					that.callbacksPreProcess[i](that.world.tpf);
				}

				that.world.process();

				for ( var i in that.callbacksPreRender) {
					that.callbacksPreRender[i](that.world.tpf);
				}

				that.renderer.info.reset();

				renderSystem.render(that.renderer);

				for ( var i in that.callbacks) {
					that.callbacks[i](that.world.tpf);
				}

				if (that.stats) {
					that.stats.update(that.renderer.info);
				}

				that.animationId = window.requestAnimationFrame(that.run);
			} catch (e) {
				if (e instanceof Error) {
					console.error(e.stack);
				} else {
					console.error(e);
				}
			}
		};

		this.animationId = -1;
		if (!parameters.manuallyStartGameLoop) {
			this.startGameLoop(this.run);
		}

		//TODO: Temporary shift+space for fullscreen and shift+enter for mouselock
		var isCtrl = false;
		document.onkeyup = function (e) {
			if (e.which === 17) {
				isCtrl = false;
			}
		};
		document.onkeydown = function (e) {
			if (e.which === 17) {
				isCtrl = true;
			} else if (e.which === 32 && isCtrl) {
				GameUtils.toggleFullScreen();
			} else if (e.which === 13 && isCtrl) {
				GameUtils.togglePointerLock();
			}
		};
	}

	GooRunner.prototype.startGameLoop = function () {
		this.start = -1;
		this.animationId = window.requestAnimationFrame(this.run);
	};

	GooRunner.prototype.stopGameLoop = function () {
		window.cancelAnimationFrame(this.animationId);
	};

	return GooRunner;
});<|endoftext|>


<commit_before>const BaseModule = require('./baseModule');

class Ozobot extends BaseModule {

	// 클래스 내부에서 사용될 필드들을 이곳에서 선언합니다.
	constructor() {
		super();

		this.sp = null;     //serial port
		this.dataFormat = {
			fheader: 0xFF,
			sheader: 0x55,
			data_size: 0,
			index: 0,
			data: [],
			tail: 0x0A
		};
		this.entryData = {
			seq: 0,
			cat: 0,
			act: 0,
			pcnt: 0,
			p1: 0,
			p2: 0,
			p3: 0,
			p4: 0,
			p5: 0,
			p6: 0
		};
		this.commands = {
			CMD_SEQ: 'seq',
			CMD_CATEGORY: 'cat',
			CMD_ACTION: 'act',
			CMD_PARAM_CNT: 'pcnt',
			CMD_PARAM_1: 'p1',
			CMD_PARAM_2: 'p2',
			CMD_PARAM_3: 'p3',
			CMD_PARAM_4: 'p4',
			CMD_PARAM_5: 'p5',
			CMD_PARAM_6: 'p6'
		};
		this.sensorData = {
			movement_finish: 0,
			surface_color: 0,
			line_color: 0,
			obstacle_front_left: 0,
			obstacle_front_right: 0,
			obstacle_rear_left: 0,
			obstacle_rear_right: 0
		}

		this.sendBuffer = [];
		this.recvBuffer = [];
		this.sendSem = false;
		this.recvFlg = 0;
		this.recvIsFirst = false;
		this.buffer = [];
		this.currentSeq = 0;
	}

	init(handler, config) {
		this.handler = handler;
		this.config = config;
	}

	setSerialPort(sp) {
		this.sp = sp;
	}

	disconnect(connect) {
		connect.close();
		if (this.sp)
			delete this.sp;
	}

	requestInitialData() {
		return true;
	}

	// 연결 후 초기에 수신받아서 정상연결인지를 확인해야하는 경우 사용합니다.
	checkInitialData(data, config) {
		return true;
	}

	// 주기적으로 하드웨어에서 받은 데이터의 검증이 필요한 경우 사용합니다.
	validateLocalData(data) {
		return true;
	}

	requestLocalData() {
		// 하드웨어로 보낼 데이터 로직
		if (!this.sendSem && this.sendBuffer.length > 0) {
			this.sendSem = true;
			this.sp.write(this.sendBuffer.shift(), () => {
				if (this.sp) {
					this.sp.drain(() => {
						this.sendSem = false;
						this.sendBuffer = [];
					});
				}
			});
		}
	}

	// 하드웨어에서 온 데이터 처리
	handleLocalData(data) {
		// 데이터 처리 로직
		if (data.length > 0) {
			var dataFormat = this.dataFormat;
			var bytes = [];
			var c = 0;
			for (bytes = [], c = 0; c < data.length; c += 2) {
				bytes.push(parseInt(data.substr(c, 2), 16));
			}
			for (var i = 0; i < bytes.length; i++) {
				if ((!this.recvIsFirst) && (bytes[i] != dataFormat.fheader)) {
					continue;
				}
				else {
					this.recvIsFirst = true;
				}
				this.recvBuffer.push(bytes[i]);
			}
			if (this.recvBuffer.shift() == dataFormat.fheader && this.recvFlg == 0) {
				this.recvFlg = 1;
			}
			else {
				this.recvFlg = 0;
				return;
			}
			if (this.recvBuffer.shift() == dataFormat.sheader && this.recvFlg == 1) {
				this.recvFlg = 2;
			}
			else {
				this.recvFlg = 0;
				return;
			}
			if (this.recvBuffer[0] + 2 == this.recvBuffer.length) {
				this.recvFlg = 3;
				dataFormat.data_size = this.recvBuffer.shift();
			}
			else {
				this.recvFlg = 0;
				return;
			}
			dataFormat.data = [];
			for (var i = 0; i < dataFormat.data_size; i++) {
				// 센서 데이터 처리
				dataFormat.data.push(this.recvBuffer.shift());
			}
			if (this.recvBuffer.shift() == dataFormat.tail && this.recvFlg == 3) {
				this.recvFlg = 0;
			}
			else {
				this.recvFlg = 0;
				dataFormat.data = [];
				return;
			}
			// console.log("DEBUG:::RECV=>" + dataFormat.data);
			if (dataFormat.data[0] == 0x00) {
				this.sensorData.movement_finish = dataFormat.data[1];
				this.sensorData.surface_color = dataFormat.data[2];
				this.sensorData.line_color = dataFormat.data[3];
				this.sensorData.obstacle_front_left = dataFormat.data[4];
				this.sensorData.obstacle_front_right = dataFormat.data[5];
				this.sensorData.obstacle_rear_left = dataFormat.data[6];
				this.sensorData.obstacle_rear_right = dataFormat.data[7];
			}
		}
	}

	// 엔트리로 전달할 데이터
	requestRemoteData(handler) {
		// handler.write(key, value) ...
		Object.keys(this.sensorData).forEach((key) => {
			if (this.sensorData[key] !== undefined) {
				handler.write(key, this.sensorData[key]);
			}
		});
	}

	// 엔트리에서 받은 데이터에 대한 처리
	handleRemoteData(handler) {
		// const value = handler.read(key) ...
		var entryData = this.entryData;
		var buffer = [];
		var temp = 0;
		entryData.seq = handler.read(this.commands.CMD_SEQ);
		if (entryData.seq == 0) {
			if(this.currentSeq != 0) {
				this.sendBuffer.push([ 0xFF, 0x55, 0x0A, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A ]);
			}
			this.currentSeq = 0;
		}
		else {
			if (this.currentSeq == entryData.seq) {
				return;
			}
			this.currentSeq = entryData.seq;
			if (handler.e(this.commands.CMD_CATEGORY))		entryData.cat = handler.read(this.commands.CMD_CATEGORY);
			if (handler.e(this.commands.CMD_ACTION))		entryData.act = handler.read(this.commands.CMD_ACTION);
			if (handler.e(this.commands.CMD_PARAM_CNT))		entryData.pcnt = handler.read(this.commands.CMD_PARAM_CNT);
			if (handler.e(this.commands.CMD_PARAM_1))		entryData.p1 = handler.read(this.commands.CMD_PARAM_1);
			if (handler.e(this.commands.CMD_PARAM_2))		entryData.p2 = handler.read(this.commands.CMD_PARAM_2);
			if (handler.e(this.commands.CMD_PARAM_3))		entryData.p3 = handler.read(this.commands.CMD_PARAM_3);
			if (handler.e(this.commands.CMD_PARAM_4))		entryData.p4 = handler.read(this.commands.CMD_PARAM_4);
			if (handler.e(this.commands.CMD_PARAM_5))		entryData.p5 = handler.read(this.commands.CMD_PARAM_5);
			if (handler.e(this.commands.CMD_PARAM_6))		entryData.p6 = handler.read(this.commands.CMD_PARAM_6);
			switch (entryData.cat) {
				case 0x01:
					buffer.push(entryData.cat);
					switch (entryData.act) {
						case 0x00:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(((entryData.p2) & 0xFF00) >> 8);
							buffer.push((entryData.p2) & 0xFF);
							buffer.push(entryData.p3);
							buffer.push(((entryData.p4) & 0xFF00) >> 8);
							buffer.push((entryData.p4) & 0xFF);
							buffer.push(0xFF);
							buffer.push(0xFF);
							break;
						case 0x01:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(((entryData.p2) & 0xFF00) >> 8);
							buffer.push((entryData.p2) & 0xFF);
							buffer.push(((entryData.p3) & 0xFF00) >> 8);
							buffer.push((entryData.p3) & 0xFF);
							buffer.push((0x5A & 0xFF00) >> 8);
							buffer.push(0x5A & 0xFF);
							break;
						case 0x02:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(((entryData.p2) & 0xFF00) >> 8);
							buffer.push((entryData.p2) & 0xFF);
							break;
						default:
						// error
					}
					break;
				case 0x02:
					buffer.push(entryData.cat);
					switch (entryData.act) {
						case 0x00:
							buffer.push(entryData.act);
							if(entryData.p1 == 0) {
								buffer.push(entryData.p1);
								buffer.push((entryData.p2 & 0xFF0000) >> 16);
								buffer.push((entryData.p2 & 0xFF00) >> 8);
								buffer.push((entryData.p2 & 0xFF));
								buffer.push((entryData.p3 & 0xFF0000) >> 16);
								buffer.push((entryData.p3 & 0xFF00) >> 8);
								buffer.push((entryData.p3 & 0xFF));
								buffer.push((entryData.p4 & 0xFF0000) >> 16);
								buffer.push((entryData.p4 & 0xFF00) >> 8);
								buffer.push((entryData.p4 & 0xFF));
								buffer.push((entryData.p5 & 0xFF0000) >> 16);
								buffer.push((entryData.p5 & 0xFF00) >> 8);
								buffer.push((entryData.p5 & 0xFF));
								buffer.push((entryData.p6 & 0xFF0000) >> 16);
								buffer.push((entryData.p6 & 0xFF00) >> 8);
								buffer.push((entryData.p6 & 0xFF));
							}
							else {
								buffer.push(entryData.p1);
								buffer.push((entryData.p2 & 0xFF0000) >> 16);
								buffer.push((entryData.p2 & 0xFF00) >> 8);
								buffer.push((entryData.p2 & 0xFF));
							}
							console.log(buffer);
							break;
						case 0x01:
							buffer.push(entryData.act);
							break;
						case 0x02:
							buffer.push(entryData.act);
							break;
						case 0x03:
							buffer.push(entryData.act);
							break;
						default:
						// error
					}
					break;
				default:
					// error
					return;
			}
			buffer.unshift(this.dataFormat.fheader, this.dataFormat.sheader, buffer.length);
			buffer.push(this.dataFormat.tail);
			this.sendBuffer.push(buffer);
		}
	}
}

module.exports = new Ozobot();<commit_msg>[ADD] Ozobot sound play.<commit_after>const BaseModule = require('./baseModule');

class Ozobot extends BaseModule {

	// 클래스 내부에서 사용될 필드들을 이곳에서 선언합니다.
	constructor() {
		super();

		this.sp = null;     //serial port
		this.dataFormat = {
			fheader: 0xFF,
			sheader: 0x55,
			data_size: 0,
			index: 0,
			data: [],
			tail: 0x0A
		};
		this.entryData = {
			seq: 0,
			cat: 0,
			act: 0,
			pcnt: 0,
			p1: 0,
			p2: 0,
			p3: 0,
			p4: 0,
			p5: 0,
			p6: 0
		};
		this.commands = {
			CMD_SEQ: 'seq',
			CMD_CATEGORY: 'cat',
			CMD_ACTION: 'act',
			CMD_PARAM_CNT: 'pcnt',
			CMD_PARAM_1: 'p1',
			CMD_PARAM_2: 'p2',
			CMD_PARAM_3: 'p3',
			CMD_PARAM_4: 'p4',
			CMD_PARAM_5: 'p5',
			CMD_PARAM_6: 'p6'
		};
		this.sensorData = {
			movement_finish: 0,
			surface_color: 0,
			line_color: 0,
			obstacle_front_left: 0,
			obstacle_front_right: 0,
			obstacle_rear_left: 0,
			obstacle_rear_right: 0
		}

		this.sendBuffer = [];
		this.recvBuffer = [];
		this.sendSem = false;
		this.recvFlg = 0;
		this.recvIsFirst = false;
		this.buffer = [];
		this.currentSeq = 0;
	}

	init(handler, config) {
		this.handler = handler;
		this.config = config;
	}

	setSerialPort(sp) {
		this.sp = sp;
	}

	disconnect(connect) {
		connect.close();
		if (this.sp)
			delete this.sp;
	}

	requestInitialData() {
		return true;
	}

	// 연결 후 초기에 수신받아서 정상연결인지를 확인해야하는 경우 사용합니다.
	checkInitialData(data, config) {
		return true;
	}

	// 주기적으로 하드웨어에서 받은 데이터의 검증이 필요한 경우 사용합니다.
	validateLocalData(data) {
		return true;
	}

	requestLocalData() {
		// 하드웨어로 보낼 데이터 로직
		if (!this.sendSem && this.sendBuffer.length > 0) {
			this.sendSem = true;
			this.sp.write(this.sendBuffer.shift(), () => {
				if (this.sp) {
					this.sp.drain(() => {
						this.sendSem = false;
						this.sendBuffer = [];
					});
				}
			});
		}
	}

	// 하드웨어에서 온 데이터 처리
	handleLocalData(data) {
		// 데이터 처리 로직
		if (data.length > 0) {
			var dataFormat = this.dataFormat;
			var bytes = [];
			var c = 0;
			for (bytes = [], c = 0; c < data.length; c += 2) {
				bytes.push(parseInt(data.substr(c, 2), 16));
			}
			for (var i = 0; i < bytes.length; i++) {
				if ((!this.recvIsFirst) && (bytes[i] != dataFormat.fheader)) {
					continue;
				}
				else {
					this.recvIsFirst = true;
				}
				this.recvBuffer.push(bytes[i]);
			}
			if (this.recvBuffer.shift() == dataFormat.fheader && this.recvFlg == 0) {
				this.recvFlg = 1;
			}
			else {
				this.recvFlg = 0;
				return;
			}
			if (this.recvBuffer.shift() == dataFormat.sheader && this.recvFlg == 1) {
				this.recvFlg = 2;
			}
			else {
				this.recvFlg = 0;
				return;
			}
			if (this.recvBuffer[0] + 2 == this.recvBuffer.length) {
				this.recvFlg = 3;
				dataFormat.data_size = this.recvBuffer.shift();
			}
			else {
				this.recvFlg = 0;
				return;
			}
			dataFormat.data = [];
			for (var i = 0; i < dataFormat.data_size; i++) {
				// 센서 데이터 처리
				dataFormat.data.push(this.recvBuffer.shift());
			}
			if (this.recvBuffer.shift() == dataFormat.tail && this.recvFlg == 3) {
				this.recvFlg = 0;
			}
			else {
				this.recvFlg = 0;
				dataFormat.data = [];
				return;
			}
			// console.log("DEBUG:::RECV=>" + dataFormat.data);
			if (dataFormat.data[0] == 0x00) {
				this.sensorData.movement_finish = dataFormat.data[1];
				this.sensorData.surface_color = dataFormat.data[2];
				this.sensorData.line_color = dataFormat.data[3];
				this.sensorData.obstacle_front_left = dataFormat.data[4];
				this.sensorData.obstacle_front_right = dataFormat.data[5];
				this.sensorData.obstacle_rear_left = dataFormat.data[6];
				this.sensorData.obstacle_rear_right = dataFormat.data[7];
			}
		}
	}

	// 엔트리로 전달할 데이터
	requestRemoteData(handler) {
		// handler.write(key, value) ...
		Object.keys(this.sensorData).forEach((key) => {
			if (this.sensorData[key] !== undefined) {
				handler.write(key, this.sensorData[key]);
			}
		});
	}

	// 엔트리에서 받은 데이터에 대한 처리
	handleRemoteData(handler) {
		// const value = handler.read(key) ...
		var entryData = this.entryData;
		var buffer = [];
		var temp = 0;
		entryData.seq = handler.read(this.commands.CMD_SEQ);
		if (entryData.seq == 0) {
			if(this.currentSeq != 0) {
				this.sendBuffer.push([ 0xFF, 0x55, 0x0A, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A ]);
			}
			this.currentSeq = 0;
		}
		else {
			if (this.currentSeq == entryData.seq) {
				return;
			}
			this.currentSeq = entryData.seq;
			if (handler.e(this.commands.CMD_CATEGORY))		entryData.cat = handler.read(this.commands.CMD_CATEGORY);
			if (handler.e(this.commands.CMD_ACTION))		entryData.act = handler.read(this.commands.CMD_ACTION);
			if (handler.e(this.commands.CMD_PARAM_CNT))		entryData.pcnt = handler.read(this.commands.CMD_PARAM_CNT);
			if (handler.e(this.commands.CMD_PARAM_1))		entryData.p1 = handler.read(this.commands.CMD_PARAM_1);
			if (handler.e(this.commands.CMD_PARAM_2))		entryData.p2 = handler.read(this.commands.CMD_PARAM_2);
			if (handler.e(this.commands.CMD_PARAM_3))		entryData.p3 = handler.read(this.commands.CMD_PARAM_3);
			if (handler.e(this.commands.CMD_PARAM_4))		entryData.p4 = handler.read(this.commands.CMD_PARAM_4);
			if (handler.e(this.commands.CMD_PARAM_5))		entryData.p5 = handler.read(this.commands.CMD_PARAM_5);
			if (handler.e(this.commands.CMD_PARAM_6))		entryData.p6 = handler.read(this.commands.CMD_PARAM_6);
			switch (entryData.cat) {
				case 0x01:
					buffer.push(entryData.cat);
					switch (entryData.act) {
						case 0x00:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(((entryData.p2) & 0xFF00) >> 8);
							buffer.push((entryData.p2) & 0xFF);
							buffer.push(entryData.p3);
							buffer.push(((entryData.p4) & 0xFF00) >> 8);
							buffer.push((entryData.p4) & 0xFF);
							buffer.push(0xFF);
							buffer.push(0xFF);
							break;
						case 0x01:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(((entryData.p2) & 0xFF00) >> 8);
							buffer.push((entryData.p2) & 0xFF);
							buffer.push(((entryData.p3) & 0xFF00) >> 8);
							buffer.push((entryData.p3) & 0xFF);
							buffer.push((0x5A & 0xFF00) >> 8);
							buffer.push(0x5A & 0xFF);
							break;
						case 0x02:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(((entryData.p2) & 0xFF00) >> 8);
							buffer.push((entryData.p2) & 0xFF);
							break;
						default:
						// error
					}
					break;
				case 0x02:
					buffer.push(entryData.cat);
					switch (entryData.act) {
						case 0x00:
							buffer.push(entryData.act);
							if(entryData.p1 == 0) {
								buffer.push(entryData.p1);
								buffer.push((entryData.p2 & 0xFF0000) >> 16);
								buffer.push((entryData.p2 & 0xFF00) >> 8);
								buffer.push((entryData.p2 & 0xFF));
								buffer.push((entryData.p3 & 0xFF0000) >> 16);
								buffer.push((entryData.p3 & 0xFF00) >> 8);
								buffer.push((entryData.p3 & 0xFF));
								buffer.push((entryData.p4 & 0xFF0000) >> 16);
								buffer.push((entryData.p4 & 0xFF00) >> 8);
								buffer.push((entryData.p4 & 0xFF));
								buffer.push((entryData.p5 & 0xFF0000) >> 16);
								buffer.push((entryData.p5 & 0xFF00) >> 8);
								buffer.push((entryData.p5 & 0xFF));
								buffer.push((entryData.p6 & 0xFF0000) >> 16);
								buffer.push((entryData.p6 & 0xFF00) >> 8);
								buffer.push((entryData.p6 & 0xFF));
							}
							else {
								buffer.push(entryData.p1);
								buffer.push((entryData.p2 & 0xFF0000) >> 16);
								buffer.push((entryData.p2 & 0xFF00) >> 8);
								buffer.push((entryData.p2 & 0xFF));
							}
							break;
						case 0x01:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(entryData.p2);
							break;
						case 0x02:
							buffer.push(entryData.act);
							buffer.push(entryData.p1);
							buffer.push(entryData.p2);
							buffer.push((entryData.p3 & 0xFF00) >> 8);
							buffer.push((entryData.p3 & 0xFF));
							break;
						case 0x03:
							buffer.push(entryData.act);
							break;
						default:
						// error
					}
					break;
				default:
					// error
					return;
			}
			buffer.unshift(this.dataFormat.fheader, this.dataFormat.sheader, buffer.length);
			buffer.push(this.dataFormat.tail);
			this.sendBuffer.push(buffer);
		}
	}
}

module.exports = new Ozobot();<|endoftext|>


<commit_before>define(["underscore", "backbone", "moxie.conf"], function(_, Backbone, conf){
    var EVENT_POSITION_UPDATED = 'position:updated';
    function UserPosition() {
        _.extend(this, Backbone.Events);
        var supportsGeoLocation = Boolean(navigator.geolocation),
            spamReduction = false,
            latestPosition = null,
            positionInterval;
        this.getLocation = function(cb, options) {
            options = options || {};
            // If we don't get a location within the errorMargin before the Timeout
            // we return the most recent position reported by watchPosition
            options.errorMargin = options.errorMargin || conf.position.errorMargin;
            options.timeout = options.timeout || conf.position.accuracyTimeout;
            var temporaryGeoWatchID;
            var accuracyTimeout = setTimeout(function() {
                navigator.geolocation.clearWatch(temporaryGeoWatchID);
                if (latestPosition) {
                    cb(latestPosition);
                } else {
                    cb(conf.defaultLocation);
                }
            }, options.timeout);
            temporaryGeoWatchID = navigator.geolocation.watchPosition(function(position) {
                latestPosition = position;
                if (latestPosition.coords && latestPosition.coords.accuracy && latestPosition.coords.accuracy <= options.errorMargin) {
                    window.clearTimeout(accuracyTimeout);
                    navigator.geolocation.clearWatch(temporaryGeoWatchID);
                    cb(latestPosition);
                }
            }, _.bind(locationError, this),
            {
                    enableHighAccuracy: conf.position.enableHighAccuracy,
                    maximumAge: conf.position.maximumAge,
            });

        };
        function locationSuccess(position) {
            this.trigger(EVENT_POSITION_UPDATED, position);
        }
        function locationError(err) {
            if ('console' in window) {
                console.log("Geolocation error: ", err);
            }
        }
        function startWatching() {
            if (supportsGeoLocation) {
                this.getLocation(_.bind(locationSuccess, this));
                positionInterval = window.setInterval(this.getLocation, conf.position.updateInterval, _.bind(locationSuccess, this));
            } else {
                locationError.apply(this);
            }
        }
        var count = 0;
        this.follow = function(cb, context) {
            context = context || this;
            if (!positionInterval) {
                // Call the "private" function with the correct context
                startWatching.apply(this);
            }
            this.on(EVENT_POSITION_UPDATED, cb, context);
            this.count++;
            // Send user latest userPosition (not default)
            if (latestPosition) {
                cb.apply(context, [latestPosition]);
            }
        };
        this.unfollow = function(cb, context) {
            if (context) {
                this.off(EVENT_POSITION_UPDATED, null, context);
            } else {
                this.off(EVENT_POSITION_UPDATED, cb);
            }
            this.count--;
            if (this.count === 0) {
                window.clearInterval(positionInterval);
            }
        };
    }
    return new UserPosition();
});
<commit_msg>Removed unused spamReduction var<commit_after>define(["underscore", "backbone", "moxie.conf"], function(_, Backbone, conf){
    var EVENT_POSITION_UPDATED = 'position:updated';
    function UserPosition() {
        _.extend(this, Backbone.Events);
        var supportsGeoLocation = Boolean(navigator.geolocation),
            latestPosition = null,
            positionInterval;
        this.getLocation = function(cb, options) {
            options = options || {};
            // If we don't get a location within the errorMargin before the Timeout
            // we return the most recent position reported by watchPosition
            options.errorMargin = options.errorMargin || conf.position.errorMargin;
            options.timeout = options.timeout || conf.position.accuracyTimeout;
            var temporaryGeoWatchID;
            var accuracyTimeout = setTimeout(function() {
                navigator.geolocation.clearWatch(temporaryGeoWatchID);
                if (latestPosition) {
                    cb(latestPosition);
                } else {
                    cb(conf.defaultLocation);
                }
            }, options.timeout);
            temporaryGeoWatchID = navigator.geolocation.watchPosition(function(position) {
                latestPosition = position;
                if (latestPosition.coords && latestPosition.coords.accuracy && latestPosition.coords.accuracy <= options.errorMargin) {
                    window.clearTimeout(accuracyTimeout);
                    navigator.geolocation.clearWatch(temporaryGeoWatchID);
                    cb(latestPosition);
                }
            }, _.bind(locationError, this),
            {
                    enableHighAccuracy: conf.position.enableHighAccuracy,
                    maximumAge: conf.position.maximumAge,
            });

        };
        function locationSuccess(position) {
            this.trigger(EVENT_POSITION_UPDATED, position);
        }
        function locationError(err) {
            if ('console' in window) {
                console.log("Geolocation error: ", err);
            }
        }
        function startWatching() {
            if (supportsGeoLocation) {
                this.getLocation(_.bind(locationSuccess, this));
                positionInterval = window.setInterval(this.getLocation, conf.position.updateInterval, _.bind(locationSuccess, this));
            } else {
                locationError.apply(this);
            }
        }
        var count = 0;
        this.follow = function(cb, context) {
            context = context || this;
            if (!positionInterval) {
                // Call the "private" function with the correct context
                startWatching.apply(this);
            }
            this.on(EVENT_POSITION_UPDATED, cb, context);
            this.count++;
            // Send user latest userPosition (not default)
            if (latestPosition) {
                cb.apply(context, [latestPosition]);
            }
        };
        this.unfollow = function(cb, context) {
            if (context) {
                this.off(EVENT_POSITION_UPDATED, null, context);
            } else {
                this.off(EVENT_POSITION_UPDATED, cb);
            }
            this.count--;
            if (this.count === 0) {
                window.clearInterval(positionInterval);
            }
        };
    }
    return new UserPosition();
});
<|endoftext|>