<commit_before>const product = require('./model/product');
const category = require('./model/category');
const account = require('./model/account');
const order = require('./model/order');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/category/:parentId?', (req, res) => {
    let parentId = (req.params.parentId === undefined) ? 0 : req.params.parentId;
    let categories = category.getCategories(parentId);
    categories.then( (result) => {
        res.json({categories: result});
    });
});

app.get('/product/:categoryId', (req, res) => {
    let products = product.getProducts(req.params.categoryId);
    products.then( (result) => {
        res.json({products :  result});
    });
});

app.post('/login', (req, res) => {
    if(req.body.username !== undefined && req.body.password !== undefined) {
        let login = account.login(req.body.username, req.body.password);
        login.then( (result) => {
            res.json({result : result});
        });

    }else{
        res.json({err : 'selam'});
    }
});

app.post('/tempdesk', (req, res) => {
    if(req.body.deskid !== undefined){
        let tempDeskId = order.getTempDesk(req.body.deskid);
        tempDeskId.then((result) => {
            res.json({tempId : result});
        });
    }else{
        res.json({err : 'selam'});
    }
});

app.post('/order', (req, res) => {
    if(req.body.products !== undefined && req.body.tempId !== undefined ){
        if(req.body.products.length > 0){
            let result = order.order(req.body.tempId, req.body.products);
            result.then((reslt) => {
                res.json({result: reslt});
            });
        }else{
            res.json({err : 'hata'});
        }
    }else{
        res.json({err : 'hata'});
    }
});

app.get('/desklist', (req, res) => {
    let deskList = order.getDeskList();
    deskList.then( (result) => {
        res.json({desklist : result});
    })
});

app.get('/deskOrders/:tempId', (req, res) => {
    let deskOrders = order.getDeskOrders(req.params.tempId);
    deskOrders.then( (result) => {
        res.json({deskOrders : result});
    })
});

app.post('/editbasket', (req, res) => {
    order.editBasket(req.body.baskets).then( (result) => {
        res.json({result : result});
    })
});

app.post('/deletebasket', (req, res) => {
    order.deleteBasket(req.body.basketId).then( (result) => {
        res.json({result : result});
    })
});

app.post('/changestatus', (req, res) => {
    if(req.body.orderId !== undefined && req.body.status !== undefined){
        let change = order.changeStatus(req.body.orderId, req.body.status);
        change.then((result) => {
            res.json({result: result});
        });
    }else{
        res.json({err : 'selam'});
    }
});

app.get('/baskets/:orderId', (req, res) => {
    if(req.params.orderId !== undefined && !isNaN(req.params.orderId)) {
        let baskets = order.getBaskets(req.params.orderId);
        baskets.then( (result) => {
            res.json({baskets : result});
        });
    } else {
        res.json({err : 'selam'});
    }
});

app.get('/detail/:productId', (req, res) => {
   if(req.params.productId !== undefined) {
       let detail = product.detail(req.params.productId);
       detail.then( (result) => {
           res.json({detail : result});
       });
   } else {
       res.json({err : 'selam'});
   }
});

app.listen(9090, () => {
    console.log('http://localhost:9090 runnig');
});
<commit_msg>baskets edit<commit_after>const product = require('./model/product');
const category = require('./model/category');
const account = require('./model/account');
const order = require('./model/order');
const bodyParser = require('body-parser');
const express = require('express');
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/category/:parentId?', (req, res) => {
    let parentId = (req.params.parentId === undefined) ? 0 : req.params.parentId;
    let categories = category.getCategories(parentId);
    categories.then( (result) => {
        res.json({categories: result});
    });
});

app.get('/product/:categoryId', (req, res) => {
    let products = product.getProducts(req.params.categoryId);
    products.then( (result) => {
        res.json({products :  result});
    });
});

app.post('/login', (req, res) => {
    if(req.body.username !== undefined && req.body.password !== undefined) {
        let login = account.login(req.body.username, req.body.password);
        login.then( (result) => {
            res.json({result : result});
        });

    }else{
        res.json({err : 'selam'});
    }
});

app.post('/tempdesk', (req, res) => {
    if(req.body.deskid !== undefined){
        let tempDeskId = order.getTempDesk(req.body.deskid);
        tempDeskId.then((result) => {
            res.json({tempId : result});
        });
    }else{
        res.json({err : 'selam'});
    }
});

app.post('/order', (req, res) => {
    if(req.body.products !== undefined && req.body.tempId !== undefined ){
        if(req.body.products.length > 0){
            let result = order.order(req.body.tempId, req.body.products);
            result.then((reslt) => {
                res.json({result: reslt});
            });
        }else{
            res.json({err : 'hata'});
        }
    }else{
        res.json({err : 'hata'});
    }
});

app.get('/desklist', (req, res) => {
    let deskList = order.getDeskList();
    deskList.then( (result) => {
        res.json({desklist : result});
    })
});

app.get('/deskOrders/:tempId', (req, res) => {
    let deskOrders = order.getDeskOrders(req.params.tempId);
    deskOrders.then( (result) => {
        res.json({deskOrders : result});
    })
});

app.post('/editbasket', (req, res) => {
    if(req.body.baskets !== undefined){
        if (req.body.baskets.length > 0){
            order.editBasket(req.body.baskets).then( (result) => {
                res.json({result : result});
            });
        } else {
            res.json({result : 'baskets array length is zero'});
        }
    } else {
        res.json({result : 'undefined baskets parameters!'});
    }

});

app.post('/deletebasket', (req, res) => {
    order.deleteBasket(req.body.basketId).then( (result) => {
        res.json({result : result});
    })
});

app.post('/changestatus', (req, res) => {
    if(req.body.orderId !== undefined && req.body.status !== undefined){
        let change = order.changeStatus(req.body.orderId, req.body.status);
        change.then((result) => {
            res.json({result: result});
        });
    }else{
        res.json({err : 'selam'});
    }
});

app.get('/baskets/:orderId', (req, res) => {
    if(req.params.orderId !== undefined && !isNaN(req.params.orderId)) {
        let baskets = order.getBaskets(req.params.orderId);
        baskets.then( (result) => {
            res.json({baskets : result});
        });
    } else {
        res.json({err : 'selam'});
    }
});

app.get('/detail/:productId', (req, res) => {
   if(req.params.productId !== undefined) {
       let detail = product.detail(req.params.productId);
       detail.then( (result) => {
           res.json({detail : result});
       });
   } else {
       res.json({err : 'selam'});
   }
});

app.listen(9090, () => {
    console.log('http://localhost:9090 runnig');
});
<|endoftext|>


<commit_before>import fs from 'fs';

import expect from '../../expect';

import DmnModdle from '../../../lib';

describe('dmn-moddle - edit', function() {

  let moddle;

  beforeEach(function() {
    moddle = new DmnModdle();
  });

  async function read(fileName, root = 'dmn:Definitions') {
    return new Promise((resolve, reject) => {
      const file = fs.readFileSync(fileName, 'utf8');

      moddle.fromXML(file, root, (err, definitions) => {
        if (err) {
          reject(err);
        }

        resolve(definitions);
      });
    });
  }

  function write(element, options = { preamble: false }) {
    return new Promise((resolve, reject) => {
      moddle.toXML(element, options, (err, xml) => {
        if (err) {
          reject(err);
        }

        resolve(xml);
      });
    });
  }

  describe('DMN', function() {

    it('edit Decision name', async function() {

      // given
      const expected =
        '<definitions xmlns="https://www.omg.org/spec/DMN/20191111/MODEL/" id="Definitions_1" name="Foo" namespace="http://camunda.org/schema/1.0/dmn">' +
          '<decision id="Decision_1" name="Decision" />' +
        '</definitions>';

      const definitions = await read('test/fixtures/dmn/dmn/decision.dmn');

      // when
      definitions.name = 'Foo';

      const xml = await write(definitions, { preamble: false });

      // then
      expect(xml).to.equal(expected);
    });

  });

});
<commit_msg>test(model): verify dmn:ItemDefinition serialization<commit_after>import fs from 'fs';

import expect from '../../expect';

import DmnModdle from '../../../lib';

import { validateXML } from 'xsd-schema-validator';

const xsd = 'resources/dmn/xsd/DMN13.xsd';

describe('dmn-moddle - edit', function() {

  let moddle;

  beforeEach(function() {
    moddle = new DmnModdle();
  });

  async function read(fileName, root = 'dmn:Definitions') {
    return new Promise((resolve, reject) => {
      const file = fs.readFileSync(fileName, 'utf8');

      moddle.fromXML(file, root, (err, definitions) => {
        if (err) {
          reject(err);
        }

        resolve(definitions);
      });
    });
  }

  function write(element, options = { preamble: false }) {
    return new Promise((resolve, reject) => {
      moddle.toXML(element, options, (err, xml) => {
        if (err) {
          reject(err);
        }

        resolve(xml);
      });
    });
  }

  function validate(xml) {

    return new Promise((resolve, reject) => {
      validateXML(xml, xsd, (err, result) => {
        if (err) {
          return reject(err);
        }

        return resolve(result);
      });
    });

  }

  describe('DMN', function() {

    it('edit Decision name', async function() {

      // given
      const expected =
        '<definitions xmlns="https://www.omg.org/spec/DMN/20191111/MODEL/" id="Definitions_1" name="Foo" namespace="http://camunda.org/schema/1.0/dmn">' +
          '<decision id="Decision_1" name="Decision" />' +
        '</definitions>';

      const definitions = await read('test/fixtures/dmn/dmn/decision.dmn');

      // when
      definitions.name = 'Foo';

      const xml = await write(definitions, { preamble: false });

      // then
      expect(xml).to.equal(expected);
    });

    it('create ItemDefinition', async function() {

      const def_1 = moddle.create('dmn:ItemDefinition', {
        typeLanguage: 'FEEL',
        name: 'def_1',
        typeRef: 'xsd:string',
        allowedValues: moddle.create('dmn:UnaryTests', {
          text: 'a, b'
        })
      });

      const def_2_component = moddle.create('dmn:ItemDefinition', {
        typeLanguage: 'FEEL',
        name: 'def_2_component',
        typeRef: 'xsd:string',
        allowedValues: moddle.create('dmn:UnaryTests', {
          text: '[0..5]'
        })
      });

      const def_2 = moddle.create('dmn:ItemDefinition', {
        name: 'def_2',
        itemComponent: [
          def_2_component
        ],
        isCollection: true
      });

      const def_3 = moddle.create('dmn:ItemDefinition', {
        name: 'def_3',
        functionItem: moddle.create('dmn:FunctionItem', {
          parameters: [
            moddle.create('dmn:InformationItem', {
              typeRef: 'string',
              name: 'ProductType'
            }),
            moddle.create('dmn:InformationItem', {
              typeRef: 'number',
              name: 'Rate'
            })
          ],
          outputTypeRef: 'xsi:string'
        })
      });

      const definitions = moddle.create('dmn:Definitions', {
        name: 'foo',
        namespace: 'http://foo',
        itemDefinition: [
          def_1,
          def_2,
          def_3
        ]
      });

      // when
      const xml = await write(definitions);

      // then
      await validate(xml);
    });

  });

});
<|endoftext|>


<commit_before>//from http://ejohn.org/blog/simple-javascript-inheritance/
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

//considered for removal in HTML5
var TimeRanges = Class.extend({
    //readonly
    length: 0,
    start: function(index) {
      return this.starts[index];
    },
    end: function(index) {
      return this.ends[index];
    },
    //private
    starts: [],
    ends: [],
    add: function(start, end) {
      this.starts.push(start);
      this.ends.push(end);
      this.length++;
    }
});

var MediaError = Class.extend({
    //readonly
    code: -1,
    init: function(code) {
      this.code = code;
    },

    MEDIA_ERR_ABORTED: 1,
    MEDIA_ERR_NETWORK: 2,
    MEDIA_ERR_DECODE:3,
    MEDIA_ERR_SRC_NOT_SUPPORTED: 4
});

var HTMLMediaElement = Class.extend({
  //network state
  NETWORK_EMPTY: 0,
  NETWORK_IDLE: 1,
  NETWORK_LOADING: 2,
  NETWORK_LOADED: 3,
  NETWORK_NO_SOURCE: 4,

  //ready state
  HAVE_NOTHING: 0,
  HAVE_METADATA: 1,
  HAVE_CURRENT_DATA: 2,
  HAVE_FUTURE_DATA: 3,
  HAVE_ENOUGH_DATA: 4,

  // error state
  //readonly attribute MediaError error;
  error: 0,

  //attribute DOMString src;
  src: null,
  //readonly attribute currentSrc
  currentSrc: null,
  //readonly attribute unsigned short networkState
  networkState: this.NETWORK_EMPTY,
  //attribute boolean autobuffer
  autobuffer: false,
  //readonly attribute TimeRanges buffered
  buffered: null,
  //readonly attribute
  readyState: this.HAVE_NOTHING,
  seeking: false,

  //playback state (floats)
  currentTime: 0.0,
  //readonly
  startTime: 0.0,
  //readonly
  duration: 0.0,
  paused: false,
  defaultPlaybackRate: 1.0,
  playbackRate: 1.0,
  //TimeRanges - readonly
  played: new TimeRanges(),
  seekable: new TimeRanges(),
  ended: false,
  autoplay: false,
  loop: false,
  controls: false,
  volume: 1,
  muted: false,

  init: function(element) {
    this.domElement = element;
    this.src = this.domElement.getAttribute("src");
    this.autobuffer = (this.domElement.getAttribute("autobuffer")!=null);
    this.autoplay = (this.domElement.getAttribute("autoplay")!=null);
    this.loop = (this.domElement.getAttribute("loop")!=null);
    this.controls = (this.domElement.getAttribute("controls")!=null);
    this.load();
  },

  //returns void
  load: function() {
    this.currentSrc = this.src;
    //find the right source
    var candidate = this.domElement.firstChild;
    var maybe = null;
    //loop until we have found a type that works probably
    while(candidate!=null&&this.currentSrc==null) {
      if (candidate.nodeName=="SOURCE"||candidate.nodeName=="source") {
        if (candidate.getAttribute("src")!=null) {
          if (this.canPlayType(candidate.getAttribute("type"))=="probably") {
            this.currentSrc = candidate.getAttribute("src");
          } else if (maybe==null&&this.canPlayType(candidate.getAttribute("type"))=="maybe") {
            maybe = candidate.getAttribute("src");
          }
        }
      }
      candidate = candidate.nextSibling;
    }
    //fall back to the first type that works maybe
    if (this.currentSrc==null&&maybe!=null) {
      this.currentSrc = maybe;
    }
    //override this in concrete implementations to build the widget
  },

  //returns String
  canPlayType: function(type) {
    return "no";
  },

  play: function() {
    //TODO
    //purely abstract
  },

  pause: function() {
    //TODO
    //purely abstract
  },

  //returns void
  //className, id - String
  //start, end - float
  //pauseOnExit - boolean
  //enterCallback, exitCallback - function
  addCueRange: function(className, id, start, end, pauseOnExit, enterCallback, exitCallback) {
    if (!this.cueRanges[className]||this.cueRanges[className]==null) {
      this.cueRanges[className] = [];
    }

    var cueRange = {
      start: start,
      end: end,
      pauseOnExit: pauseOnExit,
      enterCallback: enterCallback,
      exitCallback: exitCallback,
    };
    this.cueRanges[className].push(cueRange);
  },

  removeCueRange: function(className) {
    //reset cue ranges
    cueRanges[className] = [];
  },

  //private
  cueRanges: {},
  lastPosition: 0.0,

  checkCueRanges: function(currentPosition) {
    try {
      var entering = new Array();
      var exititing = new Array();
      for (className in this.cueRanges) {
        if (this.cueRanges.hasOwnProperty(className)) {
          var cues = this.cueRanges[className];
          for (var i=0;i<cues.length;i++) {
            var cue = cues[i];
            if (currentPosition>this.lastPosition) {
              if (cue.start>this.lastPosition&&cue.start<currentPosition) {
                entering.push(cue);
              }
              if (cue.end>this.lastPosition&&cue.end<currentPosition) {
                exititing.push(cue);
              }
            } else if (currentPosition<this.lastPosition) {
              if (cue.end>this.lastPosition&&cue.end<currentPosition) {
                entering.push(cue);
              }
              if (cue.start>this.lastPosition&&cue.start<currentPosition) {
                exititing.push(cue);
              }
            }
          }
        }
      }

      //call the entering events
      for (var i=0;i<entering.length;i++) {
        if (entering[i].enterCallback) {
          entering[i].enterCallback.call(this, entering[i].id);
        }
      }
      //call the exiting events
      for (var i=0;i<exititing.length;i++) {
        if (exititing[i].exitCallback) {
          exititing[i].exitCallback.call(this, exititing[i].id);
        }
        if (exititing[i].pauseOnExit) {
          this.pause();
        }
      }
    } catch (e) {
      console.error(e);
    }
    this.lastPosition = currentPosition;
  }
});

var HTMLVideoElement = HTMLMediaElement.extend({
    width: "0px",
    height: "0px",
    videoWidth: 0,
    videoHeight: 0,
    //poster frame
    poster: null,

    init: function(element) {
      this._super(element);
      this.height = this.domElement.getAttribute("height");
      this.width = this.domElement.getAttribute("width");
      this.poster = this.domElement.getAttribute("poster");
    }
});

var HTMLAudioElement = HTMLMediaElement.extend({
    id: "id" + (new Date().getTime()),
    sound: null,

    //no additional properties
    init: function(element) {
      this._super(element);

      if (this.domElement.getAttribute("id")) {
        this.id = this.domElement.getAttribute("id");
      }

      var that = this;

      this.sound = soundManager.createSound({
          id: that.id,
          url: that.currentSrc,
          autoLoad: that.autobuffer,
          autoPlay: that.autoplay,
          whileloading: that.whileloading,
      });
      this.sound.wrapper = this;
    },

    onfinish: function(e) {
      if (this.wrapper.loop) {
        this.wrapper.play();
      } else {
        this.wrapper.ended = true;
      }
    },

    whileloading: function() {

      if (this.readyState==3) {
        this.wrapper.networkState = this.wrapper.NETWORK_LOADED;
      } else if (this.readyState==2) {
        //error
        this.wrapper.networkState = this.wrapper.NETWORK_NO_SOURCE;
      } else if (this.readyState==1) {
        //loading
        this.wrapper.networkState = this.wrapper.LOADING;
      } else if (this.readyState==0) {
        //uninitialized
        this.wrapper.networkState = this.wrapper.EMPTY;
      }
      console.log(this.wrapper.networkState);
    },

    whileplaying: function() {
      this.wrapper.currentTime = this.position / 1000;
      this.wrapper.checkCueRanges(this.position / 1000);
    },

    play: function() {
      if (this.muted) {
        this.sound.setVolume(0);
      } else {
        this.sound.setVolume(Math.floor(100*Math.max(0, Math.min(1,this.volume))));
      }

      if (this.sound.playState==1) {
        this.sound.position = Math.floor(this.currentTime * 1000);
        this.sound.resume();
      } else {
        var that = this;
        this.sound.wrapper = this;
        this.sound.play({
            onfinish: that.onfinish,
            whileplaying: that.whileplaying,
            position: Math.floor(that.startTime * 1000),
            whileloading: that.whileloading,
        });
      }
    },

    pause: function() {
      this.sound.pause();
    },

    canPlayType: function(type) {
      if (type.match(/^audio\/mp3/)) {
        return "probably";
      }
      if (type.match(/^audio\/wav/)) {
        return "probably";
      }
      if (type.match(/^audio\/(x-)?aiff/)) {
        return "probably";
      }
      if (type.match(/^audio\//)) {
        return "maybe";
      }
      return "no";
    }
});

function getHTML5Tags() {
  var audios = document.getElementsByTagName("audio");
  var videos = document.getElementsByTagName("video");
  var html5tags = [];
  for (var i=0;i<audios.length;i++) {
    if (audios[i].play) {
      html5tags.push(audios[i]);
    }
    html5tags.push(new HTMLAudioElement(audios[i]));
  }

  for (var i=0;i<videos.length;i++) {
    if (videos[i].play) {
      html5tags.push(videos[i]);
    }
    html5tags.push(new HTMLVideoElement(videos[i]));
  }
  return html5tags;
}
<commit_msg>support for error codes, duration<commit_after>//from http://ejohn.org/blog/simple-javascript-inheritance/
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

//considered for removal in HTML5
var TimeRanges = Class.extend({
    //readonly
    length: 0,
    start: function(index) {
      return this.starts[index];
    },
    end: function(index) {
      return this.ends[index];
    },
    //private
    starts: [],
    ends: [],
    add: function(start, end) {
      this.starts.push(start);
      this.ends.push(end);
      this.length++;
    }
});

var MediaError = Class.extend({
    //readonly
    code: -1,
    init: function(code) {
      this.code = code;
    },

    MEDIA_ERR_ABORTED: 1,
    MEDIA_ERR_NETWORK: 2,
    MEDIA_ERR_DECODE:3,
    MEDIA_ERR_SRC_NOT_SUPPORTED: 4
});

var HTMLMediaElement = Class.extend({
  //network state
  NETWORK_EMPTY: 0,
  NETWORK_IDLE: 1,
  NETWORK_LOADING: 2,
  NETWORK_LOADED: 3,
  NETWORK_NO_SOURCE: 4,

  //ready state
  HAVE_NOTHING: 0,
  HAVE_METADATA: 1,
  HAVE_CURRENT_DATA: 2,
  HAVE_FUTURE_DATA: 3,
  HAVE_ENOUGH_DATA: 4,

  // error state
  //readonly attribute MediaError error;
  error: 0,

  //attribute DOMString src;
  src: null,
  //readonly attribute currentSrc
  currentSrc: null,
  //readonly attribute unsigned short networkState
  networkState: this.NETWORK_EMPTY,
  //attribute boolean autobuffer
  autobuffer: false,
  //readonly attribute TimeRanges buffered
  buffered: null,
  //readonly attribute
  readyState: this.HAVE_NOTHING,
  seeking: false,

  //playback state (floats)
  currentTime: 0.0,
  //readonly
  startTime: 0.0,
  //readonly
  duration: 0.0,
  paused: false,
  defaultPlaybackRate: 1.0,
  playbackRate: 1.0,
  //TimeRanges - readonly
  played: new TimeRanges(),
  seekable: new TimeRanges(),
  ended: false,
  autoplay: false,
  loop: false,
  controls: false,
  volume: 1,
  muted: false,

  init: function(element) {
    this.domElement = element;
    this.src = this.domElement.getAttribute("src");
    this.autobuffer = (this.domElement.getAttribute("autobuffer")!=null);
    this.autoplay = (this.domElement.getAttribute("autoplay")!=null);
    this.loop = (this.domElement.getAttribute("loop")!=null);
    this.controls = (this.domElement.getAttribute("controls")!=null);
    this.load();
  },

  //returns void
  load: function() {
    this.currentSrc = this.src;
    //find the right source
    var candidate = this.domElement.firstChild;
    var maybe = null;
    //loop until we have found a type that works probably
    while(candidate!=null&&this.currentSrc==null) {
      if (candidate.nodeName=="SOURCE"||candidate.nodeName=="source") {
        if (candidate.getAttribute("src")!=null) {
          if (this.canPlayType(candidate.getAttribute("type"))=="probably") {
            this.currentSrc = candidate.getAttribute("src");
          } else if (maybe==null&&this.canPlayType(candidate.getAttribute("type"))=="maybe") {
            maybe = candidate.getAttribute("src");
          }
        }
      }
      candidate = candidate.nextSibling;
    }
    //fall back to the first type that works maybe
    if (this.currentSrc==null&&maybe!=null) {
      this.currentSrc = maybe;
    }
    if (this.currentSrc==null) {
      //media selection failed
      this.error = new MediaError(MediaError.prototype.MEDIA_ERR_SRC_NOT_SUPPORTED);
    }
    //override this in concrete implementations to build the widget
  },

  //returns String
  canPlayType: function(type) {
    return "no";
  },

  play: function() {
    //TODO
    //purely abstract
  },

  pause: function() {
    //TODO
    //purely abstract
  },

  //returns void
  //className, id - String
  //start, end - float
  //pauseOnExit - boolean
  //enterCallback, exitCallback - function
  addCueRange: function(className, id, start, end, pauseOnExit, enterCallback, exitCallback) {
    if (!this.cueRanges[className]||this.cueRanges[className]==null) {
      this.cueRanges[className] = [];
    }

    var cueRange = {
      start: start,
      end: end,
      pauseOnExit: pauseOnExit,
      enterCallback: enterCallback,
      exitCallback: exitCallback,
    };
    this.cueRanges[className].push(cueRange);
  },

  removeCueRange: function(className) {
    //reset cue ranges
    cueRanges[className] = [];
  },

  //private
  cueRanges: {},
  lastPosition: 0.0,

  checkCueRanges: function(currentPosition) {
    try {
      var entering = new Array();
      var exititing = new Array();
      for (className in this.cueRanges) {
        if (this.cueRanges.hasOwnProperty(className)) {
          var cues = this.cueRanges[className];
          for (var i=0;i<cues.length;i++) {
            var cue = cues[i];
            if (currentPosition>this.lastPosition) {
              if (cue.start>this.lastPosition&&cue.start<currentPosition) {
                entering.push(cue);
              }
              if (cue.end>this.lastPosition&&cue.end<currentPosition) {
                exititing.push(cue);
              }
            } else if (currentPosition<this.lastPosition) {
              if (cue.end>this.lastPosition&&cue.end<currentPosition) {
                entering.push(cue);
              }
              if (cue.start>this.lastPosition&&cue.start<currentPosition) {
                exititing.push(cue);
              }
            }
          }
        }
      }

      //call the entering events
      for (var i=0;i<entering.length;i++) {
        if (entering[i].enterCallback) {
          entering[i].enterCallback.call(this, entering[i].id);
        }
      }
      //call the exiting events
      for (var i=0;i<exititing.length;i++) {
        if (exititing[i].exitCallback) {
          exititing[i].exitCallback.call(this, exititing[i].id);
        }
        if (exititing[i].pauseOnExit) {
          this.pause();
        }
      }
    } catch (e) {
      console.error(e);
    }
    this.lastPosition = currentPosition;
  }
});

var HTMLVideoElement = HTMLMediaElement.extend({
    width: "0px",
    height: "0px",
    videoWidth: 0,
    videoHeight: 0,
    //poster frame
    poster: null,

    init: function(element) {
      this._super(element);
      this.height = this.domElement.getAttribute("height");
      this.width = this.domElement.getAttribute("width");
      this.poster = this.domElement.getAttribute("poster");
    }
});

var HTMLAudioElement = HTMLMediaElement.extend({
    id: "id" + (new Date().getTime()),
    sound: null,

    //no additional properties
    init: function(element) {
      this._super(element);

      if (this.domElement.getAttribute("id")) {
        this.id = this.domElement.getAttribute("id");
      }

      var that = this;

      this.sound = soundManager.createSound({
          id: that.id,
          url: that.currentSrc,
          autoLoad: that.autobuffer,
          autoPlay: that.autoplay,
          whileloading: that.whileloading,
      });
      this.sound.wrapper = this;
    },

    onfinish: function(e) {
      if (this.wrapper.loop) {
        this.wrapper.play();
      } else {
        this.wrapper.ended = true;
      }
    },

    whileloading: function() {
      if (this.readyState==3) {
        this.wrapper.networkState = this.wrapper.NETWORK_LOADED;
        this.wrapper.duration = this.duration;
      } else if (this.readyState==2) {
        //error
        this.wrapper.networkState = this.wrapper.NETWORK_NO_SOURCE;
      } else if (this.readyState==1) {
        //loading
        this.wrapper.networkState = this.wrapper.NETWORK_LOADING;
        this.wrapper.duration = this.durationEstimate;
      } else if (this.readyState==0) {
        //uninitialized
        this.wrapper.networkState = this.wrapper.NETWORK_EMPTY;
      }
      console.log(this.wrapper.networkState);
    },

    onload: function(success) {
      if (success) {
        this.wrapper.networkState = this.wrapper.NETWORK_LOADED;
        this.wrapper.duration = this.duration;
      } else {
        this.wrapper.networkState = this.wrapper.NETWORK_NO_SOURCE;
        this.wrapper.error = new MediaError(MediaError.prototype.NETWORK);
      }
    },

    whileplaying: function() {
      this.wrapper.currentTime = this.position / 1000;
      this.wrapper.checkCueRanges(this.position / 1000);
    },

    play: function() {
      if (this.muted) {
        this.sound.setVolume(0);
      } else {
        this.sound.setVolume(Math.floor(100*Math.max(0, Math.min(1,this.volume))));
      }

      if (this.sound.playState==1) {
        this.sound.position = Math.floor(this.currentTime * 1000);
        this.sound.resume();
      } else {
        var that = this;
        this.sound.wrapper = this;
        this.sound.play({
            onfinish: that.onfinish,
            whileplaying: that.whileplaying,
            position: Math.floor(that.startTime * 1000),
            whileloading: that.whileloading,
        });
      }
    },

    pause: function() {
      this.sound.pause();
    },

    canPlayType: function(type) {
      if (type.match(/^audio\/mp3/)) {
        return "probably";
      }
      if (type.match(/^audio\/wav/)) {
        return "probably";
      }
      if (type.match(/^audio\/(x-)?aiff/)) {
        return "probably";
      }
      if (type.match(/^audio\//)) {
        return "maybe";
      }
      return "no";
    }
});

function getHTML5Tags() {
  var audios = document.getElementsByTagName("audio");
  var videos = document.getElementsByTagName("video");
  var html5tags = [];
  for (var i=0;i<audios.length;i++) {
    if (audios[i].play) {
      html5tags.push(audios[i]);
    }
    html5tags.push(new HTMLAudioElement(audios[i]));
  }

  for (var i=0;i<videos.length;i++) {
    if (videos[i].play) {
      html5tags.push(videos[i]);
    }
    html5tags.push(new HTMLVideoElement(videos[i]));
  }
  return html5tags;
}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
//var globalTunnel = require('global-tunnel');
//globalTunnel.initialize();

var session = require('express-session');
var partials = require('express-partials');

////////////////////////////////////////////////////////////////
// MongoDB初期化
var model = require('./model');
var User = model.User;
var Score = model.Score;

// ページ遷移
var routes = require('./routes/index');
var dashboard = require('./routes/dashboard');
var answer = require('./routes/answer');
var login = require('./routes/login');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(partials());
app.use(session({
  secret: 'the quick brown fox',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 30*60*1000
  }
}));

////////////////////////////////////////////////////////////////
// セッションチェック
var sessionCheck = function(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    res.redirect('/');
  }
};

////////////////////////////////////////////////////////////////
// 認証処理
var authconfig = require('./auth.js');
var passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

////////////////////////////////////////////////////////////////
// GitHubアカウントによるOAuth処理
var GitHubStrategy = require('passport-github').Strategy;
passport.use(new GitHubStrategy({
    clientID: authconfig.github.clientID,
    clientSecret: authconfig.github.clientSecret,
    callbackURL: authconfig.github.callbackURL,
  },
  function(token, tokenSecret, profile, done) {
    User.find({provider: profile.provider, provider_id: profile.id}, function(err, docs){
      if (docs.length == 0) {
        var user = new User({ provider: profile.provider, provider_id: profile.id, nickname: profile.username });
        user.save(function(err) {
          if (err) { console.log(err); }
        });
      }
      if (err) {
        return done(err);
      }
      return done(null, profile);
    });
  })
);

app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/' }),
  function (req, res) {
    req.session.user = {name: req.body.username};
    res.redirect('/dashboard');
  }
);

////////////////////////////////////////////////////////////////
// TwitterアカウントによるOAuth処理
var TwitterStrategy = require('passport-twitter').Strategy;
passport.use(new TwitterStrategy({
    clientID: authconfig.twitter.clientID,
    clientSecret: authconfig.twitter.clientSecret,
    callbackURL: authconfig.twitter.callbackURL,
  },
  function(token, tokenSecret, profile, done) {
    User.find({provider: profile.provider, provider_id: profile.id}, function(err, docs){
      if (docs.length == 0) {
        var user = new User({ provider: profile.provider, provider_id: profile.id, nickname: profile.username });
        user.save(function(err) {
          if (err) { console.log(err); }
        });
      }
      if (err) {
        return done(err);
      }
      return done(null, profile);
    });
  })
);
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/' }),
  function (req, res) {
    req.session.user = {name: req.body.username};
    res.redirect('/dashboard');
  }
);

////////////////////////////////////////////////////////////////
// GoogleアカウントによるOAuth処理
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.use(new GoogleStrategy({
    clientID: authconfig.google.clientID,
    clientSecret: authconfig.google.clientSecret,
    callbackURL: authconfig.google.callbackURL,
  },
  function(token, tokenSecret, profile, done) {
    User.find({provider: profile.provider, provider_id: profile.id}, function(err, docs){
      if (docs.length == 0) {
        var user = new User({ provider: profile.provider, provider_id: profile.id, nickname: profile.username });
        user.save(function(err) {
          if (err) { console.log(err); }
        });
      }
      if (err) {
        return done(err);
      }
      return done(null, profile);
    });
  })
);
app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }),
  function (req, res) {
    req.session.user = {name: req.body.username};
    res.redirect('/dashboard');
  }
);

///////////////////////////////////////
app.use('/', routes);
app.use('/login', login);
app.use('/dashboard', sessionCheck, dashboard);
app.use('/answer', sessionCheck, answer);

var problem = require('./routes/problem/problem_public');
app.use('/problem', sessionCheck, problem);

app.get('/logout', function(req, res) {
  delete req.session.user;
  res.redirect('/');
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>seiri<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
//var globalTunnel = require('global-tunnel');
//globalTunnel.initialize();

var session = require('express-session');
var partials = require('express-partials');

////////////////////////////////////////////////////////////////
// MongoDB初期化
var model = require('./model');
var User = model.User;
var Score = model.Score;

// ページ遷移
var routes = require('./routes/index');
var dashboard = require('./routes/dashboard');
var answer = require('./routes/answer');
var login = require('./routes/login');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(partials());
app.use(session({
  secret: 'the quick brown fox',
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 30*60*1000
  }
}));

////////////////////////////////////////////////////////////////
// セッションチェック
var sessionCheck = function(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    res.redirect('/');
  }
};

////////////////////////////////////////////////////////////////
// 認証処理
var authconfig = require('./auth.js');
var passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

////////////////////////////////////////////////////////////////
// GitHubアカウントによるOAuth処理
var GitHubStrategy = require('passport-github').Strategy;
passport.use(new GitHubStrategy({
    clientID: authconfig.github.clientID,
    clientSecret: authconfig.github.clientSecret,
    callbackURL: authconfig.github.callbackURL,
  },
  function(token, tokenSecret, profile, done) {
    User.find({provider: profile.provider, provider_id: profile.id}, function(err, docs){
      if (docs.length == 0) {
        var user = new User({ provider: profile.provider, provider_id: profile.id, nickname: profile.username });
        user.save(function(err) {
          if (err) { console.log(err); }
        });
      }
      if (err) {
        return done(err);
      }
      return done(null, profile);
    });
  })
);

app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/' }),
  function (req, res) {
    req.session.user = {name: req.body.username};
    res.redirect('/dashboard');
  }
);

////////////////////////////////////////////////////////////////
// TwitterアカウントによるOAuth処理
var TwitterStrategy = require('passport-twitter').Strategy;
passport.use(new TwitterStrategy({
    clientID: authconfig.twitter.clientID,
    clientSecret: authconfig.twitter.clientSecret,
    callbackURL: authconfig.twitter.callbackURL,
  },
  function(token, tokenSecret, profile, done) {
    User.find({provider: profile.provider, provider_id: profile.id}, function(err, docs){
      if (docs.length == 0) {
        var user = new User({ provider: profile.provider, provider_id: profile.id, nickname: profile.username });
        user.save(function(err) {
          if (err) { console.log(err); }
        });
      }
      if (err) {
        return done(err);
      }
      return done(null, profile);
    });
  })
);
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/' }),
  function (req, res) {
    req.session.user = {name: req.body.username};
    res.redirect('/dashboard');
  }
);

////////////////////////////////////////////////////////////////
// GoogleアカウントによるOAuth処理
var GoogleStrategy = require('passport-google-oauth').Strategy;
passport.use(new GoogleStrategy({
    clientID: authconfig.google.clientID,
    clientSecret: authconfig.google.clientSecret,
    callbackURL: authconfig.google.callbackURL,
  },
  function(token, tokenSecret, profile, done) {
    User.find({provider: profile.provider, provider_id: profile.id}, function(err, docs){
      if (docs.length == 0) {
        var user = new User({ provider: profile.provider, provider_id: profile.id, nickname: profile.username });
        user.save(function(err) {
          if (err) { console.log(err); }
        });
      }
      if (err) {
        return done(err);
      }
      return done(null, profile);
    });
  })
);
app.get('/auth/google', passport.authenticate('google'));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }),
  function (req, res) {
    req.session.user = {name: req.body.username};
    res.redirect('/dashboard');
  }
);

///////////////////////////////////////
app.use('/', routes);
app.use('/login', login);
app.use('/dashboard', sessionCheck, dashboard);
app.use('/answer', sessionCheck, answer);

var problem = require('./routes/problem/problem_public');
app.use('/problem', sessionCheck, problem);

app.get('/logout', function(req, res) {
  delete req.session.user;
  res.redirect('/');
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>var baseUrl, dep, callback;

if ( window.__karma__ ) {
    var tests = [];
    for ( var file in window.__karma__.files ) {
        if ( /Spec\.js$/.test( file ) ) {
            tests.push( file );
        }
    }
    // Karma serves files from '/base'
    baseUrl = '/base/src';
    deps = tests;
    callback = window.__karma__.start;
} else {
    baseUrl = '../src';
    deps = [
        'tests/specs/array/JoinSpec',
        'tests/specs/collection/LimitSpec',
        'tests/specs/collection/WhereSpec',
        'tests/specs/comparison/IfEqOrSpec',
        'tests/specs/comparison/IfEqSpec',
        'tests/specs/comparison/IfGteSpec',
        'tests/specs/comparison/IfGtSpec',
        'tests/specs/comparison/IfLteSpec',
        'tests/specs/comparison/IfltSpec',
        'tests/specs/comparison/IfNotEqSpec',
        'tests/specs/date/AgoSpec',
        'tests/specs/date/FormatDateSpec',
        'tests/specs/date/FromNowSpec',
        'tests/specs/date/NowSpec',
        'tests/specs/form/SelectOptionsListSpec',
        'tests/specs/math/AddSpec',
        'tests/specs/math/CeilSpec',
        'tests/specs/math/DivideSpec',
        'tests/specs/math/FloorSpec',
        'tests/specs/math/MultiplySpec',
        'tests/specs/math/RoundSpec',
        'tests/specs/math/SubtractSpec',
        'tests/specs/string/CapitalizeSpec',
        'tests/specs/string/EncodeURIComponentSpec',
        'tests/specs/string/LowercaseSpec',
        'tests/specs/string/UppercaseSpec'
    ];
    callback = mocha.run;
}

requirejs.config({
    baseUrl: baseUrl,
    paths: {
        "underscore"        : "../test/bower_components/underscore/underscore",
        "handlebars"        : "../test/bower_components/handlebars/handlebars.amd",
        "moment"            : "../test/bower_components/moment/moment",
        "tests"             : "../test"
    },
    deps: deps,
    callback: function() {
        callback();
    }
});
<commit_msg>Add markdown helper tests to AMD spec runner<commit_after>var baseUrl, dep, callback;

if ( window.__karma__ ) {
    var tests = [];
    for ( var file in window.__karma__.files ) {
        if ( /Spec\.js$/.test( file ) ) {
            tests.push( file );
        }
    }
    // Karma serves files from '/base'
    baseUrl = '/base/src';
    deps = tests;
    callback = window.__karma__.start;
} else {
    baseUrl = '../src';
    deps = [
        'tests/specs/array/JoinSpec',
        'tests/specs/collection/LimitSpec',
        'tests/specs/collection/WhereSpec',
        'tests/specs/comparison/IfEqOrSpec',
        'tests/specs/comparison/IfEqSpec',
        'tests/specs/comparison/IfGteSpec',
        'tests/specs/comparison/IfGtSpec',
        'tests/specs/comparison/IfLteSpec',
        'tests/specs/comparison/IfltSpec',
        'tests/specs/comparison/IfNotEqSpec',
        'tests/specs/date/AgoSpec',
        'tests/specs/date/FormatDateSpec',
        'tests/specs/date/FromNowSpec',
        'tests/specs/date/NowSpec',
        'tests/specs/form/SelectOptionsListSpec',
        'tests/specs/math/AddSpec',
        'tests/specs/math/CeilSpec',
        'tests/specs/math/DivideSpec',
        'tests/specs/math/FloorSpec',
        'tests/specs/math/MultiplySpec',
        'tests/specs/math/RoundSpec',
        'tests/specs/math/SubtractSpec',
        'tests/specs/string/CapitalizeSpec',
        'tests/specs/string/EncodeURIComponentSpec',
        'tests/specs/string/LowercaseSpec',
        'tests/specs/string/MarkdownSpec',
        'tests/specs/string/UppercaseSpec'
    ];
    callback = mocha.run;
}

requirejs.config({
    baseUrl: baseUrl,
    paths: {
        "underscore"        : "../test/bower_components/underscore/underscore",
        "handlebars"        : "../test/bower_components/handlebars/handlebars.amd",
        "moment"            : "../test/bower_components/moment/moment",
        "pagedown"          : "../test/bower_components/pagedown/Markdown.Converter",
        "tests"             : "../test"
    },
    shim: {
        "pagedown": {
            exports: "Markdown"
        }
    },
    deps: deps,
    callback: function() {
        callback();
    }
});
<|endoftext|>


<commit_before>import { createStore as _createStore, applyMiddleware, compose } from 'redux';
import createMiddleware from './middleware/clientMiddleware';
import transitionMiddleware from './middleware/transitionMiddleware';

export default function createStore(reduxReactRouter, getRoutes, createHistory, client, data) {
  const middleware = [createMiddleware(client), transitionMiddleware];

  let finalCreateStore;
  if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) {
    const { devTools, persistState } = require('redux-devtools');
    finalCreateStore = compose(
      applyMiddleware(...middleware),
      devTools(),
      persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
    )(_createStore);
  } else {
    finalCreateStore = applyMiddleware(...middleware)(_createStore);
  }

  finalCreateStore = reduxReactRouter({ getRoutes, createHistory })(finalCreateStore);

  const reducer = require('./modules/reducer');
  const store = finalCreateStore(reducer, data);
  store.client = client;

  if (__DEVELOPMENT__ && module.hot) {
    module.hot.accept('./modules/reducer', () => {
      store.replaceReducer(require('./modules/reducer'));
    });
  }

  return store;
}
<commit_msg>removed old vestigial design element. fixes #352<commit_after>import { createStore as _createStore, applyMiddleware, compose } from 'redux';
import createMiddleware from './middleware/clientMiddleware';
import transitionMiddleware from './middleware/transitionMiddleware';

export default function createStore(reduxReactRouter, getRoutes, createHistory, client, data) {
  const middleware = [createMiddleware(client), transitionMiddleware];

  let finalCreateStore;
  if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) {
    const { devTools, persistState } = require('redux-devtools');
    finalCreateStore = compose(
      applyMiddleware(...middleware),
      devTools(),
      persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
    )(_createStore);
  } else {
    finalCreateStore = applyMiddleware(...middleware)(_createStore);
  }

  finalCreateStore = reduxReactRouter({ getRoutes, createHistory })(finalCreateStore);

  const reducer = require('./modules/reducer');
  const store = finalCreateStore(reducer, data);

  if (__DEVELOPMENT__ && module.hot) {
    module.hot.accept('./modules/reducer', () => {
      store.replaceReducer(require('./modules/reducer'));
    });
  }

  return store;
}
<|endoftext|>


<commit_before>function makeMap(str) {
  return str.split(",").reduce((map, cur) => {
    map[cur] = true
    return map
  }, {})
}

const REGEXP = {
  startTag: /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
  endTag: /^<\/([-A-Za-z0-9_]+)[^>]*>/,
  attr: /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g
}

const MAKER = {
  empty: makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"),
  fillAttrs: makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"),
}

function getAttributes(str) {
  let attrsMap = {}
  str.replace(REGEXP.attr, function(match, name) {
    const value = arguments[2] ? arguments[2] :
      arguments[3] ? arguments[3] :
      arguments[4] ? arguments[4] :
      MAKER.fillAttrs[name] ? name : ""

    attrsMap[name] = value.replace(/(^|[^\\])"/g, '$1\\\"')
  })
  return attrsMap
}

function lex(html) {
  let string = html
  let tokens = []

  while (string) {
    if (string.indexOf("</") === 0) {
      const match = string.match(REGEXP.endTag)
      if (!match) continue
      string = string.substring(match[0].length)
      tokens.push({
        tag: match[1],
        type: 'tag-end',
      })
      continue
    }
    if (string.indexOf("<") === 0) {
      const match = string.match(REGEXP.startTag)
      if (!match) continue
      string = string.substring(match[0].length)
      const tag = match[1]
      const isEmpty = !!MAKER.empty[tag]
      const type = isEmpty ? 'tag-empty' : 'tag-start'
      const attributes = getAttributes(match[2])

      tokens.push({
        tag,
        type,
        attributes
      })
      continue
    }

    const index = string.indexOf('<')
    const text = index < 0 ? string : string.substring(0, index)

    string = index < 0 ? "" : string.substring(index)
    tokens.push({
      type: "text",
      text
    })
  }
  return tokens
}

function parse(tokens) {
  let root = {
    tag: "root",
    children: []
  }
  let tagArray = [root]
  tagArray.last = () => tagArray[tagArray.length - 1]

  for (var i = 0; i < tokens.length; i++) {
    const token = tokens[i]
    if (token.type === 'tag-start') {
      const node = {
        type: "Element",
        tagName: token.tag,
        attributes: token.attributes,
        children: []
      }
      tagArray.push(node)
      continue
    }
    if (token.type === 'tag-end') {
      let parent = tagArray[tagArray.length - 2]
      let node = tagArray.pop()
      parent.children.push(node)
      continue
    }
    if (token.type === 'text') {
      tagArray.last().children.push({
        type: 'text',
        content: token.text
      })
      continue
    }
    if (token.type === 'tag-empty') {
      tagArray.last().children.push({
        type: "Element",
        tagName: token.tag,
        attributes: token.attributes
      })
      continue
    }
  }
  return root
}

export default function htmlParser(html) {
  return parse(lex(html))
}<commit_msg>fix empty tag with tag-end<commit_after>function makeMap(str) {
  return str.split(",").reduce((map, cur) => {
    map[cur] = true
    return map
  }, {})
}

const REGEXP = {
  startTag: /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
  endTag: /^<\/([-A-Za-z0-9_]+)[^>]*>/,
  attr: /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g
}

const MAKER = {
  empty: makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr"),
  fillAttrs: makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected"),
}

function getAttributes(str) {
  let attrsMap = {}
  str.replace(REGEXP.attr, function(match, name) {
    const value = arguments[2] ? arguments[2] :
      arguments[3] ? arguments[3] :
      arguments[4] ? arguments[4] :
      MAKER.fillAttrs[name] ? name : ""

    attrsMap[name] = value.replace(/(^|[^\\])"/g, '$1\\\"')
  })
  return attrsMap
}

function lex(html) {
  let string = html
  let tokens = []

  while (string) {
    if (string.indexOf("</") === 0) {
      const match = string.match(REGEXP.endTag)
      if (!match) continue
      string = string.substring(match[0].length)

      const isEmpty = !!MAKER.empty[tag]
      if (isEmpty) continue

      tokens.push({
        tag: match[1],
        type: 'tag-end',
      })
      continue
    }
    if (string.indexOf("<") === 0) {
      const match = string.match(REGEXP.startTag)
      if (!match) continue
      string = string.substring(match[0].length)
      const tag = match[1]
      const isEmpty = !!MAKER.empty[tag]
      const type = isEmpty ? 'tag-empty' : 'tag-start'
      const attributes = getAttributes(match[2])

      tokens.push({
        tag,
        type,
        attributes
      })
      continue
    }

    const index = string.indexOf('<')
    const text = index < 0 ? string : string.substring(0, index)

    string = index < 0 ? "" : string.substring(index)
    tokens.push({
      type: "text",
      text
    })
  }
  return tokens
}

function parse(tokens) {
  let root = {
    tag: "root",
    children: []
  }
  let tagArray = [root]
  tagArray.last = () => tagArray[tagArray.length - 1]

  for (var i = 0; i < tokens.length; i++) {
    const token = tokens[i]
    if (token.type === 'tag-start') {
      const node = {
        type: "Element",
        tagName: token.tag,
        attributes: token.attributes,
        children: []
      }
      tagArray.push(node)
      continue
    }
    if (token.type === 'tag-end') {
      let parent = tagArray[tagArray.length - 2]
      let node = tagArray.pop()
      parent.children.push(node)
      continue
    }
    if (token.type === 'text') {
      tagArray.last().children.push({
        type: 'text',
        content: token.text
      })
      continue
    }
    if (token.type === 'tag-empty') {
      tagArray.last().children.push({
        type: "Element",
        tagName: token.tag,
        attributes: token.attributes
      })
      continue
    }
  }
  return root
}

export default function htmlParser(html) {
  return parse(lex(html))
}<|endoftext|>


<commit_before>var express = require('express');
var DeviceManager = require('./devicemanager.js').DeviceManager;
var _ = require('underscore');
var scheduler = require('node-schedule');
var storage = require('node-persist');

var manager = new DeviceManager();
var app = express();

app.set('views', __dirname + '/views')
app.set('view engine', 'jade')

app.get('/', function(req, res) {
	var devices = _.map(manager.getDevices(), function (uuid) {
		var device = manager.getDevice(uuid);
		return {
			uuid: uuid,
			icon: device.icon,
			name: device.name
		}
	});
	res.render('index', {
		title : 'Devices',
		devices: devices
	} );
});

var server = app.listen(18080);

var changeSource= function (uuid, sourceId) {
    return function () {
        var device = manager.getDevice(uuid);
	if (device) {
            manager.changeSource(device, sourceId);
	}
    }
};

storage.initSync();

if (!storage.getItem('schedules.json') {
    storeage.setItem('schedules.json', []);
}

_.each(storage.getItem('schedules.json'), function (schedule) {
	var recurrence = new scheduler.RecurrenceRule();
	recurrence.dayOfWeek = schedule.dayOfWeek;
	recurrence.hour = schedule.hour;
	recurrence.minute = schedule.minute;
	scheduler.scheduleJob(recurrence, changeSource(schedule.uuid,schedule.source));
});
<commit_msg>Syntax error fix<commit_after>var express = require('express');
var DeviceManager = require('./devicemanager.js').DeviceManager;
var _ = require('underscore');
var scheduler = require('node-schedule');
var storage = require('node-persist');

var manager = new DeviceManager();
var app = express();

app.set('views', __dirname + '/views')
app.set('view engine', 'jade')

app.get('/', function(req, res) {
	var devices = _.map(manager.getDevices(), function (uuid) {
		var device = manager.getDevice(uuid);
		return {
			uuid: uuid,
			icon: device.icon,
			name: device.name
		}
	});
	res.render('index', {
		title : 'Devices',
		devices: devices
	} );
});

var server = app.listen(18080);

var changeSource= function (uuid, sourceId) {
    return function () {
        var device = manager.getDevice(uuid);
	if (device) {
            manager.changeSource(device, sourceId);
	}
    }
};

storage.initSync();

if (!storage.getItem('schedules.json')) {
    storeage.setItem('schedules.json', []);
}

_.each(storage.getItem('schedules.json'), function (schedule) {
	var recurrence = new scheduler.RecurrenceRule();
	recurrence.dayOfWeek = schedule.dayOfWeek;
	recurrence.hour = schedule.hour;
	recurrence.minute = schedule.minute;
	scheduler.scheduleJob(recurrence, changeSource(schedule.uuid,schedule.source));
});
<|endoftext|>


<commit_before>import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
import axios from 'axios'
import thunk from 'redux-thunk'

import { Request } from '../api'
import rootReducer from '../ducks/reducer'
import createMiddleware from './clientMiddleware'
import DevTools from './DevTools'

const getDebugSessionKey = () => {
  // You can write custom logic here!
  // By default we try to read the key from ?debug_session=<key> in the address bar
  const matches = window.location.href.match(/[?&]debug_session=([^&#]+)\b/)
  return (matches && matches.length > 0)? matches[1] : null
}

export default function createApiClientStore(client, initialState) {
  const request = new Request()
  const thunkWithExtraArgument = thunk.withExtraArgument(request)
  const middleware = createMiddleware(client)
  let enhancer

  if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) {
    const { persistState } = require('redux-devtools')
    enhancer = compose(
      applyMiddleware(thunkWithExtraArgument),
      applyMiddleware(middleware),
      DevTools.instrument(),
      persistState(getDebugSessionKey())
    )(createStore)
  } else {
    enhancer = compose(
      applyMiddleware(thunkWithExtraArgument),
      applyMiddleware(middleware)
    )(createStore)
  }

  const store = enhancer(rootReducer, initialState)
  store.client = client
  store.request = request

  if (__DEVELOPMENT__ && module.hot) {
    module.hot.accept('../ducks/reducer', () => {
      store.replaceReducer(require('../ducks/reducer'))
    })
  }

  return store
}
<commit_msg>Fix change DevTools component require only when environment is development. #184<commit_after>import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
import axios from 'axios'
import thunk from 'redux-thunk'

import { Request } from '../api'
import rootReducer from '../ducks/reducer'
import createMiddleware from './clientMiddleware'

const getDebugSessionKey = () => {
  // You can write custom logic here!
  // By default we try to read the key from ?debug_session=<key> in the address bar
  const matches = window.location.href.match(/[?&]debug_session=([^&#]+)\b/)
  return (matches && matches.length > 0)? matches[1] : null
}

export default function createApiClientStore(client, initialState) {
  const request = new Request()
  const thunkWithExtraArgument = thunk.withExtraArgument(request)
  const middleware = createMiddleware(client)
  let enhancer

  if (__DEVELOPMENT__ && __CLIENT__ && __DEVTOOLS__) {
    const { persistState } = require('redux-devtools')
    const DevTools = require('DevTools')
    enhancer = compose(
      applyMiddleware(thunkWithExtraArgument),
      applyMiddleware(middleware),
      DevTools.instrument(),
      persistState(getDebugSessionKey())
    )(createStore)
  } else {
    enhancer = compose(
      applyMiddleware(thunkWithExtraArgument),
      applyMiddleware(middleware)
    )(createStore)
  }

  const store = enhancer(rootReducer, initialState)
  store.client = client
  store.request = request

  if (__DEVELOPMENT__ && module.hot) {
    module.hot.accept('../ducks/reducer', () => {
      store.replaceReducer(require('../ducks/reducer'))
    })
  }

  return store
}
<|endoftext|>


<commit_before>/**
 * Created by Scott on 2/25/2015.
 */
define(['testharness', '../lib/request', '../lib/squareDB'],
    function(harness, request, squareDB) {
        return {
            run: function () {
                "use strict";

                var db, table, query;

                harness.test(function () {
                    db = squareDB.createDB('Library');
                    harness.assert_true(squareDB.getDB('Library') !== undefined);
                }, "CREATE DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = squareDB.dropDB('Library');
                    harness.assert_true(db && squareDB.getDB('Library') === undefined);
                }, "DROP DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = squareDB.createDB('Library');
                    table = db.createTable('Books')('title');
                    harness.assert_true(table.hasOwnProperty('title'));
                }, "CREATE TABLE Books (title)");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');

                harness.test(function () {

                    db.createTable('Books')('title');
                    db.insertInto('Books')('title').values('Book of Foo');
                    query = db.select('title').from('Books').go();
                    harness.assert_true(query[0].title === 'Book of Foo');
                }, "INSERT INTO Books (title) VALUES ('Book of Foo')");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title');

                harness.test(function () {
                    var testPassed,
                        titlesArray;

                    db.insertInto('Books')('title').values('Alphabet Soup')('Aliens')('Baseball')('Bats')('Cats')('Soup for the Soul');
                    titlesArray = db.select('title').from('Books').go();
                    testPassed = titlesArray.every(function (rowObj) {
                        var title = rowObj.title,
                            a = ['Alphabet Soup', 'Aliens', 'Baseball', 'Bats', 'Cats', 'Soup for the Soul'];

                        return title && a.indexOf(title) >= 0;
                    });
                    harness.assert_true(testPassed);
                }, "INSERT INTO Books (title) VALUES ('Alphabet Soup'),('Aliens'),('Baseball'),('Bats'),('Cats'),('Soup for the Soul')");

                // next test uses prerequisites from previous test...
                harness.test(function () {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').go();
                    harness.assert_true(query[0] && query[0].title === 'Aliens');
                }, "SELECT title FROM Books WHERE title = 'Aliens'");

                // keep going...
                harness.test(function () {
                    var passedTest;

                    query = db.select('title').from('Books').where('title', 'like', 'soup').go();
                    passedTest = query.length === 0;
                    if (passedTest) {
                        query = db.select('title').from('Books').where('title', 'like', '.*soup').go();
                        passedTest = query.length === 1 && query[0].title === 'Alphabet Soup';
                    }
                    if (passedTest) {
                        query = db.select('title').from('Books').where('title', 'like', 'ba.*').go();
                        passedTest = query.length === 2 && query[0].title === 'Baseball' && query[1].title === 'Bats';
                    }
                    if (passedTest) {
                        query = db.select('title').from('Books').where('title', 'like', '.*ou.*ou.*').go();
                        passedTest = query.length === 1 && query[0].title === 'Soup for the Soul';
                    }
                    harness.assert_true(passedTest);
                }, "SELECT title FROM Books WHERE title LIKE %ou%ou%  => plus 3 more 'LIKE' tests");

                harness.test(function () {
                    var passedTest;

                    query = db.select('title').from('Books').where('title', 'not like', '.*b.*').go();
                    passedTest = query.length === 3 && query[0].title === 'Aliens' && query[1].title === 'Cats' && query[2].title === 'Soup for the Soul';
                    harness.assert_true(passedTest);
                }, "SELECT title FROM Books WHERE title NOT LIKE %b%");

                harness.test(function () {
                    query = db.select('*').from('Books').go();
                    harness.assert_true(query.length === 6);
                }, "SELECT * FROM Books");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');

                harness.test(function () {
                    var testPassed, returnSet;

                    db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Abe Jones')
                                                                    ('Coffee Break', 'Bob Aaron')('Bats', 'Wes Stacks')('Cats', 'Kaitlyn Rose')
                                                                    ('Soup for the Soul', 'Flora Ivy');
                    returnSet = db.select('author').from('Books').where('author', 'like', '.*o.*s.*').go();
                    testPassed = returnSet.length === 3 && returnSet[0]['author'] === 'Abe Jones' && returnSet[1]['author'] === 'Abe Jones' && returnSet[2]['author'] === 'Kaitlyn Rose';
                    harness.assert_true(testPassed);
                }, "SELECT title FROM Books WHERE author LIKE %o%s%  => condition based on field not in SELECT");

                harness.test(function () {
                    // todo: special case when select is called empty?
                    var returnSet = db.select().distinct('author').from('Books').go(),
                        testPassed;
                    console.log('returnSet', returnSet);
                    testPassed = returnSet.length === 6 && returnSet[0]['author'] === 'Hank Aaron' && returnSet[1]['author'] === 'Abe Jones' && returnSet[2]['author'] === 'Bob Aaron';
                    harness.assert_true(testPassed);
                }, "SELECT DISTINCT author FROM Books WHERE author = 'Creepy Guy'");

                harness.test(function () {
                    db.update('Books').set('title', 'Green Eggs & Ham')('author', 'Dr. Seuss').where('title', '===', 'Bats').go();
                    query = db.select('title', 'author').from('Books').go();
                    harness.assert_true(query.length === 7 && query[4].title === 'Green Eggs & Ham' && query[4]['author'] === 'Dr. Seuss');
                }, "UPDATE Books SET title = 'Green Eggs & Ham', author = 'Dr. Seuss' WHERE title = 'Bats'");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', 'like', '.*break').and('author', 'like', '.*Aaron').go();
                    harness.assert_true(query[0].title === 'Coffee Break');
                }, "SELECT title FROM Books WHERE title like %break AND author like %Aaron");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').or('author', '===', 'Kaitlyn Rose').go();
                    harness.assert_true(query.length === 2 && query[0].title === 'Aliens' && query[1].title === 'Cats');
                }, "SELECT title FROM Books WHERE title = 'Aliens' OR author = 'Kaitlyn Rose'");

                harness.test(function() {
                    var d = db.delete().from('Books').where('author', '===', 'Hank Aaron').or('author', 'like', '.*ivy').go();
                    query = db.select('title', 'author').from('Books').where('author', '===', 'Hank Aaron').or('author', 'like', '.*ivy').go();
                    console.log('delete 1st and last title', Array.from(d.title));
                    console.log('delete 1st and last author', Array.from(d['author']));
                    harness.assert_true(query.length === 0);
                }, "DELETE FROM Books WHERE author === 'Hank Aaron' OR author like %ivy");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');
                db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')('Soup for the Soul', 'Flora Ivy');

                harness.test(function() {
                    var d = db.delete('author').from('Books').go();
                    query = db.select('author').from('Books').go();
                    console.log('delete author', Array.from(d['author']));
                    console.log('did not delete title', db.select('title').from('Books').go());
                    harness.assert_true(query.length === 0);
                }, "DELETE author FROM Books");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');
                db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')('Soup for the Soul', 'Flora Ivy');

                harness.test(function() {
                    var d = db.delete('*').from('Books').go();  // same as db.delete().from('Books').go();
                    var q1 = db.select('title').from('Books').go(),
                        q2 = db.select('author').from('Books').go();

                    console.log('delete title and author data from Books - Title', Array.from(d.title));
                    console.log('delete title and author data from Books - Author', Array.from(d.title));
                    harness.assert_true(q1.length === 0 && q2.length === 0);
                }, "DELETE * FROM Books => same as DELETE FROM Books");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');
                db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')('Soup for the Soul', 'Flora Ivy');

                harness.test(function() {
                    db.alterTable('Books').add('pages');
                    query = db.select('pages').from('Books').go();
                    harness.assert_true(query.length === 7);
                }, "ALTER TABLE Books ADD pages");

                harness.test(function() {
                    db.alterTable('Books').drop('pages');
                    query = db.select('pages').from('Books').go();
                    console.log('table', table);
                    harness.assert_true(query.length === 0);
                }, "ALTER TABLE Books DROP pages");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author', 'pages');
                db.insertInto('Books')('title', 'author', 'pages').values('Baseball', 'Hank Aaron', 90)('Alphabet Soup', 'Abe Jones', 540)('Aliens', 'Corey Dorey', 210)
                ('Coffee Break', 'Bob Aaron', 65)('Bats', 'Creepy Guy', 300)('Cats', 'Kaitlyn Rose', 829)('Soup for the Soul', 'Flora Ivy', 1200);

                harness.test(function() {
                    query = db.select().min('pages').from('Books').go();
                    harness.assert_true(query['pages'] === 65);
                }, "SELECT AVG('pages') FROM Books");

            }
        };
    }
);
<commit_msg>squareDBTests - Coverage added for MAX, SUM, and AVG<commit_after>/**
 * Created by Scott on 2/25/2015.
 */
define(['testharness', '../lib/request', '../lib/squareDB'],
    function(harness, request, squareDB) {
        return {
            run: function () {
                "use strict";

                var db, table, query;

                harness.test(function () {
                    db = squareDB.createDB('Library');
                    harness.assert_true(squareDB.getDB('Library') !== undefined);
                }, "CREATE DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = squareDB.dropDB('Library');
                    harness.assert_true(db && squareDB.getDB('Library') === undefined);
                }, "DROP DATABASE Library  => happens in each test, checking here");

                harness.test(function () {
                    db = squareDB.createDB('Library');
                    table = db.createTable('Books')('title');
                    harness.assert_true(table.hasOwnProperty('title'));
                }, "CREATE TABLE Books (title)");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');

                harness.test(function () {

                    db.createTable('Books')('title');
                    db.insertInto('Books')('title').values('Book of Foo');
                    query = db.select('title').from('Books').go();
                    harness.assert_true(query[0].title === 'Book of Foo');
                }, "INSERT INTO Books (title) VALUES ('Book of Foo')");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title');

                harness.test(function () {
                    var testPassed,
                        titlesArray;

                    db.insertInto('Books')('title').values('Alphabet Soup')('Aliens')('Baseball')('Bats')('Cats')('Soup for the Soul');
                    titlesArray = db.select('title').from('Books').go();
                    testPassed = titlesArray.every(function (rowObj) {
                        var title = rowObj.title,
                            a = ['Alphabet Soup', 'Aliens', 'Baseball', 'Bats', 'Cats', 'Soup for the Soul'];

                        return title && a.indexOf(title) >= 0;
                    });
                    harness.assert_true(testPassed);
                }, "INSERT INTO Books (title) VALUES ('Alphabet Soup'),('Aliens'),('Baseball'),('Bats'),('Cats'),('Soup for the Soul')");

                // next test uses prerequisites from previous test...
                harness.test(function () {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').go();
                    harness.assert_true(query[0] && query[0].title === 'Aliens');
                }, "SELECT title FROM Books WHERE title = 'Aliens'");

                // keep going...
                harness.test(function () {
                    var passedTest;

                    query = db.select('title').from('Books').where('title', 'like', 'soup').go();
                    passedTest = query.length === 0;
                    if (passedTest) {
                        query = db.select('title').from('Books').where('title', 'like', '.*soup').go();
                        passedTest = query.length === 1 && query[0].title === 'Alphabet Soup';
                    }
                    if (passedTest) {
                        query = db.select('title').from('Books').where('title', 'like', 'ba.*').go();
                        passedTest = query.length === 2 && query[0].title === 'Baseball' && query[1].title === 'Bats';
                    }
                    if (passedTest) {
                        query = db.select('title').from('Books').where('title', 'like', '.*ou.*ou.*').go();
                        passedTest = query.length === 1 && query[0].title === 'Soup for the Soul';
                    }
                    harness.assert_true(passedTest);
                }, "SELECT title FROM Books WHERE title LIKE %ou%ou%  => plus 3 more 'LIKE' tests");

                harness.test(function () {
                    var passedTest;

                    query = db.select('title').from('Books').where('title', 'not like', '.*b.*').go();
                    passedTest = query.length === 3 && query[0].title === 'Aliens' && query[1].title === 'Cats' && query[2].title === 'Soup for the Soul';
                    harness.assert_true(passedTest);
                }, "SELECT title FROM Books WHERE title NOT LIKE %b%");

                harness.test(function () {
                    query = db.select('*').from('Books').go();
                    harness.assert_true(query.length === 6);
                }, "SELECT * FROM Books");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');

                harness.test(function () {
                    var testPassed, returnSet;

                    db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Abe Jones')
                                                                    ('Coffee Break', 'Bob Aaron')('Bats', 'Wes Stacks')('Cats', 'Kaitlyn Rose')
                                                                    ('Soup for the Soul', 'Flora Ivy');
                    returnSet = db.select('author').from('Books').where('author', 'like', '.*o.*s.*').go();
                    testPassed = returnSet.length === 3 && returnSet[0]['author'] === 'Abe Jones' && returnSet[1]['author'] === 'Abe Jones' && returnSet[2]['author'] === 'Kaitlyn Rose';
                    harness.assert_true(testPassed);
                }, "SELECT title FROM Books WHERE author LIKE %o%s%  => condition based on field not in SELECT");

                harness.test(function () {
                    // todo: special case when select is called empty?
                    var returnSet = db.select().distinct('author').from('Books').go(),
                        testPassed;
                    console.log('returnSet', returnSet);
                    testPassed = returnSet.length === 6 && returnSet[0]['author'] === 'Hank Aaron' && returnSet[1]['author'] === 'Abe Jones' && returnSet[2]['author'] === 'Bob Aaron';
                    harness.assert_true(testPassed);
                }, "SELECT DISTINCT author FROM Books WHERE author = 'Creepy Guy'");

                harness.test(function () {
                    db.update('Books').set('title', 'Green Eggs & Ham')('author', 'Dr. Seuss').where('title', '===', 'Bats').go();
                    query = db.select('title', 'author').from('Books').go();
                    harness.assert_true(query.length === 7 && query[4].title === 'Green Eggs & Ham' && query[4]['author'] === 'Dr. Seuss');
                }, "UPDATE Books SET title = 'Green Eggs & Ham', author = 'Dr. Seuss' WHERE title = 'Bats'");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', 'like', '.*break').and('author', 'like', '.*Aaron').go();
                    harness.assert_true(query[0].title === 'Coffee Break');
                }, "SELECT title FROM Books WHERE title like %break AND author like %Aaron");

                harness.test(function() {
                    query = db.select('title').from('Books').where('title', '===', 'Aliens').or('author', '===', 'Kaitlyn Rose').go();
                    harness.assert_true(query.length === 2 && query[0].title === 'Aliens' && query[1].title === 'Cats');
                }, "SELECT title FROM Books WHERE title = 'Aliens' OR author = 'Kaitlyn Rose'");

                harness.test(function() {
                    var d = db.delete().from('Books').where('author', '===', 'Hank Aaron').or('author', 'like', '.*ivy').go();
                    query = db.select('title', 'author').from('Books').where('author', '===', 'Hank Aaron').or('author', 'like', '.*ivy').go();
                    console.log('delete 1st and last title', Array.from(d.title));
                    console.log('delete 1st and last author', Array.from(d['author']));
                    harness.assert_true(query.length === 0);
                }, "DELETE FROM Books WHERE author === 'Hank Aaron' OR author like %ivy");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');
                db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')('Soup for the Soul', 'Flora Ivy');

                harness.test(function() {
                    var d = db.delete('author').from('Books').go();
                    query = db.select('author').from('Books').go();
                    console.log('delete author', Array.from(d['author']));
                    console.log('did not delete title', db.select('title').from('Books').go());
                    harness.assert_true(query.length === 0);
                }, "DELETE author FROM Books");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');
                db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')('Soup for the Soul', 'Flora Ivy');

                harness.test(function() {
                    var d = db.delete('*').from('Books').go();  // same as db.delete().from('Books').go();
                    var q1 = db.select('title').from('Books').go(),
                        q2 = db.select('author').from('Books').go();

                    console.log('delete title and author data from Books - Title', Array.from(d.title));
                    console.log('delete title and author data from Books - Author', Array.from(d.title));
                    harness.assert_true(q1.length === 0 && q2.length === 0);
                }, "DELETE * FROM Books => same as DELETE FROM Books");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author');
                db.insertInto('Books')('title', 'author').values('Baseball', 'Hank Aaron')('Alphabet Soup', 'Abe Jones')('Aliens', 'Corey Dorey')
                ('Coffee Break', 'Bob Aaron')('Bats', 'Creepy Guy')('Cats', 'Kaitlyn Rose')('Soup for the Soul', 'Flora Ivy');

                harness.test(function() {
                    db.alterTable('Books').add('pages');
                    query = db.select('pages').from('Books').go();
                    harness.assert_true(query.length === 7);
                }, "ALTER TABLE Books ADD pages");

                harness.test(function() {
                    db.alterTable('Books').drop('pages');
                    query = db.select('pages').from('Books').go();
                    console.log('table', table);
                    harness.assert_true(query.length === 0);
                }, "ALTER TABLE Books DROP pages");

                // tear-down & setup for next test
                db = squareDB.dropDB('Library');
                db = squareDB.createDB('Library');
                table = db.createTable('Books')('title', 'author', 'pages');
                db.insertInto('Books')('title', 'author', 'pages').values('Baseball', 'Hank Aaron', 90)('Alphabet Soup', 'Abe Jones', 540)('Aliens', 'Corey Dorey', 210)
                ('Coffee Break', 'Bob Aaron', 65)('Bats', 'Creepy Guy', 300)('Cats', 'Kaitlyn Rose', 829)('Soup for the Soul', 'Flora Ivy', 1200);

                harness.test(function() {
                    query = db.select().min('pages').from('Books').go();
                    harness.assert_true(query['pages'] === 65);
                }, "SELECT MIN('pages') FROM Books");

                harness.test(function() {
                    query = db.select().max('pages').from('Books').go();
                    harness.assert_true(query['pages'] === 1200);
                }, "SELECT MAX('pages') FROM Books");

                harness.test(function() {
                    query = db.select().sum('pages').from('Books').go();
                    harness.assert_true(query['pages'] === 3234);
                }, "SELECT SUM('pages') FROM Books");

                harness.test(function() {
                    query = db.select().avg('pages').from('Books').go();
                    harness.assert_true(query['pages'] === 462);
                }, "SELECT AVG('pages') FROM Books");

            }
        };
    }
);
<|endoftext|>