<commit_before>import Vue from 'vue'
import { parseFilters } from 'compiler/parser/filter-parser'

describe('Filters', () => {
  it('basic usage', () => {
    const vm = new Vue({
      template: '
{{ msg | upper }}
',
      data: {
        msg: 'hi'
      },
      filters: {
        upper: v => v.toUpperCase()
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('HI')
  })

  it('chained usage', () => {
    const vm = new Vue({
      template: '
{{ msg | upper | reverse }}
',
      data: {
        msg: 'hi'
      },
      filters: {
        upper: v => v.toUpperCase(),
        reverse: v => v.split('').reverse().join('')
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('IH')
  })

  it('in v-bind', () => {
    const vm = new Vue({
      template: `

      `,
      filters: {
        upper: v => v.toUpperCase(),
        reverse: v => v.split('').reverse().join(''),
        lower: v => v.toLowerCase()
      },
      data: {
        id: 'abc',
        cls: 'foo',
        ref: 'BAR'
      }
    }).$mount()
    expect(vm.$el.id).toBe('CBA')
    expect(vm.$el.className).toBe('oof')
    expect(vm.$refs.bar).toBe(vm.$el)
  })

  it('handle regex with pipe', () => {
    const vm = new Vue({
      template: `<test ref="test" :pattern="/a|b\\// | identity"></test>`,
      filters: { identity: v => v },
      components: {
        test: {
          props: ['pattern'],
          template: '

'
        }
      }
    }).$mount()
    expect(vm.$refs.test.pattern instanceof RegExp).toBe(true)
    expect(vm.$refs.test.pattern.toString()).toBe('/a|b\\//')
  })

  it('handle division', () => {
    const vm = new Vue({
      data: { a: 2 },
      template: `<div>{{ 1/a / 4 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(1 / 4))
  })

  it('handle division with parenthesis', () => {
    const vm = new Vue({
      data: { a: 20 },
      template: `<div>{{ (a*2) / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(16))
  })

  it('handle division with dot', () => {
    const vm = new Vue({
      template: `<div>{{ 20. / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('handle division with array values', () => {
    const vm = new Vue({
      data: { a: [20] },
      template: `<div>{{ a[0] / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('handle division with hash values', () => {
    const vm = new Vue({
      data: { a: { n: 20 }},
      template: `<div>{{ a['n'] / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('handle division with variable++', () => {
    const vm = new Vue({
      data: { a: 7 },
      template: `<div>{{ a++ / 2 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(7))
  })

  it('handle division with variable--', () => {
    const vm = new Vue({
      data: { a: 7 },
      template: `<div>{{ a++ / 2 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(7))
  })

  it('handle division with variable_', () => {
    const vm = new Vue({
      data: { a_: 8 },
      template: `<div>{{ a_ / 2 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('arguments', () => {
    const vm = new Vue({
      template: `<div>{{ msg | add(a, 3) }}</div>`,
      data: {
        msg: 1,
        a: 2
      },
      filters: {
        add: (v, arg1, arg2) => v + arg1 + arg2
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('6')
  })

  it('quotes', () => {
    const vm = new Vue({
      template: `<div>{{ msg + "b | c" + 'd' | upper }}</div>`,
      data: {
        msg: 'a'
      },
      filters: {
        upper: v => v.toUpperCase()
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('AB | CD')
  })

  it('double pipe', () => {
    const vm = new Vue({
      template: `<div>{{ b || msg | upper }}</div>`,
      data: {
        b: false,
        msg: 'a'
      },
      filters: {
        upper: v => v.toUpperCase()
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('A')
  })

  it('object literal', () => {
    const vm = new Vue({
      template: `<div>{{ { a: 123 } | pick('a') }}</div>`,
      filters: {
        pick: (v, key) => v[key]
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('123')
  })

  it('array literal', () => {
    const vm = new Vue({
      template: `<div>{{ [1, 2, 3] | reverse }}</div>`,
      filters: {
        reverse: arr => arr.reverse().join(',')
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('3,2,1')
  })

  it('warn non-existent', () => {
    new Vue({
      template: '
{{ msg | upper }}
',
      data: { msg: 'foo' }
    }).$mount()
    expect('Failed to resolve filter: upper').toHaveBeenWarned()
  })

  it('support template string', () => {
    expect(parseFilters('`a | ${b}c` | d')).toBe('_f("d")(`a | ${b}c`)')
  })
})
<commit_msg>chore(filter.spec): fix variable-- test case (#5094)<commit_after>import Vue from 'vue'
import { parseFilters } from 'compiler/parser/filter-parser'

describe('Filters', () => {
  it('basic usage', () => {
    const vm = new Vue({
      template: '
{{ msg | upper }}
',
      data: {
        msg: 'hi'
      },
      filters: {
        upper: v => v.toUpperCase()
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('HI')
  })

  it('chained usage', () => {
    const vm = new Vue({
      template: '
{{ msg | upper | reverse }}
',
      data: {
        msg: 'hi'
      },
      filters: {
        upper: v => v.toUpperCase(),
        reverse: v => v.split('').reverse().join('')
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('IH')
  })

  it('in v-bind', () => {
    const vm = new Vue({
      template: `

      `,
      filters: {
        upper: v => v.toUpperCase(),
        reverse: v => v.split('').reverse().join(''),
        lower: v => v.toLowerCase()
      },
      data: {
        id: 'abc',
        cls: 'foo',
        ref: 'BAR'
      }
    }).$mount()
    expect(vm.$el.id).toBe('CBA')
    expect(vm.$el.className).toBe('oof')
    expect(vm.$refs.bar).toBe(vm.$el)
  })

  it('handle regex with pipe', () => {
    const vm = new Vue({
      template: `<test ref="test" :pattern="/a|b\\// | identity"></test>`,
      filters: { identity: v => v },
      components: {
        test: {
          props: ['pattern'],
          template: '

'
        }
      }
    }).$mount()
    expect(vm.$refs.test.pattern instanceof RegExp).toBe(true)
    expect(vm.$refs.test.pattern.toString()).toBe('/a|b\\//')
  })

  it('handle division', () => {
    const vm = new Vue({
      data: { a: 2 },
      template: `<div>{{ 1/a / 4 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(1 / 4))
  })

  it('handle division with parenthesis', () => {
    const vm = new Vue({
      data: { a: 20 },
      template: `<div>{{ (a*2) / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(16))
  })

  it('handle division with dot', () => {
    const vm = new Vue({
      template: `<div>{{ 20. / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('handle division with array values', () => {
    const vm = new Vue({
      data: { a: [20] },
      template: `<div>{{ a[0] / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('handle division with hash values', () => {
    const vm = new Vue({
      data: { a: { n: 20 }},
      template: `<div>{{ a['n'] / 5 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('handle division with variable++', () => {
    const vm = new Vue({
      data: { a: 7 },
      template: `<div>{{ a++ / 2 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(7))
  })

  it('handle division with variable--', () => {
    const vm = new Vue({
      data: { a: 7 },
      template: `<div>{{ a-- / 2 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(7))
  })

  it('handle division with variable_', () => {
    const vm = new Vue({
      data: { a_: 8 },
      template: `<div>{{ a_ / 2 | double }}</div>`,
      filters: { double: v => v * 2 }
    }).$mount()
    expect(vm.$el.textContent).toBe(String(8))
  })

  it('arguments', () => {
    const vm = new Vue({
      template: `<div>{{ msg | add(a, 3) }}</div>`,
      data: {
        msg: 1,
        a: 2
      },
      filters: {
        add: (v, arg1, arg2) => v + arg1 + arg2
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('6')
  })

  it('quotes', () => {
    const vm = new Vue({
      template: `<div>{{ msg + "b | c" + 'd' | upper }}</div>`,
      data: {
        msg: 'a'
      },
      filters: {
        upper: v => v.toUpperCase()
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('AB | CD')
  })

  it('double pipe', () => {
    const vm = new Vue({
      template: `<div>{{ b || msg | upper }}</div>`,
      data: {
        b: false,
        msg: 'a'
      },
      filters: {
        upper: v => v.toUpperCase()
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('A')
  })

  it('object literal', () => {
    const vm = new Vue({
      template: `<div>{{ { a: 123 } | pick('a') }}</div>`,
      filters: {
        pick: (v, key) => v[key]
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('123')
  })

  it('array literal', () => {
    const vm = new Vue({
      template: `<div>{{ [1, 2, 3] | reverse }}</div>`,
      filters: {
        reverse: arr => arr.reverse().join(',')
      }
    }).$mount()
    expect(vm.$el.textContent).toBe('3,2,1')
  })

  it('warn non-existent', () => {
    new Vue({
      template: '
{{ msg | upper }}
',
      data: { msg: 'foo' }
    }).$mount()
    expect('Failed to resolve filter: upper').toHaveBeenWarned()
  })

  it('support template string', () => {
    expect(parseFilters('`a | ${b}c` | d')).toBe('_f("d")(`a | ${b}c`)')
  })
})
<|endoftext|>


<commit_before>(function (exports) {

  // -- Parse selectors
  var ps = function(selector){
    selector = selector || ''
    var cn = selector.split('.');
    var tag = false;
    if(selector[0] != '.') tag = cn[0];
    cn.splice(0, 1);
    var id = false;
    if(tag && tag[0] == '#') id = tag.split('#')[1];
    if(tag && id == '' && tag.indexOf('#') != -1){
      _tag = tag.split('#')
      tag = _tag[0]
      id = _tag[1]
    }
    if(id == '')
      for(var i = 0; i<cn.length;i++){
        var _id = cn[i].split('#')
        if(_id[1]){
          id = _id[1]
          cn[i] = _id[0]
          break;
        }
      }
    if(tag == '#'+id) tag = '';
    return {
      tag: tag,
      id: id,
      classList: cn
    }
  }

  // -- Query functions
  var qq = function(qs, root){
    if(root instanceof Array || root instanceof NodeList){
      var s = ps(qs);
      var arr = [].slice.call(root);
      var ret = [];
      for (var i = 0; i < arr.length; i++){
        is = true;
        if(arr[i] instanceof Element){
          if(s.tag && arr[i].tagName.toLowerCase()!=s.tag.toLowerCase()) is = false;
          if(s.id && arr[i].id != s.id) is = false;
          for (var j = 0; j < s.classList.length; j++)
            if(!arr[i].classList.contains(s.classList[j])) is = false;
          if(is) ret.push(arr[i]);
        }
      }
      return ret;
    }
    root = root instanceof Element ? root : document;
    if(qs instanceof Element) return [qs];
    if(qs instanceof NodeList || qs instanceof Array){
      var arr = [].slice.call(qs);
      var ret = [];
      for (var i = 0; i < arr.length; i++)
        if(arr[i] instanceof Element) ret.push(arr[i]);
      return ret;
    }
    var arr = [].slice.call(root.querySelectorAll(qs));
    var ret = [];
    for (var i = 0; i < arr.length; i++)
      if(arr[i] instanceof Element) ret.push(arr[i]);
    return ret;
  }
  var q = function(qs, root){
    return qq(qs, root)[0]||null;
  }
  Element.prototype.qq = function(qs){
    return qq(qs, this);
  }
  Element.prototype.q = function(qs){
    return q(qs, this);
  }

  //-- Create elements
  var e = function(selector){
    var s = ps(selector);
    var el = document.createElement(s.tag||'div');
    if(s.id) el.id = s.id;
    for (var i = 0; i < s.classList.length; i++)
      el.classList.add(s.classList[i]);
    return el;
  }
  var t = function(text){
    var e = document.createTextNode(text);
    return e;
  }
  Text.prototype.set = function (text) {
    this.nodeValue = text;
  }
  Text.prototype.get = function () {
    return this.nodeValue;
  }

  // -- Element actions
  Element.prototype.append = function (element) {
    this.appendChild(element);
  }
  Element.prototype.text = function (text) {
    if(!text) return this.textContent;
    if(text instanceof NodeList || text instanceof Array){
      var arr = [].slice.call(text);
      var _text = '';
      for (var i = 0; i < arr.length; i++){
        if(arr[i] instanceof Text) _text+= arr[i].get();
        else _text += arr[i].toString();
      }
      var e = t(_text);
      this.append(e);
      return e;
    }
    var nodes = this.childNodes;
    for (var i = 0; i < nodes.length; i++)
      nodes[i].remove();
    var e = t(text);
    this.append(e);
    return e;
  }
  Element.prototype.html = function (html) {
    if(!html) return this.innerHTML;
    var nodes = this.childNodes;
    for (var i = 0; i < nodes.length; i++)
      nodes[i].remove();
    if(html instanceof Element){
      this.append(html);
      return this.innerHTML;
    }
    if(html instanceof NodeList || html instanceof Array){
      var arr = [].slice.call(html);
      for (var i = 0; i < arr.length; i++)
        if(arr[i] instanceof Element || arr[i] instanceof Text)
          this.append(arr[i]);
      return this.innerHTML;
    }
    this.innerHTML = html;
    return this.innerHTML;
  }

  // -- Observe elements
  Element.prototype.observe = function () {
    var self = this;
    if(!this._observer){
      this._observerHandlers = []
      this._observer = new MutationObserver(function(mutations) {
        for (var i = 0; i < self._observerHandlers.length; i++) {
          for (var j = 0; j < mutations.length; j++) {
            var mutation = mutations[j];
            self._observerHandlers[i].call(self, mutation);
          }
        }
      });
      var config = {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true,
        attributeOldValue: true,
        characterDataOldValue: true
      }
      this._observer.observe(this, config);
    }
  }
  Element.prototype.stopObserving = function () {
    if(this._observer){
      this._observer.disconnect();
      delete this._observer;
    }
  }

  // -- Path
  Element.prototype.path = function (){
    var root = this;
    var path = [];
    while (root.parentNode){
      if (root.id != ''){
        path.unshift('#' + root.id);
        break;
      }
      if (root==root.ownerDocument.documentElement) path.unshift(root.tagName.toLowerCase());
      else{
        for (var i = 1, e = root; e.previousElementSibling; e = e.previousElementSibling, i++);
        path.unshift(root.tagName.toLowerCase() + ':nth-child(' + i + ')');
      }
      root=root.parentNode;
    }
    return path.join(' > ');
  }

  // -- Event
  EventTarget.prototype.on = function(event, next, capture){
    if(this._events == null) this._events = {};
    if(this._eventsInited == null) this._eventsInited = {};
    if(this._events[event] == null) this._events[event] = []
    this._events[event].push(next);
    if(this._eventsInited[event] !== true)
      this.addEventListener(event, function(ev){
        for(var i = 0; i < this._events[event].length; i++)
          this._events[event][i].call(this, ev);
      }, capture);
    this._eventsInited[event] = true
  };
  EventTarget.prototype.off = function(event, next, capture){
    if(this._events == null) this._events = {};;
    if(this._events[event] == null || next == null) this._events[event] = [];
    var index = this._events[event].indexOf(next);
    if(index != -1) this._events[event].splice(index, 1);
  };
  EventTarget.prototype.event = function(event){
    if(typeof event == 'string') return this.dispatchEvent(new Event(event));
    return this.dispatchEvent(event);
  };
  EventTarget.prototype.once = function(event, next, capture){
    var n = function(ev){
      next.call(self, ev);
      this.off(event, n, capture);
    }
    this.on(event, n, capture);
  };

  // -- Element events
  Element.prototype.on = function(event, next, capture){
    var _on = EventTarget.prototype.on;
    switch (event) {
      case 'mutation':
        this._observerHandlers.push(next);
        break;
      default:
        _on.apply(this, arguments);
      }
  }
  Element.prototype.off = function(event, next, capture){
    var _on = EventTarget.prototype.off;
    switch (event) {
      case 'mutation':
        var index = this._observerHandlers.indexOf(next);
        if(index != -1) this._observerHandlers.splice(index, 1);
        break;
      default:
        _off.apply(this, arguments);
      }
  }

  // -- Changing css
  Element.prototype.css = function(css, ignoreDefaults){
    if(typeof css === 'boolean') return this.css(null, css);
    if(typeof css === 'string') return this.css(null, ignoreDefaults)[css];
    if(!css){
      css = getComputedStyle(this);
      var ret = {};
      if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
        if(ignoreDefaults){
          var defaults = getComputedStyle(e(this.tagName));
          for (var k in css) {
            if (!css.hasOwnProperty(k) && isNaN(+k) && css[k] != '' && css[k] != defaults[k]) {
               ret[k] = css[k];
            }
          }
          return ret;
        }
        for (var k in css) {
          if (!css.hasOwnProperty(k) && isNaN(+k) && css[k] != '') {
             ret[k] = css[k];
          }
        }
      } else {
        if(ignoreDefaults){
          var defaults = getComputedStyle(e(this.tagName));
          for (var k in css) {
            if (css.hasOwnProperty(k) && isNaN(+k) && css[k] != '' && css[k] != defaults[k]) {
               ret[k] = css[k];
            }
          }
          return ret;
        }
        for (var k in css) {
          if (css.hasOwnProperty(k) && isNaN(+k) && css[k] != '') {
             ret[k] = css[k];
          }
        }
      }
      return ret;
    };
    var self = this;
    for (var _k in css) {
      if (css.hasOwnProperty(_k)) {
        self.style[_k] = css[_k]
      }
    }
  }

  exports.q = exports.query = q;
  exports.qq = exports.queryAll = qq;
  exports.ps = exports.parseSelectors = ps;
  exports.e = exports.element = e;
  exports.t = exports.text = t;

})(window);
<commit_msg>Changed `queryAll()` to `query.all()`<commit_after>(function (exports) {

  // -- Parse selectors
  var ps = function(selector){
    selector = selector || ''
    var cn = selector.split('.');
    var tag = false;
    if(selector[0] != '.') tag = cn[0];
    cn.splice(0, 1);
    var id = false;
    if(tag && tag[0] == '#') id = tag.split('#')[1];
    if(tag && id == '' && tag.indexOf('#') != -1){
      _tag = tag.split('#')
      tag = _tag[0]
      id = _tag[1]
    }
    if(id == '')
      for(var i = 0; i<cn.length;i++){
        var _id = cn[i].split('#')
        if(_id[1]){
          id = _id[1]
          cn[i] = _id[0]
          break;
        }
      }
    if(tag == '#'+id) tag = '';
    return {
      tag: tag,
      id: id,
      classList: cn
    }
  }

  // -- Query functions
  var qq = function(qs, root){
    if(root instanceof Array || root instanceof NodeList){
      var s = ps(qs);
      var arr = [].slice.call(root);
      var ret = [];
      for (var i = 0; i < arr.length; i++){
        is = true;
        if(arr[i] instanceof Element){
          if(s.tag && arr[i].tagName.toLowerCase()!=s.tag.toLowerCase()) is = false;
          if(s.id && arr[i].id != s.id) is = false;
          for (var j = 0; j < s.classList.length; j++)
            if(!arr[i].classList.contains(s.classList[j])) is = false;
          if(is) ret.push(arr[i]);
        }
      }
      return ret;
    }
    root = root instanceof Element ? root : document;
    if(qs instanceof Element) return [qs];
    if(qs instanceof NodeList || qs instanceof Array){
      var arr = [].slice.call(qs);
      var ret = [];
      for (var i = 0; i < arr.length; i++)
        if(arr[i] instanceof Element) ret.push(arr[i]);
      return ret;
    }
    var arr = [].slice.call(root.querySelectorAll(qs));
    var ret = [];
    for (var i = 0; i < arr.length; i++)
      if(arr[i] instanceof Element) ret.push(arr[i]);
    return ret;
  }
  var q = function(qs, root){
    return qq(qs, root)[0]||null;
  }
  q.all = qq;
  q.doc = document;
  q.body = q.doc.body;
  Element.prototype.q = Element.prototype.query = function(qs){
    return q(qs, this);
  }
  Element.prototype.qq = function(qs){
    return qq(qs, this);
  }

  //-- Create elements
  var e = function(selector){
    var s = ps(selector);
    var el = document.createElement(s.tag||'div');
    if(s.id) el.id = s.id;
    for (var i = 0; i < s.classList.length; i++)
      el.classList.add(s.classList[i]);
    return el;
  }
  var t = function(text){
    var e = document.createTextNode(text);
    return e;
  }
  Text.prototype.set = function (text) {
    this.nodeValue = text;
  }
  Text.prototype.get = function () {
    return this.nodeValue;
  }

  // -- Element actions
  Element.prototype.append = function (element) {
    this.appendChild(element);
  }
  Element.prototype.text = function (text) {
    if(!text) return this.textContent;
    if(text instanceof NodeList || text instanceof Array){
      var arr = [].slice.call(text);
      var _text = '';
      for (var i = 0; i < arr.length; i++){
        if(arr[i] instanceof Text) _text+= arr[i].get();
        else _text += arr[i].toString();
      }
      var e = t(_text);
      this.append(e);
      return e;
    }
    var nodes = this.childNodes;
    for (var i = 0; i < nodes.length; i++)
      nodes[i].remove();
    var e = t(text);
    this.append(e);
    return e;
  }
  Element.prototype.html = function (html) {
    if(!html) return this.innerHTML;
    var nodes = this.childNodes;
    for (var i = 0; i < nodes.length; i++)
      nodes[i].remove();
    if(html instanceof Element){
      this.append(html);
      return this.innerHTML;
    }
    if(html instanceof NodeList || html instanceof Array){
      var arr = [].slice.call(html);
      for (var i = 0; i < arr.length; i++)
        if(arr[i] instanceof Element || arr[i] instanceof Text)
          this.append(arr[i]);
      return this.innerHTML;
    }
    this.innerHTML = html;
    return this.innerHTML;
  }

  // -- Observe elements
  Element.prototype.observe = function () {
    var self = this;
    if(!this._observer){
      this._observerHandlers = []
      this._observer = new MutationObserver(function(mutations) {
        for (var i = 0; i < self._observerHandlers.length; i++) {
          for (var j = 0; j < mutations.length; j++) {
            var mutation = mutations[j];
            self._observerHandlers[i].call(self, mutation);
          }
        }
      });
      var config = {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true,
        attributeOldValue: true,
        characterDataOldValue: true
      }
      this._observer.observe(this, config);
    }
  }
  Element.prototype.stopObserving = function () {
    if(this._observer){
      this._observer.disconnect();
      delete this._observer;
    }
  }

  // -- Path
  Element.prototype.path = function (){
    var root = this;
    var path = [];
    while (root.parentNode){
      if (root.id != ''){
        path.unshift('#' + root.id);
        break;
      }
      if (root==root.ownerDocument.documentElement) path.unshift(root.tagName.toLowerCase());
      else{
        for (var i = 1, e = root; e.previousElementSibling; e = e.previousElementSibling, i++);
        path.unshift(root.tagName.toLowerCase() + ':nth-child(' + i + ')');
      }
      root=root.parentNode;
    }
    return path.join(' > ');
  }

  // -- Event
  EventTarget.prototype.on = function(event, next, capture){
    if(this._events == null) this._events = {};
    if(this._eventsInited == null) this._eventsInited = {};
    if(this._events[event] == null) this._events[event] = []
    this._events[event].push(next);
    if(this._eventsInited[event] !== true)
      this.addEventListener(event, function(ev){
        for(var i = 0; i < this._events[event].length; i++)
          this._events[event][i].call(this, ev);
      }, capture);
    this._eventsInited[event] = true
  };
  EventTarget.prototype.off = function(event, next, capture){
    if(this._events == null) this._events = {};;
    if(this._events[event] == null || next == null) this._events[event] = [];
    var index = this._events[event].indexOf(next);
    if(index != -1) this._events[event].splice(index, 1);
  };
  EventTarget.prototype.event = function(event){
    if(typeof event == 'string') return this.dispatchEvent(new Event(event));
    return this.dispatchEvent(event);
  };
  EventTarget.prototype.once = function(event, next, capture){
    var n = function(ev){
      next.call(self, ev);
      this.off(event, n, capture);
    }
    this.on(event, n, capture);
  };

  // -- Element events
  Element.prototype.on = function(event, next, capture){
    var _on = EventTarget.prototype.on;
    switch (event) {
      case 'mutation':
        this._observerHandlers.push(next);
        break;
      default:
        _on.apply(this, arguments);
      }
  }
  Element.prototype.off = function(event, next, capture){
    var _on = EventTarget.prototype.off;
    switch (event) {
      case 'mutation':
        var index = this._observerHandlers.indexOf(next);
        if(index != -1) this._observerHandlers.splice(index, 1);
        break;
      default:
        _off.apply(this, arguments);
      }
  }

  // -- Changing css
  Element.prototype.css = function(css, ignoreDefaults){
    if(typeof css === 'boolean') return this.css(null, css);
    if(typeof css === 'string') return this.css(null, ignoreDefaults)[css];
    if(!css){
      css = getComputedStyle(this);
      var ret = {};
      if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
        if(ignoreDefaults){
          var defaults = getComputedStyle(e(this.tagName));
          for (var k in css) {
            if (!css.hasOwnProperty(k) && isNaN(+k) && css[k] != '' && css[k] != defaults[k]) {
               ret[k] = css[k];
            }
          }
          return ret;
        }
        for (var k in css) {
          if (!css.hasOwnProperty(k) && isNaN(+k) && css[k] != '') {
             ret[k] = css[k];
          }
        }
      } else {
        if(ignoreDefaults){
          var defaults = getComputedStyle(e(this.tagName));
          for (var k in css) {
            if (css.hasOwnProperty(k) && isNaN(+k) && css[k] != '' && css[k] != defaults[k]) {
               ret[k] = css[k];
            }
          }
          return ret;
        }
        for (var k in css) {
          if (css.hasOwnProperty(k) && isNaN(+k) && css[k] != '') {
             ret[k] = css[k];
          }
        }
      }
      return ret;
    };
    var self = this;
    for (var _k in css) {
      if (css.hasOwnProperty(_k)) {
        self.style[_k] = css[_k]
      }
    }
  }

  exports.q = exports.query = q;
  exports.qq = qq;
  exports.ps = exports.parseSelectors = ps;
  exports.e = exports.element = e;
  exports.t = exports.text = t;

})(window);
<|endoftext|>


<commit_before>/*
waitMe - 1.07 [11.02.15]
Author: vadimsva
Github: https://github.com/vadimsva/waitMe
*/
(function(g){g.fn.waitMe=function(h){return this.each(function(){var f=g(this),u,n,c,p=!1,m="background-color",k="",l="",q,d,b,e,r,t={init:function(){e=g.extend({effect:"bounce",text:"",bg:"rgba(255,255,255,0.7)",color:"#000",sizeW:"",sizeH:"",source:""},h);r=(new Date).getMilliseconds();q=g('

');var a="width:"+e.sizeW+";height:"+e.sizeH;switch(e.effect){case "none":c=0;break;case "bounce":c=3;d="";b=a;break;case "rotateplane":c=1;d="";b=a;break;case "stretch":c=
5;d="";b=a;break;case "orbit":c=2;d=a;b="";break;case "roundBounce":c=12;d=a;b="";break;case "win8":c=5;p=!0;b=d=a;break;case "win8_linear":c=5;p=!0;d=a;b="";break;case "ios":c=12;d=a;b="";break;case "facebook":c=3;d="";b=a;break;case "rotation":c=1;m="border-color";d="";b=a;break;case "timer":c=2;k="border-color:"+e.color;d=a;b="";break;case "pulse":c=1;m="border-color";d="";b=a;break;case "progressBar":c=1;d="";b=a;break;case "bouncePulse":c=3;d="";b=a;break;case "img":c=1,d="",b=a}""==e.sizeW&&
""==e.sizeH&&(d=b="");""!=d&&""!=k&&(k=";"+k);if(0<c){n=g('

');if("img"==e.effect)l='';else for(a=1;a<=c;++a)l=p?l+('

'):l+('

');n=g('
'+l+"
")}e.text&&(u=g('
'+e.text+"
"));f.find("> .waitMe")&&f.find("> .waitMe").remove();waitMeDivObj=g('

');waitMeDivObj.append(n,u);q.append(waitMeDivObj);"HTML"==f[0].tagName&&(f=g("body"));f.addClass("waitMe_container").attr("data-waitme_id",r).append(q);f.find("> .waitMe").css({background:e.bg});f.find(".waitMe_content").css({marginTop:-f.find(".waitMe_content").outerHeight()/2+"px"})},hide:function(){var a=f.attr("data-waitme_id");f.removeClass("waitMe_container").removeAttr("data-waitme_id");
f.find('.waitMe[data-waitme_id="'+a+'"]').remove()}};if(t[h])return t[h].apply(this,Array.prototype.slice.call(arguments,1));if("object"===typeof h||!h)return t.init.apply(this,arguments);g.event.special.destroyed={remove:function(a){a.handler&&a.handler()}}})}})(jQuery);
<commit_msg>20.02.15<commit_after>/*
waitMe - 1.08 [20.02.15]
Author: vadimsva
Github: https://github.com/vadimsva/waitMe
*/
(function(f){f.fn.waitMe=function(h){return this.each(function(){var g=f(this),u,n,c,p=!1,m="background-color",k="",l="",q,d,b,e,r,t={init:function(){e=f.extend({effect:"bounce",text:"",bg:"rgba(255,255,255,0.7)",color:"#000",sizeW:"",sizeH:"",source:""},h);r=(new Date).getMilliseconds();q=f('

');var a="width:"+e.sizeW+";height:"+e.sizeH;switch(e.effect){case "none":c=0;break;case "bounce":c=3;d="";b=a;break;case "rotateplane":c=1;d="";b=a;break;case "stretch":c=
5;d="";b=a;break;case "orbit":c=2;d=a;b="";break;case "roundBounce":c=12;d=a;b="";break;case "win8":c=5;p=!0;b=d=a;break;case "win8_linear":c=5;p=!0;d=a;b="";break;case "ios":c=12;d=a;b="";break;case "facebook":c=3;d="";b=a;break;case "rotation":c=1;m="border-color";d="";b=a;break;case "timer":c=2;k="border-color:"+e.color;d=a;b="";break;case "pulse":c=1;m="border-color";d="";b=a;break;case "progressBar":c=1;d="";b=a;break;case "bouncePulse":c=3;d="";b=a;break;case "img":c=1,d="",b=a}""==e.sizeW&&
""==e.sizeH&&(d=b="");""!=d&&""!=k&&(k=";"+k);if(0<c){n=f('

');if("img"==e.effect)l='';else for(a=1;a<=c;++a)l=p?l+('

'):l+('

');n=f('
'+l+"
")}e.text&&(u=f('
'+e.text+"
"));g.find("> .waitMe")&&g.find("> .waitMe").remove();waitMeDivObj=f('

');waitMeDivObj.append(n,u);q.append(waitMeDivObj);"HTML"==g[0].tagName&&(g=f("body"));g.addClass("waitMe_container").attr("data-waitme_id",r).append(q);g.find("> .waitMe").css({background:e.bg});g.find(".waitMe_content").css({marginTop:-g.find(".waitMe_content").outerHeight()/2+"px"})},hide:function(){var a=g.attr("data-waitme_id");g.removeClass("waitMe_container").removeAttr("data-waitme_id");
g.find('.waitMe[data-waitme_id="'+a+'"]').remove()}};if(t[h])return t[h].apply(this,Array.prototype.slice.call(arguments,1));if("object"===typeof h||!h)return t.init.apply(this,arguments);f.event.special.destroyed={remove:function(a){a.handler&&a.handler()}}})};f(window).load(function(){f("body.waitMe_body").find(".waitMe_container").remove();f("body.waitMe_body").removeClass("waitMe_body")})})(jQuery);
<|endoftext|>


<commit_before>/**
 * @module sqlite
 * @author Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {Boolean} [config.log=false]
 */
exports.config = _.extend({
	log: false,
}, Alloy.CFG.T ? Alloy.CFG.T.sqlite : {});

var Util = require('T/util');

var MODULE_NAME = 'sqlite';

var DatabaseModule = require('T/db');

function SQLite(name, file) {
	this.query = null;
	this.name = name;
	this.db = null;

	// Install the database from a file if needed, and close it immediately.
	if (file != null) {
		this.db = DatabaseModule.install(file, name);

		this.close();
	}
}

/**
 * Returns a new instance of SQLite opened from a file identified by the path argument.
 * @method fromFile
 * @static
 * @param  {String} path
 * @return {SQLite}
 */
SQLite.fromFile = function(path) {
	var file = Ti.Filesystem.getFile(path);
	var name = file.name.replace(/\..+$/, '');

	var destination_file = Ti.Filesystem.getFile(Util.getDatabaseDirectory() + '/' + name + '.sql');

	if (destination_file.exists()) destination_file.deleteFile();
	destination_file.write(file);

	// I know, this functions seems a bit an hack, but the API is inconsistent:
	// On iOS, open doesn't recognize a path, so we have to copy the SQL file in the exact location, then pass the name.
	// On Android, it simply works with open + file, but we have to copy to external storage if present.

	if (OS_IOS) {
		return new SQLite(name);
	} else if (OS_ANDROID) {
		return new SQLite(destination_file);
	}
};

/**
 * Start a chain to query informations
 * @method table
 * @param  {String} name The table name
 * @return {SQLite}
 */
SQLite.prototype.table = function(name) {
	this.query = {
		method: 'select',
		table: name,
		where: [],
		whereData: [],
		select: null,
		update: null,
		updateData: [],
		order: null,
		insert: null,
		insertData: []
	};
	return this;
};

/**
 * Select attributes
 * @method select
 * @return {SQLite}
 */
SQLite.prototype.select = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.method = 'select';

	var args = _.toArray(arguments);
	if (args.length === 0) {

		/*
		.select()
		*/
		this.query.select = null;

	} else if (args.length > 1) {

		/*
		.select('id', 'title', 'order')
		*/
		this.query.select = _.object(args, args);

	} else {

		if (_.isArray(args[0])) {

			/*
			.select(['id', 'title', 'order'])
			*/
			this.query.select = _.object(args[0], args[0]);

		} else if (_.isObject(args[0])) {

			/*
			.select({
				"_alias": "alias",
				"_id": "id"
			})
			*/
			this.query.select = args[0];

		} else {

			/*
			.select('id')
			*/
			this.query.select = _.object([args[0]], [args[0]]);

		}

	}

	return this;
};

/**
 * Update attributes.
 * @method update
 * @param  {Object} obj
 * @return {SQLite}
 */
SQLite.prototype.update = function(obj) {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	/*
	.update({
		value: 2,
		other_value: 3
	})
	*/
	this.query.method = 'update';
	this.query.update = _.keys(obj);
	this.query.updateData = _.values(obj);

	return this;
};

/**
 * Perform a delete table.
 * @method delete
 * @return {SQLite}
 */
SQLite.prototype.delete = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.method = 'delete';

	return this;
};

/**
 * Order the results in the select.
 * @method order
 * @alias orderBy
 * @return {SQLite}
 */
SQLite.prototype.order = SQLite.prototype.orderBy = function(key, direction) {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.order = {
		key: key,
		direction: direction || 'ASC'
	};

	return this;
};

/**
 * Perform a truncate table.
 * @method truncate
 * @return {SQLite}
 */
SQLite.prototype.truncate = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.method = 'truncate';

	return this;
};

/**
 * Add where clauses.
 * @method where
 * @alias andWhere
 * @return {SQLite}
 */
SQLite.prototype.where = SQLite.prototype.andWhere = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	var args = _.toArray(arguments);
	if (args.length === 1) {

		/*
		.where({
			id: 2,
			id_sub: 3
		})
		*/
		if (_.isObject(args[0])) {
			this.query.where = _.map(_.keys(args[0]), function(k) { return k + ' = ?'; });
			this.query.whereData = _.values(args[0]);
		} else if (_.isString(args[0])) {
			this.query.where.push(args[0]);
		}

	} else if (args.length === 2) {

		/*
		.where('id', 2)
		*/
		this.query.where.push(args[0] + ' = ?');
		this.query.whereData.push(args[1]);

	} else if (args.length === 3) {

		/*
		.where('string', 'LIKE', 'test')
		*/
		this.query.where.push(args[0] + ' ' + args[1] + ' ?');
		this.query.whereData.push(args[2]);

	}

	return this;
};

/**
 * Insert values
 * @method insert
 * @return {SQLite}
 */
SQLite.prototype.insert = function(obj) {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	/*
	.insert({
		value: 2,
		other_value: 3
	})
	*/
	this.query.method = 'insert';
	this.query.insert = _.keys(obj);
	this.query.insertData = _.values(obj);

	return this;
};

/**
 * Returns the query to pass to native module
 * @method getExequery
 * @return {Array}
 */
SQLite.prototype.getExequery = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	var whereClause = (this.query.where.length > 0 ? (' WHERE ' + this.query.where.join(' AND ')) : '');
	switch (this.query.method) {

		case 'select':
		return [
			'SELECT ' + (this.query.select === null ? '*' : _.map(this.query.select, function(v, k){ return k + ' AS ' + v; }).join(',')) +
			' FROM [' + this.query.table + ']' +
			whereClause +
			(this.query.order === null ? '' : (' ORDER BY ' + this.query.order.key + ' ' + this.query.order.direction))
		]
		.concat(this.query.whereData);

		case 'update':
		return [
			'UPDATE [' + this.query.table + ']' +
			' SET ' + (this.query.update.join(' = ?, ') + ' = ?') +
			whereClause
		]
		.concat(this.query.updateData)
		.concat(this.query.whereData);

		case 'delete':
		return [
			'DELETE FROM [' + this.query.table + ']' +
			whereClause
		]
		.concat(this.query.whereData);

		case 'truncate':
		return [
			'TRUNCATE TABLE [' + this.query.table + ']'
		];

		case 'insert':
		return [
			'INSERT INTO [' + this.query.table + ']' +
			'(' + this.query.insert.join(',') + ') ' +
			'VALUES (' + this.query.insert.map(function(){ return '?'; }) + ')'
		]
		.concat(this.query.insertData);

	}
};

/**
 * Open the database.
 * Important: ALWAYS close the database after you are done with it.
 * @method open
 */
SQLite.prototype.open = function() {
	try {
		this.db = DatabaseModule.open(this.name);
	} catch (ex) {
		Ti.API.error(MODULE_NAME + ': Error while opening the database: ' + ex);
	}
};

/**
 * Close the database
 * @method close
 */
SQLite.prototype.close = function() {
	try {
		this.db.close();
	} catch (ex) {
		Ti.API.error(MODULE_NAME + ': Error while closing the database: ' + ex);
	}
};

/**
 * Executes a query.
 * Important: this method differs from SQLite.run() for the fact that it leaves the database open, and returns the result of the call to DatabaseModule.DB.execute().
 * @method execute
 * @alias exec
 * @param {String} query
 * @param {Vararg} values
 * @return {DatabaseModule.ResultSet}
 */
SQLite.prototype.execute = SQLite.prototype.exec = function() {
	Ti.API.warn(MODULE_NAME + ': WARNING: if you use .execute(), you will have to close the result set and the database manually!');

	var q = null;

	if (this.query === null) {
		q = arguments;
	} else {
		q = this.getExequery();
		this.query = null; // Reset query
	}

	if (exports.config.log) Ti.API.debug(MODULE_NAME + ':', q);

	this.open();
	return Function.prototype.apply.call(this.db.execute, this.db, q);
};

/**
 * Execute a query and apply a transformation function to the result set, then close the set and the database.
 * @param {String} [query]
 * @param {Vararg} [values]
 * @param {Function} fn The transformation function to apply to the dataset. It will be passed a `dataset` argument, which is an instance of DatabaseModule.ResultSet, and it should return the transformed result.
 * @return The result of fn
 */
SQLite.prototype.transform = function() {
	var _arguments = _.toArray(arguments);
	var transform = _arguments.pop();
	if (!_.isFunction(transform)) {
		throw new Error('SQLite: last argument of SQLite.transform must be a Function');
	}

	var q = null;

	if (this.query === null) {
		q = _arguments;
	} else {
		q = this.getExequery();
		this.query = null; // Reset query
	}

	if (exports.config.log) Ti.API.debug(MODULE_NAME + ':', q);

	this.open();
	var dataset = Function.prototype.apply.call(this.db.execute, this.db, q);

	var res = transform(dataset);

	dataset.close();
	this.close();

	return res;
};

/**
 * Run a query chain. Also accepts a query string.
 * @method run
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.run = function() {
	this.open();

	var q = null;

	if (this.query === null) {
		q = arguments;
	} else {
		q = this.getExequery();
		this.query = null; // Reset query
	}

	if (exports.config.log) Ti.API.debug(MODULE_NAME + ':', arguments);

	var row = Function.prototype.apply.call(this.db.execute, this.db, q);

	if (row != null) {
		row.close();
	}

	this.close();
};

/**
 * Returns a single value
 * @method value
 * @alias val
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.value = SQLite.prototype.val = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		if (!row || row.isValidRow() === false) return null;

		return row.field(0);
	});

	return this.transform.apply(this, _args);
};

/**
 * Returns a single object (row)
 * @method single
 * @alias row
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.single = SQLite.prototype.row = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		if (!row || row.isValidRow() === false) return null;

		var obj = {};
		for (var i = 0; i < row.fieldCount; i++) {
			obj[row.fieldName(i)] = row.field(i);
		}

		return obj;
	});

	return this.transform.apply(this, _args);
};

/**
 * Returns a list of single values
 * @method list
 * @alias array
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.list = SQLite.prototype.array = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		var list = [];
		while (row && row.isValidRow() === true) {
			list.push(row.field(0));
			row.next();
		}
		return list;
	});

	return this.transform.apply(this, _args);
};

/**
 * Returns a list of objects (row)
 * @method all
 * @alias rows
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.all = SQLite.prototype.rows = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		var list = [];
		var fieldNames = [];
		while (row && row.isValidRow() === true) {
			var obj = {};
			for (var i = 0; i < row.fieldCount; i++) {
				fieldNames[i] = fieldNames[i] || row.fieldName(i);
				obj[fieldNames[i]] = row.field(i);
			}
			list.push(obj);
			row.next();
		}
		return list;
	});

	return this.transform.apply(this, _args);
};

/**
 * Loop over query
 * @method loop
 * @param {String} [query]
 * @param {Vararg} [values]
 * @param {Function} fn The function to loop over the query result
 */
SQLite.prototype.loop = function() {
	var _args = _.toArray(arguments);
	var loopFn = _args.pop();
	if (!_.isFunction(loopFn)) {
		throw new Error('SQLite: last argument of SQLite.loop must be a Function');
	}

	this.transform.apply(this, _args.concat(function(row) {
		var fieldNames = [];
		while (row && row.isValidRow() === true) {
			var obj = {};
			for (var i = 0; i < row.fieldCount; i++) {
				fieldNames[i] = fieldNames[i] || row.fieldName(i);
				obj[fieldNames[i]] = row.field(i);
			}
			loopFn(obj);
			row.next();
		}
	}));
};

module.exports = SQLite;
<commit_msg>Fixed minor bug in sqlite<commit_after>/**
 * @module sqlite
 * @author Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {Boolean} [config.log=false]
 */
exports.config = _.extend({
	log: false,
}, Alloy.CFG.T ? Alloy.CFG.T.sqlite : {});

var Util = require('T/util');

var MODULE_NAME = 'sqlite';

var DatabaseModule = require('T/db');

function SQLite(name, file) {
	this.query = null;
	this.name = name;
	this.db = null;

	// Install the database from a file if needed, and close it immediately.
	if (file != null) {
		this.db = DatabaseModule.install(file, name);

		this.close();
	}
}

/**
 * Returns a new instance of SQLite opened from a file identified by the path argument.
 * @method fromFile
 * @static
 * @param  {String} path
 * @return {SQLite}
 */
SQLite.fromFile = function(path) {
	var file = Ti.Filesystem.getFile(path);
	var name = file.name.replace(/\..+$/, '');

	var destination_file = Ti.Filesystem.getFile(Util.getDatabaseDirectory() + '/' + name + '.sql');

	if (destination_file.exists()) destination_file.deleteFile();
	destination_file.write(file);

	// I know, this functions seems a bit an hack, but the API is inconsistent:
	// On iOS, open doesn't recognize a path, so we have to copy the SQL file in the exact location, then pass the name.
	// On Android, it simply works with open + file, but we have to copy to external storage if present.

	if (OS_IOS) {
		return new SQLite(name);
	} else if (OS_ANDROID) {
		return new SQLite(destination_file);
	}
};

/**
 * Start a chain to query informations
 * @method table
 * @param  {String} name The table name
 * @return {SQLite}
 */
SQLite.prototype.table = function(name) {
	this.query = {
		method: 'select',
		table: name,
		where: [],
		whereData: [],
		select: null,
		update: null,
		updateData: [],
		order: null,
		insert: null,
		insertData: []
	};
	return this;
};

/**
 * Select attributes
 * @method select
 * @return {SQLite}
 */
SQLite.prototype.select = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.method = 'select';

	var args = _.toArray(arguments);
	if (args.length === 0) {

		/*
		.select()
		*/
		this.query.select = null;

	} else if (args.length > 1) {

		/*
		.select('id', 'title', 'order')
		*/
		this.query.select = _.object(args, args);

	} else {

		if (_.isArray(args[0])) {

			/*
			.select(['id', 'title', 'order'])
			*/
			this.query.select = _.object(args[0], args[0]);

		} else if (_.isObject(args[0])) {

			/*
			.select({
				"_alias": "alias",
				"_id": "id"
			})
			*/
			this.query.select = args[0];

		} else {

			/*
			.select('id')
			*/
			this.query.select = _.object([args[0]], [args[0]]);

		}

	}

	return this;
};

/**
 * Update attributes.
 * @method update
 * @param  {Object} obj
 * @return {SQLite}
 */
SQLite.prototype.update = function(obj) {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	/*
	.update({
		value: 2,
		other_value: 3
	})
	*/
	this.query.method = 'update';
	this.query.update = _.keys(obj);
	this.query.updateData = _.values(obj);

	return this;
};

/**
 * Perform a delete table.
 * @method delete
 * @return {SQLite}
 */
SQLite.prototype.delete = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.method = 'delete';

	return this;
};

/**
 * Order the results in the select.
 * @method order
 * @alias orderBy
 * @return {SQLite}
 */
SQLite.prototype.order = SQLite.prototype.orderBy = function(key, direction) {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.order = {
		key: key,
		direction: direction || 'ASC'
	};

	return this;
};

/**
 * Perform a truncate table.
 * @method truncate
 * @return {SQLite}
 */
SQLite.prototype.truncate = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	this.query.method = 'truncate';

	return this;
};

/**
 * Add where clauses.
 * @method where
 * @alias andWhere
 * @return {SQLite}
 */
SQLite.prototype.where = SQLite.prototype.andWhere = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	var args = _.toArray(arguments);
	if (args.length === 1) {

		/*
		.where({
			id: 2,
			id_sub: 3
		})
		*/
		if (_.isObject(args[0])) {
			this.query.where = _.map(_.keys(args[0]), function(k) { return k + ' = ?'; });
			this.query.whereData = _.values(args[0]);
		} else if (_.isString(args[0])) {
			this.query.where.push(args[0]);
		}

	} else if (args.length === 2) {

		/*
		.where('id', 2)
		*/
		this.query.where.push(args[0] + ' = ?');
		this.query.whereData.push(args[1]);

	} else if (args.length === 3) {

		/*
		.where('string', 'LIKE', 'test')
		*/
		this.query.where.push(args[0] + ' ' + args[1] + ' ?');
		this.query.whereData.push(args[2]);

	}

	return this;
};

/**
 * Insert values
 * @method insert
 * @return {SQLite}
 */
SQLite.prototype.insert = function(obj) {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	/*
	.insert({
		value: 2,
		other_value: 3
	})
	*/
	this.query.method = 'insert';
	this.query.insert = _.keys(obj);
	this.query.insertData = _.values(obj);

	return this;
};

/**
 * Returns the query to pass to native module
 * @method getExequery
 * @return {Array}
 */
SQLite.prototype.getExequery = function() {
	if (this.query === null) throw new Error('Start a query chain with .table() method');

	var whereClause = (this.query.where.length > 0 ? (' WHERE ' + this.query.where.join(' AND ')) : '');
	switch (this.query.method) {

		case 'select':
		return [
			'SELECT ' + (this.query.select === null ? '*' : _.map(this.query.select, function(v, k){ return k + ' AS ' + v; }).join(',')) +
			' FROM [' + this.query.table + ']' +
			whereClause +
			(this.query.order === null ? '' : (' ORDER BY ' + this.query.order.key + ' ' + this.query.order.direction))
		]
		.concat(this.query.whereData);

		case 'update':
		return [
			'UPDATE [' + this.query.table + ']' +
			' SET ' + (this.query.update.join(' = ?, ') + ' = ?') +
			whereClause
		]
		.concat(this.query.updateData)
		.concat(this.query.whereData);

		case 'delete':
		return [
			'DELETE FROM [' + this.query.table + ']' +
			whereClause
		]
		.concat(this.query.whereData);

		case 'truncate':
		return [
			'TRUNCATE TABLE [' + this.query.table + ']'
		];

		case 'insert':
		return [
			'INSERT INTO [' + this.query.table + ']' +
			'(' + this.query.insert.join(',') + ') ' +
			'VALUES (' + this.query.insert.map(function(){ return '?'; }) + ')'
		]
		.concat(this.query.insertData);

	}
};

/**
 * Open the database.
 * Important: ALWAYS close the database after you are done with it.
 * @method open
 */
SQLite.prototype.open = function() {
	try {
		this.db = DatabaseModule.open(this.name);
	} catch (ex) {
		Ti.API.error(MODULE_NAME + ': Error while opening the database: ' + ex);
	}
};

/**
 * Close the database
 * @method close
 */
SQLite.prototype.close = function() {
	try {
		this.db.close();
	} catch (ex) {
		Ti.API.error(MODULE_NAME + ': Error while closing the database: ' + ex);
	}
};

/**
 * Executes a query.
 * Important: this method differs from SQLite.run() for the fact that it leaves the database open, and returns the result of the call to DatabaseModule.DB.execute().
 * @method execute
 * @alias exec
 * @param {String} query
 * @param {Vararg} values
 * @return {DatabaseModule.ResultSet}
 */
SQLite.prototype.execute = SQLite.prototype.exec = function() {
	Ti.API.warn(MODULE_NAME + ': WARNING: if you use .execute(), you will have to close the result set and the database manually!');

	var q = null;

	if (this.query === null) {
		q = arguments;
	} else {
		q = this.getExequery();
		this.query = null; // Reset query
	}

	if (exports.config.log) Ti.API.debug(MODULE_NAME + ':', q);

	this.open();
	return Function.prototype.apply.call(this.db.execute, this.db, q);
};

/**
 * Execute a query and apply a transformation function to the result set, then close the set and the database.
 * @param {String} [query]
 * @param {Vararg} [values]
 * @param {Function} fn The transformation function to apply to the dataset. It will be passed a `dataset` argument, which is an instance of DatabaseModule.ResultSet, and it should return the transformed result.
 * @return The result of fn
 */
SQLite.prototype.transform = function() {
	var _arguments = _.toArray(arguments);
	var transform = _arguments.pop();
	if (!_.isFunction(transform)) {
		throw new Error('SQLite: last argument of SQLite.transform must be a Function');
	}

	var q = null;

	if (this.query === null) {
		q = _arguments;
	} else {
		q = this.getExequery();
		this.query = null; // Reset query
	}

	if (exports.config.log) Ti.API.debug(MODULE_NAME + ':', q);

	this.open();
	var dataset = Function.prototype.apply.call(this.db.execute, this.db, q);

	var res = transform(dataset);

	if (dataset) dataset.close();
	this.close();

	return res;
};

/**
 * Run a query chain. Also accepts a query string.
 * @method run
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.run = function() {
	this.open();

	var q = null;

	if (this.query === null) {
		q = arguments;
	} else {
		q = this.getExequery();
		this.query = null; // Reset query
	}

	if (exports.config.log) Ti.API.debug(MODULE_NAME + ':', arguments);

	var row = Function.prototype.apply.call(this.db.execute, this.db, q);

	if (row != null) {
		row.close();
	}

	this.close();
};

/**
 * Returns a single value
 * @method value
 * @alias val
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.value = SQLite.prototype.val = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		if (!row || row.isValidRow() === false) return null;

		return row.field(0);
	});

	return this.transform.apply(this, _args);
};

/**
 * Returns a single object (row)
 * @method single
 * @alias row
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.single = SQLite.prototype.row = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		if (!row || row.isValidRow() === false) return null;

		var obj = {};
		for (var i = 0; i < row.fieldCount; i++) {
			obj[row.fieldName(i)] = row.field(i);
		}

		return obj;
	});

	return this.transform.apply(this, _args);
};

/**
 * Returns a list of single values
 * @method list
 * @alias array
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.list = SQLite.prototype.array = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		var list = [];
		while (row && row.isValidRow() === true) {
			list.push(row.field(0));
			row.next();
		}
		return list;
	});

	return this.transform.apply(this, _args);
};

/**
 * Returns a list of objects (row)
 * @method all
 * @alias rows
 * @param {String} query
 * @param {Vararg} values
 */
SQLite.prototype.all = SQLite.prototype.rows = function() {
	var _args = _.toArray(arguments);
	_args.push(function(row) {
		var list = [];
		var fieldNames = [];
		while (row && row.isValidRow() === true) {
			var obj = {};
			for (var i = 0; i < row.fieldCount; i++) {
				fieldNames[i] = fieldNames[i] || row.fieldName(i);
				obj[fieldNames[i]] = row.field(i);
			}
			list.push(obj);
			row.next();
		}
		return list;
	});

	return this.transform.apply(this, _args);
};

/**
 * Loop over query
 * @method loop
 * @param {String} [query]
 * @param {Vararg} [values]
 * @param {Function} fn The function to loop over the query result
 */
SQLite.prototype.loop = function() {
	var _args = _.toArray(arguments);
	var loopFn = _args.pop();
	if (!_.isFunction(loopFn)) {
		throw new Error('SQLite: last argument of SQLite.loop must be a Function');
	}

	this.transform.apply(this, _args.concat(function(row) {
		var fieldNames = [];
		while (row && row.isValidRow() === true) {
			var obj = {};
			for (var i = 0; i < row.fieldCount; i++) {
				fieldNames[i] = fieldNames[i] || row.fieldName(i);
				obj[fieldNames[i]] = row.field(i);
			}
			loopFn(obj);
			row.next();
		}
	}));
};

module.exports = SQLite;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var child_process = require('child_process'),
	program = require('commander'),
	watch = require('node-watch'),
	chalk = require('chalk'),
	_ = require('lodash');

var exec = child_process.exec,
	spawn = child_process.spawn;

// Configure CLI parameters.
require('pkginfo')(module);
program
  .version(module.exports.version)
  .description(module.exports.description)
  .option('-c, --command [cmd]', 'command to run, and to restart when files change')
  .option('-w, --watch [path]', 'directory or file to watch for changes')
  .parse(process.argv);

// Start process and listen for shutdown event.
var child;
var start = function () {
	child = exec(program.command);
	child.stdout.pipe(process.stdout);
	child.stderr.pipe(process.stderr);
	child.on('close', function (code, signal) {
		if (code !== 8) {
			console.log(chalk.bgRed(' Process has died. Waiting for changes to restart. '));
		}
	});
}

// Listen for file changes and, when they occur, restart process.
watch(program.watch, _.debounce(function(path) {
	console.log(chalk.green(' → Change detected on "%s". Restarting process.'), path);
	child.kill();
  start();
}, 1000));

// Initialize.
start();
console.log(chalk.black.bgGreen(' Watching %s/ for changes. '), program.watch);
<commit_msg>change text color on red bg<commit_after>#!/usr/bin/env node

var child_process = require('child_process'),
	program = require('commander'),
	watch = require('node-watch'),
	chalk = require('chalk'),
	_ = require('lodash');

var exec = child_process.exec,
	spawn = child_process.spawn;

// Configure CLI parameters.
require('pkginfo')(module);
program
  .version(module.exports.version)
  .description(module.exports.description)
  .option('-c, --command [cmd]', 'command to run, and to restart when files change')
  .option('-w, --watch [path]', 'directory or file to watch for changes')
  .parse(process.argv);

// Start process and listen for shutdown event.
var child;
var start = function () {
	child = exec(program.command);
	child.stdout.pipe(process.stdout);
	child.stderr.pipe(process.stderr);
	child.on('close', function (code, signal) {
		if (code !== 8) {
			console.log(chalk.black.bgRed(' Process has died. Waiting for changes to restart. '));
		}
	});
}

// Listen for file changes and, when they occur, restart process.
watch(program.watch, _.debounce(function(path) {
	console.log(chalk.green(' → Change detected on "%s". Restarting process.'), path);
	child.kill();
  start();
}, 1000));

// Initialize.
start();
console.log(chalk.black.bgGreen(' Watching %s/ for changes. '), program.watch);
<|endoftext|>


<commit_before>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};

// Global variables
Alloy.Globals.APPID = "9999SWEDENTEST";
Alloy.Globals.FACEBOOKOBJECT;
Alloy.Globals.FACEBOOK;
Alloy.Globals.CHALLENGEOBJECTARRAY = [];
Alloy.Globals.BETKAMPENUID = 0;
Alloy.Globals.CHALLENGEINDEX;
Alloy.Globals.LEAGUES;
Alloy.Globals.AVAILABLELANGUAGES;
Alloy.Globals.SLIDERZINDEX = 1;
Alloy.Globals.TIMEOUT = 30000;
Alloy.Globals.CURRENTVIEW;
Alloy.Globals.PREVIOUSVIEW;
Alloy.Globals.NAV = null;
Alloy.Globals.MAINVIEW;
Alloy.Globals.MAINWIN = null;
Alloy.Globals.LANDINGWIN = null;
Alloy.Globals.WINDOWS = [];
Alloy.Globals.OPEN = true;
Alloy.Globals.CLOSE = true;
Alloy.Globals.FBERROR = true;
Alloy.Globals.PHRASES = {};
Alloy.Globals.TiBeacon = null;
Alloy.Globals.AcceptedBeacon1 = false;
Alloy.Globals.AcceptedBeacon2 = false;
Alloy.Globals.AcceptedBeacon3 = false;

//initialize beacons
if(OS_IOS){
	Alloy.Globals.TiBeacon = require('org.beuckman.tibeacons');
}else if(OS_ANDROID){
	Alloy.Globals.TiBeacon = require('miga.tibeacon');
}

// try to get stored language
var lang = JSON.parse(Ti.App.Properties.getString('language'));

if(typeof lang == 'undefined' || lang == '' || lang == null) {
	Alloy.Globals.LOCALE = Titanium.Locale.getCurrentLanguage().toLowerCase();
} else {
	lang = lang.language;
	Alloy.Globals.LOCALE = lang;
}

// urls. Everything live needs to be done over SSL
Alloy.Globals.INVITEURL = 'https://apps.facebook.com/betkampen';
Alloy.Globals.BETKAMPENURL = 'http://secure.jimdavislabs.se/secure/betkampen_vm';
Alloy.Globals.BETKAMPENLOGINURL = Alloy.Globals.BETKAMPENURL + '/api/login.php';
Alloy.Globals.BETKAMPENCHALLENGESURL = Alloy.Globals.BETKAMPENURL + '/api/challenges_v2.php';
Alloy.Globals.BETKAMPENUSERURL = Alloy.Globals.BETKAMPENURL + '/api/user_stats.php'; //
Alloy.Globals.BETKAMPENGAMESURL = Alloy.Globals.BETKAMPENURL + '/api/get_challenge_game.php';
Alloy.Globals.BETKAMPENANSWERURL = Alloy.Globals.BETKAMPENURL + '/api/answer_challenge.php';
Alloy.Globals.BETKAMPENGETGAMESURL = Alloy.Globals.BETKAMPENURL + '/api/get_available_games.php';
Alloy.Globals.BETKAMPENGETGAMESFORCHALLENGEURL = Alloy.Globals.BETKAMPENURL + '/api/get_game_and_types_for_challenge.php';
Alloy.Globals.BETKAMPENGETGAMESFORTOURNAMENT = Alloy.Globals.BETKAMPENURL + '/api/get_tournament_game.php';
Alloy.Globals.BETKAMPENGETGROUPSURL = Alloy.Globals.BETKAMPENURL + '/api/get_groups.php';
Alloy.Globals.BETKAMPENCHALLENGEDONEURL = Alloy.Globals.BETKAMPENURL + '/api/challenge_done.php';
Alloy.Globals.BETKAMPENDEVICETOKENURL = Alloy.Globals.BETKAMPENURL + '/api/store_device_token.php';
Alloy.Globals.BETKAMPENCOINSURL = Alloy.Globals.BETKAMPENURL + '/api/get_coins.php';
Alloy.Globals.BETKAMPENCHECKCOINSURL = Alloy.Globals.BETKAMPENURL + '/api/check_coins.php';
Alloy.Globals.BETKAMPENCOINSANDROIDURL = Alloy.Globals.BETKAMPENURL + '/api/get_coins_android.php';
Alloy.Globals.BETKAMPENSHAREURL = Alloy.Globals.BETKAMPENURL + '/api/share.php';
Alloy.Globals.GETLANGUAGE = Alloy.Globals.BETKAMPENURL + '/api/get_language.php';
Alloy.Globals.BETKAMPENACHIEVEMENTSURL = Alloy.Globals.BETKAMPENURL + '/api/get_achievements.php';
Alloy.Globals.BETKAMPENEMAILLOGIN = Alloy.Globals.BETKAMPENURL + '/api/email_login.php'; //Email login
Alloy.Globals.BETKAMPENEMAILREG = Alloy.Globals.BETKAMPENURL + '/api/email_registration.php'; //Email registration
Alloy.Globals.BETKAMPENGETMOTDINFO = Alloy.Globals.BETKAMPENURL + '/api/get_match_day_info.php'; //matchens mästare
Alloy.Globals.BETKAMPENGETTICKETS = Alloy.Globals.BETKAMPENURL + '/api/get_user_tickets.php';
Alloy.Globals.BETKAMPENSETTINGURL = Alloy.Globals.BETKAMPENURL + '/api/settings.php';
Alloy.Globals.BETKAMPENIMAGEUPLOADURL = Alloy.Globals.BETKAMPENURL + '/api/image_upload.php';
Alloy.Globals.BETKAMPENGETFRIENDSURL = Alloy.Globals.BETKAMPENURL + '/api/get_friends.php';
Alloy.Globals.BETKAMPENGETGETBEACONSURL = Alloy.Globals.BETKAMPENURL + '/api/get_beacons.php';
Alloy.Globals.BETKAMPENGETPROMOTIONURL = Alloy.Globals.BETKAMPENURL + '/api/get_promotion.php';

Alloy.Globals.performTimeout = function(func) {
	if (OS_ANDROID) {
		setTimeout(function() { func;
		}, 300);
	} else { func;
	}

};

Alloy.Globals.themeColor = function() {
	var theme = 2;
	switch(theme) {
		case 1:
			return '#58B101';
		case 2:
			return '#ea7337';
	}
};

Alloy.Globals.getFont = function() {
	if (OS_IOS) {
		return 'Helvetica Neue';
	} else if (OS_ANDROID) {
		return 'Roboto-Regular';
	}
};

Alloy.Globals.getFontSize = function(target) {
	var font;

	if (OS_IOS) {
		if (target === 1) {
			// normal
			font = 16;
		} else if (target === 2) {
			// section
			font = 22;
		} else if (target === 3) {
			// header
			font = 44;
		}
		return font;
	} else if (OS_ANDROID) {
		if (target === 1) {
			// normal
			font = 18;
		} else if (target === 2) {
			// section
			font = 24;
		} else if (target === 3) {
			// header
			font = 48;
		}
		return font;
	}
};

// show feedback dialog
Alloy.Globals.showFeedbackDialog = function(msg) {
	var alertWindow = Titanium.UI.createAlertDialog({
		title : Alloy.Globals.PHRASES.betbattleTxt,
		message : msg,
		buttonNames : [Alloy.Globals.PHRASES.okConfirmTxt]
	});

	alertWindow.addEventListener('click', function(e) {
		switch (e.index) {
			case 0:
				alertWindow.hide();
				break;
		}
	});
	alertWindow.show();
};

// check network
Alloy.Globals.checkConnection = function() {
	return Titanium.Network.online;
};

// post device token to our backend
Alloy.Globals.postDeviceToken = function(deviceToken) {
	// check connection
	if (Alloy.Globals.checkConnection()) {
		var xhr = Titanium.Network.createHTTPClient();
		xhr.onerror = function(e) {
			Ti.API.error('Bad Sever =>' + e.error);
		};

		try {
			xhr.open('POST', Alloy.Globals.BETKAMPENDEVICETOKENURL);
			xhr.setRequestHeader("content-type", "application/json");
			xhr.setRequestHeader("Authorization", Alloy.Globals.FACEBOOK.accessToken);
			xhr.setTimeout(Alloy.Globals.TIMEOUT);

			// build the json string
			var param = '{"device_token":"' + deviceToken + '", "device_type":"' + Ti.Platform.osname + '", "lang":"' + Alloy.Globals.LOCALE +'"}';

			xhr.send(param);
		} catch(e) {
			//
		}

		xhr.onload = function() {
			if (this.status == '200') {
				if (this.readyState == 4) {
					var response = '';
					try {
						response = JSON.parse(this.responseText);
					} catch(e) {

					}

					Ti.API.log(response);
				} else {
					Ti.API.log(this.response);
				}
			} else {
				Ti.API.error("Error =>" + this.response);
			}
		};
	} else {
		Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.noConnectionErrorTxt);
	}
};

// check coins for user
Alloy.Globals.checkCoins = function() {
	// check connection
	if (Alloy.Globals.checkConnection()) {
		var xhr = Titanium.Network.createHTTPClient();
		xhr.onerror = function(e) {
			Ti.API.error('Bad Sever =>' + e.error);
		};

		try {
			xhr.open('POST', Alloy.Globals.BETKAMPENCHECKCOINSURL + '?uid=' + Alloy.Globals.BETKAMPENUID + '&lang=' + Alloy.Globals.LOCALE);
			xhr.setRequestHeader("content-type", "application/json");
			xhr.setRequestHeader("Authorization", Alloy.Globals.FACEBOOK.accessToken);
			xhr.setTimeout(Alloy.Globals.TIMEOUT);

			xhr.send();
		} catch(e) {
			//
		}

		xhr.onload = function() {
			if (this.status == '200') {
				if (this.readyState == 4) {
					var coins = null;
					try {
						coins = JSON.parse(this.responseText);
						coins = parseInt(coins);
					} catch (e) {
						coins = null;
					}
					if (coins !== null) {
						if (coins <= 0) {
							var alertWindow = Titanium.UI.createAlertDialog({
								title : Alloy.Globals.PHRASES.betbattleTxt,
								message : Alloy.Globals.PHRASES.noCoinsErrorTxt,
								buttonNames : [Alloy.Globals.PHRASES.okConfirmTxt, Alloy.Globals.PHRASES.storeTxt]
							});

							alertWindow.addEventListener('click', function(e) {
								switch (e.index) {
									case 0:
										alertWindow.hide();
										break;
									case 1:
										var win = Alloy.createController('store').getView();

										if (OS_IOS) {
											Alloy.Globals.NAV.openWindow(win, {
												animated : true
											});
										} else {
											win.open({
												fullscreen : false
											});
											win = null;
										}

										alertWindow.hide();
										break;
								}
							});
							alertWindow.show();
						}
					}

				}
			} else {
				Ti.API.error("Error =>" + this.response);
			}
		};
	}
};

// construct Challenge objects
Alloy.Globals.constructChallenge = function(responseAPI) {
	// 3 arrays will be returned from server, one for each type: accept, pending, finished
	// for each challenge object returned create a challenge object and store in array
	var finalArray = [];

	for (var c = 0; c < responseAPI.length; c++) {

		response = responseAPI[c];
		var array = [];

		for (var i = 0; i < response.length; i++) {

			// get opponents for each challenge
			var cOpponents = [];
			for (var x = 0; x < response[i].opponents.length; x++) {
				// build object
				var opponent = {
					fbid : response[i].opponents[x].fbid,
					name : response[i].opponents[x].name,
					status : response[i].opponents[x].status
				};
				// store in array
				cOpponents.push(opponent);
			}

			// get winner/winners for each challenge
			var cWinners = [];
			for (var z = 0; z < response[i].winners.length; z++) {
				// build object
				var winner = {
					fbid : response[i].winners[z].fbid,
					name : response[i].winners[z].name,
					uid : response[i].winners[z].uid
				};
				cWinners.push(winner);
			}

			if (c == 3 || c == 4) {
				// handle tournaments
				var challenge = Alloy.createModel('challenge', {
					id : response[i].id,
					name : response[i].t_name,
					time : response[i].game_date,
					opponents : cOpponents,
					winners : cWinners,
					group : response[i].group,
					league : response[i].league_id,
					round : response[i].rnd,
					opponentCount : response[i].count_opps,
					tournamentPot : response[i].pot,
					show : response[i].show
				});

			} else {
				// handle normal challenge's
				var challenge = Alloy.createModel('challenge', {
					id : response[i].c_id,
					name : response[i].c_name,
					fbid : response[i].c_fbid,
					time : response[i].c_time,
					status : response[i].status,
					opponents : cOpponents,
					pot : response[i].pot,
					potential_pot : response[i].potential_pot,
					winners : cWinners,
					group : response[i].group,
					league : response[i].league,
					round : response[i].round,
					show : response[i].show
				});
			}

			array.push(challenge);
		}
		finalArray.push(array);
	}

	return finalArray;
};

<commit_msg>ny länk i alloy.js<commit_after>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};

// Global variables
Alloy.Globals.APPID = "9999SWEDENTEST";
Alloy.Globals.FACEBOOKOBJECT;
Alloy.Globals.FACEBOOK;
Alloy.Globals.CHALLENGEOBJECTARRAY = [];
Alloy.Globals.BETKAMPENUID = 0;
Alloy.Globals.CHALLENGEINDEX;
Alloy.Globals.LEAGUES;
Alloy.Globals.AVAILABLELANGUAGES;
Alloy.Globals.SLIDERZINDEX = 1;
Alloy.Globals.TIMEOUT = 30000;
Alloy.Globals.CURRENTVIEW;
Alloy.Globals.PREVIOUSVIEW;
Alloy.Globals.NAV = null;
Alloy.Globals.MAINVIEW;
Alloy.Globals.MAINWIN = null;
Alloy.Globals.LANDINGWIN = null;
Alloy.Globals.WINDOWS = [];
Alloy.Globals.OPEN = true;
Alloy.Globals.CLOSE = true;
Alloy.Globals.FBERROR = true;
Alloy.Globals.PHRASES = {};
Alloy.Globals.TiBeacon = null;
Alloy.Globals.AcceptedBeacon1 = false;
Alloy.Globals.AcceptedBeacon2 = false;
Alloy.Globals.AcceptedBeacon3 = false;

//initialize beacons
if(OS_IOS){
	Alloy.Globals.TiBeacon = require('org.beuckman.tibeacons');
}else if(OS_ANDROID){
	Alloy.Globals.TiBeacon = require('miga.tibeacon');
}

// try to get stored language
var lang = JSON.parse(Ti.App.Properties.getString('language'));

if(typeof lang == 'undefined' || lang == '' || lang == null) {
	Alloy.Globals.LOCALE = Titanium.Locale.getCurrentLanguage().toLowerCase();
} else {
	lang = lang.language;
	Alloy.Globals.LOCALE = lang;
}

// urls. Everything live needs to be done over SSL
Alloy.Globals.INVITEURL = 'https://apps.facebook.com/betkampen';
Alloy.Globals.BETKAMPENURL = 'http://secure.jimdavislabs.se/secure/betkampen_vm';
Alloy.Globals.BETKAMPENLOGINURL = Alloy.Globals.BETKAMPENURL + '/api/login.php';
Alloy.Globals.BETKAMPENCHALLENGESURL = Alloy.Globals.BETKAMPENURL + '/api/challenges_v2.php';
Alloy.Globals.BETKAMPENUSERURL = Alloy.Globals.BETKAMPENURL + '/api/user_stats.php'; //
Alloy.Globals.BETKAMPENGAMESURL = Alloy.Globals.BETKAMPENURL + '/api/get_challenge_game.php';
Alloy.Globals.BETKAMPENANSWERURL = Alloy.Globals.BETKAMPENURL + '/api/answer_challenge.php';
Alloy.Globals.BETKAMPENGETGAMESURL = Alloy.Globals.BETKAMPENURL + '/api/get_available_games.php';
Alloy.Globals.BETKAMPENGETGAMESFORCHALLENGEURL = Alloy.Globals.BETKAMPENURL + '/api/get_game_and_types_for_challenge.php';
Alloy.Globals.BETKAMPENGETGAMESFORTOURNAMENT = Alloy.Globals.BETKAMPENURL + '/api/get_tournament_game.php';
Alloy.Globals.BETKAMPENGETGROUPSURL = Alloy.Globals.BETKAMPENURL + '/api/get_groups.php';
Alloy.Globals.BETKAMPENCHALLENGEDONEURL = Alloy.Globals.BETKAMPENURL + '/api/challenge_done.php';
Alloy.Globals.BETKAMPENDEVICETOKENURL = Alloy.Globals.BETKAMPENURL + '/api/store_device_token.php';
Alloy.Globals.BETKAMPENCOINSURL = Alloy.Globals.BETKAMPENURL + '/api/get_coins.php';
Alloy.Globals.BETKAMPENCHECKCOINSURL = Alloy.Globals.BETKAMPENURL + '/api/check_coins.php';
Alloy.Globals.BETKAMPENCOINSANDROIDURL = Alloy.Globals.BETKAMPENURL + '/api/get_coins_android.php';
Alloy.Globals.BETKAMPENSHAREURL = Alloy.Globals.BETKAMPENURL + '/api/share.php';
Alloy.Globals.GETLANGUAGE = Alloy.Globals.BETKAMPENURL + '/api/get_language.php';
Alloy.Globals.BETKAMPENACHIEVEMENTSURL = Alloy.Globals.BETKAMPENURL + '/api/get_achievements.php';
Alloy.Globals.BETKAMPENEMAILLOGIN = Alloy.Globals.BETKAMPENURL + '/api/email_login.php'; //Email login
Alloy.Globals.BETKAMPENEMAILREG = Alloy.Globals.BETKAMPENURL + '/api/email_registration.php'; //Email registration
Alloy.Globals.BETKAMPENGETMOTDINFO = Alloy.Globals.BETKAMPENURL + '/api/get_match_day_info.php'; //matchens mästare
Alloy.Globals.BETKAMPENGETTICKETS = Alloy.Globals.BETKAMPENURL + '/api/get_user_tickets.php';
Alloy.Globals.BETKAMPENSETTINGURL = Alloy.Globals.BETKAMPENURL + '/api/settings.php';
Alloy.Globals.BETKAMPENIMAGEUPLOADURL = Alloy.Globals.BETKAMPENURL + '/api/image_upload.php';
Alloy.Globals.BETKAMPENGETFRIENDSURL = Alloy.Globals.BETKAMPENURL + '/api/get_friends.php';
Alloy.Globals.BETKAMPENGETGETBEACONSURL = Alloy.Globals.BETKAMPENURL + '/api/get_beacons.php';
Alloy.Globals.BETKAMPENGETPROMOTIONURL = Alloy.Globals.BETKAMPENURL + '/api/get_promotion.php';
Alloy.Globals.BETKAMPENCHALLENGESHOWURL = Alloy.Globals.BETKAMPENURL + '/api/show_challenge.php';

Alloy.Globals.performTimeout = function(func) {
	if (OS_ANDROID) {
		setTimeout(function() { func;
		}, 300);
	} else { func;
	}

};

Alloy.Globals.themeColor = function() {
	var theme = 2;
	switch(theme) {
		case 1:
			return '#58B101';
		case 2:
			return '#ea7337';
	}
};

Alloy.Globals.getFont = function() {
	if (OS_IOS) {
		return 'Helvetica Neue';
	} else if (OS_ANDROID) {
		return 'Roboto-Regular';
	}
};

Alloy.Globals.getFontSize = function(target) {
	var font;

	if (OS_IOS) {
		if (target === 1) {
			// normal
			font = 16;
		} else if (target === 2) {
			// section
			font = 22;
		} else if (target === 3) {
			// header
			font = 44;
		}
		return font;
	} else if (OS_ANDROID) {
		if (target === 1) {
			// normal
			font = 18;
		} else if (target === 2) {
			// section
			font = 24;
		} else if (target === 3) {
			// header
			font = 48;
		}
		return font;
	}
};

// show feedback dialog
Alloy.Globals.showFeedbackDialog = function(msg) {
	var alertWindow = Titanium.UI.createAlertDialog({
		title : Alloy.Globals.PHRASES.betbattleTxt,
		message : msg,
		buttonNames : [Alloy.Globals.PHRASES.okConfirmTxt]
	});

	alertWindow.addEventListener('click', function(e) {
		switch (e.index) {
			case 0:
				alertWindow.hide();
				break;
		}
	});
	alertWindow.show();
};

// check network
Alloy.Globals.checkConnection = function() {
	return Titanium.Network.online;
};

// post device token to our backend
Alloy.Globals.postDeviceToken = function(deviceToken) {
	// check connection
	if (Alloy.Globals.checkConnection()) {
		var xhr = Titanium.Network.createHTTPClient();
		xhr.onerror = function(e) {
			Ti.API.error('Bad Sever =>' + e.error);
		};

		try {
			xhr.open('POST', Alloy.Globals.BETKAMPENDEVICETOKENURL);
			xhr.setRequestHeader("content-type", "application/json");
			xhr.setRequestHeader("Authorization", Alloy.Globals.FACEBOOK.accessToken);
			xhr.setTimeout(Alloy.Globals.TIMEOUT);

			// build the json string
			var param = '{"device_token":"' + deviceToken + '", "device_type":"' + Ti.Platform.osname + '", "lang":"' + Alloy.Globals.LOCALE +'"}';

			xhr.send(param);
		} catch(e) {
			//
		}

		xhr.onload = function() {
			if (this.status == '200') {
				if (this.readyState == 4) {
					var response = '';
					try {
						response = JSON.parse(this.responseText);
					} catch(e) {

					}

					Ti.API.log(response);
				} else {
					Ti.API.log(this.response);
				}
			} else {
				Ti.API.error("Error =>" + this.response);
			}
		};
	} else {
		Alloy.Globals.showFeedbackDialog(Alloy.Globals.PHRASES.noConnectionErrorTxt);
	}
};

// check coins for user
Alloy.Globals.checkCoins = function() {
	// check connection
	if (Alloy.Globals.checkConnection()) {
		var xhr = Titanium.Network.createHTTPClient();
		xhr.onerror = function(e) {
			Ti.API.error('Bad Sever =>' + e.error);
		};

		try {
			xhr.open('POST', Alloy.Globals.BETKAMPENCHECKCOINSURL + '?uid=' + Alloy.Globals.BETKAMPENUID + '&lang=' + Alloy.Globals.LOCALE);
			xhr.setRequestHeader("content-type", "application/json");
			xhr.setRequestHeader("Authorization", Alloy.Globals.FACEBOOK.accessToken);
			xhr.setTimeout(Alloy.Globals.TIMEOUT);

			xhr.send();
		} catch(e) {
			//
		}

		xhr.onload = function() {
			if (this.status == '200') {
				if (this.readyState == 4) {
					var coins = null;
					try {
						coins = JSON.parse(this.responseText);
						coins = parseInt(coins);
					} catch (e) {
						coins = null;
					}
					if (coins !== null) {
						if (coins <= 0) {
							var alertWindow = Titanium.UI.createAlertDialog({
								title : Alloy.Globals.PHRASES.betbattleTxt,
								message : Alloy.Globals.PHRASES.noCoinsErrorTxt,
								buttonNames : [Alloy.Globals.PHRASES.okConfirmTxt, Alloy.Globals.PHRASES.storeTxt]
							});

							alertWindow.addEventListener('click', function(e) {
								switch (e.index) {
									case 0:
										alertWindow.hide();
										break;
									case 1:
										var win = Alloy.createController('store').getView();

										if (OS_IOS) {
											Alloy.Globals.NAV.openWindow(win, {
												animated : true
											});
										} else {
											win.open({
												fullscreen : false
											});
											win = null;
										}

										alertWindow.hide();
										break;
								}
							});
							alertWindow.show();
						}
					}

				}
			} else {
				Ti.API.error("Error =>" + this.response);
			}
		};
	}
};

// construct Challenge objects
Alloy.Globals.constructChallenge = function(responseAPI) {
	// 3 arrays will be returned from server, one for each type: accept, pending, finished
	// for each challenge object returned create a challenge object and store in array
	var finalArray = [];

	for (var c = 0; c < responseAPI.length; c++) {

		response = responseAPI[c];
		var array = [];

		for (var i = 0; i < response.length; i++) {

			// get opponents for each challenge
			var cOpponents = [];
			for (var x = 0; x < response[i].opponents.length; x++) {
				// build object
				var opponent = {
					fbid : response[i].opponents[x].fbid,
					name : response[i].opponents[x].name,
					status : response[i].opponents[x].status
				};
				// store in array
				cOpponents.push(opponent);
			}

			// get winner/winners for each challenge
			var cWinners = [];
			for (var z = 0; z < response[i].winners.length; z++) {
				// build object
				var winner = {
					fbid : response[i].winners[z].fbid,
					name : response[i].winners[z].name,
					uid : response[i].winners[z].uid
				};
				cWinners.push(winner);
			}

			if (c == 3 || c == 4) {
				// handle tournaments
				var challenge = Alloy.createModel('challenge', {
					id : response[i].id,
					name : response[i].t_name,
					time : response[i].game_date,
					opponents : cOpponents,
					winners : cWinners,
					group : response[i].group,
					league : response[i].league_id,
					round : response[i].rnd,
					opponentCount : response[i].count_opps,
					tournamentPot : response[i].pot,
					show : response[i].show
				});

			} else {
				// handle normal challenge's
				var challenge = Alloy.createModel('challenge', {
					id : response[i].c_id,
					name : response[i].c_name,
					fbid : response[i].c_fbid,
					time : response[i].c_time,
					status : response[i].status,
					opponents : cOpponents,
					pot : response[i].pot,
					potential_pot : response[i].potential_pot,
					winners : cWinners,
					group : response[i].group,
					league : response[i].league,
					round : response[i].round,
					show : response[i].show
				});
			}

			array.push(challenge);
		}
		finalArray.push(array);
	}

	return finalArray;
};

<|endoftext|>


<commit_before>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};
Alloy.Globals.Map = require('ti.map');
<commit_msg>AlloyのGlobal.xxにFacebookモジュール読み込むように設定ファイルを変更<commit_after>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};
Alloy.Globals.Map = require('ti.map');
Alloy.Globals.Facebook = require('facebook');
<|endoftext|>


<commit_before>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};

var API = require('api');
var getValueFromXml = function(xml, parent,child){
	var parentNode =  xml.getElementsByTagName(parent).item(0);
	var childNode = parentNode.getElementsByTagName(child).item(0).textContent;
	return childNode;
};

var getValueFromPipe = function(xml){
	var res = getValueFromXml(xml, 'HTML' , 'BODY');
	var data = res.split("||");
 	var obj = {};

	if(data[1] == "S:"){
		for(var i=2; i <= data.length; i++){
			if(i != data.length){
				var inner = data[i].split(":");
		       	if(inner[0] !== ""){

		       		//fixed key space
		       		var inner_key = inner[0].replace(" ", "");

		       		var val_inner = inner[1];

		       		//fixed for time format
		       		if(inner.length > 2){
		       			val_inner = inner[1] +":"+inner[2] +":"+inner[3];
		       		}

		       		obj[inner_key] = val_inner.trim();
		       	}

	    	}
		}

	}
	return obj;
};
<commit_msg>support "R:" from Pipe result<commit_after>// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};

var API = require('api');
var getValueFromXml = function(xml, parent,child){
	var parentNode =  xml.getElementsByTagName(parent).item(0);
	var childNode = parentNode.getElementsByTagName(child).item(0).textContent;
	return childNode;
};

var getValueFromPipe = function(xml){
	var res = getValueFromXml(xml, 'HTML' , 'BODY');
	var data = res.split("||");
 	var obj = {};

	if(data[1] == "S:" || data[1] == "R:"){
		for(var i=2; i <= data.length; i++){
			if(i != data.length){
				var inner = data[i].split(":");
		       	if(inner[0] !== ""){

		       		//fixed key space
		       		var inner_key = inner[0].replace(" ", "");

		       		var val_inner = inner[1];

		       		//fixed for time format
		       		if(inner.length > 2){
		       			val_inner = inner[1] +":"+inner[2] +":"+inner[3];
		       		}

		       		obj[inner_key] = val_inner.trim();
		       	}

	    	}
		}

	}
	return obj;
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 Sankarsan Kampa
 *                    https://sankarsankampa.com/contact
 *
 * This file is a part of Bastion Discord BOT.
 *                        https://github.com/snkrsnkampa/Bastion
 *
 * This code is licensed under the SNKRSN Shared License. It is free to
 * download, copy, compile, use, study and refer under the terms of the
 * SNKRSN Shared License. You can modify the code only for personal or
 * internal use only. However, you can not redistribute the code without
 * explicitly getting permission fot it.
 *
 * Bastion BOT is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY. See the SNKRSN Shared License for
 * more details.
 *
 * You should have received a copy of the SNKRSN Shared License along
 * with this program. If not, see <https://github.com/snkrsnkampa/Bastion/LICENSE>.
 */

const sql = require('sqlite');
sql.open('./data/Bastion.sqlite');

exports.run = (Bastion, message, args) => {
  if (!message.member.hasPermission('ADMINISTRATOR')) return Bastion.log.info('User doesn\'t have permission to use this command.');
  if (args.length < 1) {
    sql.get(`SELECT greetDMMessage FROM guildSettings WHERE guildID=${message.guild.id}`).then(guild => {
      message.channel.send({embed: {
        color: Bastion.colors.dark_grey,
        title: 'DM Greeting message:',
        description: guild.greetDMMessage
      }}).catch(e => {
        Bastion.log.error(e.stack);
      });
    }).catch(e => {
      Bastion.log.error(e.stack);
    });
  }
  else {
    sql.run(`UPDATE guildSettings SET greetDMMessage="${args.join(' ').replace(/"/g, '\'')}" WHERE guildID=${message.guild.id}`).catch(e => {
      Bastion.log.error(e.stack);
    });

    message.channel.send({embed: {
      color: Bastion.colors.green,
      title: 'DM Greeting message set to:',
      description: args.join(' ')
    }}).catch(e => {
      Bastion.log.error(e.stack);
    });
  }
};

exports.config = {
  aliases: ['gmsg'],
  enabled: true
};

exports.help = {
  name: 'greetdmmessage',
  description: 'Edit the greeting message that is sent as direct message when a new member is joined in the server.',
  botPermission: '',
  userPermission: 'Administrator',
  usage: 'greetDMMessage [Message]',
  example: ['greetDMMessage Hello $user! Welcome to $server.']
};
<commit_msg>Fixed prefix of greetdmmessage<commit_after>/*
 * Copyright (C) 2017 Sankarsan Kampa
 *                    https://sankarsankampa.com/contact
 *
 * This file is a part of Bastion Discord BOT.
 *                        https://github.com/snkrsnkampa/Bastion
 *
 * This code is licensed under the SNKRSN Shared License. It is free to
 * download, copy, compile, use, study and refer under the terms of the
 * SNKRSN Shared License. You can modify the code only for personal or
 * internal use only. However, you can not redistribute the code without
 * explicitly getting permission fot it.
 *
 * Bastion BOT is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY. See the SNKRSN Shared License for
 * more details.
 *
 * You should have received a copy of the SNKRSN Shared License along
 * with this program. If not, see <https://github.com/snkrsnkampa/Bastion/LICENSE>.
 */

const sql = require('sqlite');
sql.open('./data/Bastion.sqlite');

exports.run = (Bastion, message, args) => {
  if (!message.member.hasPermission('ADMINISTRATOR')) return Bastion.log.info('User doesn\'t have permission to use this command.');
  if (args.length < 1) {
    sql.get(`SELECT greetDMMessage FROM guildSettings WHERE guildID=${message.guild.id}`).then(guild => {
      message.channel.send({embed: {
        color: Bastion.colors.dark_grey,
        title: 'DM Greeting message:',
        description: guild.greetDMMessage
      }}).catch(e => {
        Bastion.log.error(e.stack);
      });
    }).catch(e => {
      Bastion.log.error(e.stack);
    });
  }
  else {
    sql.run(`UPDATE guildSettings SET greetDMMessage="${args.join(' ').replace(/"/g, '\'')}" WHERE guildID=${message.guild.id}`).catch(e => {
      Bastion.log.error(e.stack);
    });

    message.channel.send({embed: {
      color: Bastion.colors.green,
      title: 'DM Greeting message set to:',
      description: args.join(' ')
    }}).catch(e => {
      Bastion.log.error(e.stack);
    });
  }
};

exports.config = {
  aliases: ['gdmmsg'],
  enabled: true
};

exports.help = {
  name: 'greetdmmessage',
  description: 'Edit the greeting message that is sent as direct message when a new member is joined in the server.',
  botPermission: '',
  userPermission: 'Administrator',
  usage: 'greetDMMessage [Message]',
  example: ['greetDMMessage Hello $user! Welcome to $server.']
};
<|endoftext|>


<commit_before>import _ from 'lodash';
export default class TestCtrl{
  constructor(test, $http, tests, unit, $window, user){
    this.$http = $http;
    this.test = test;
    this.unit = unit;
    this.shuffle = test.shuffle(unit);
    this.$window = $window;
    this.user = user;
    this.init(tests);
    this.feedback = {
      right: 'Korrekt',
      wrong: 'Leider nicht korrekt'
    };
  }
  init(tests){
    this.tests = tests.data.tests;
    if(this.shuffle.items){this.tests = _.shuffle(this.tests);}
    this.guess = tests.data.guess;
    this.run = tests.data.run;
    this.count = this.guess.responses.length;
    this.item = this.test.item(this.tests, this.guess);
    if(this.shuffle.choices){
      this.tests[this.item].choices = _.shuffle(this.tests[this.item].choices);
    }
    this.score = {
      max: _.sumBy(this.tests, this.test.maxPoints) || 0,
      current: this.test.runPoints(this.tests, this.guess)
    };
    this.response = this.test.input(this.tests[this.item]);
    this.output = null;
  }
  submit(){
    const item = this.tests[this.item];
    const response = this.test.response(item, this.response);
    const config = {
      method: 'POST',
      url: `api/guesses/${this.guess._id}/responses`,
      data: response,
      headers: {'if-unmodified-since': this.guess.updatedAt}
    };
    return this.$http(config)
    .then(
      (res) => {
        this.guess.responses.push(res.data);
        this.guess.updatedAt = res.headers('last-modified');
        this.score.current += this.test.points(item, response.value);
        if(item.type === 'input'){
          this.output = _.find(item.choices,{text: response.value});
          if(!this.output){
            this.output = {
              correct: false,
              feedback: 'Diese Antwort ist leider falsch'
            };
          }
        }
        this.count+=1;
        if(this.count === this.tests.length){
          return this.user.addUnit(this.unit._id);
        }
        return res;
      },
      (e) => {
        this.error = e;
        this.form.$submitted = false;
        return e;
      }
    );
  }
  next(){
    this.form.$submitted = false;
    this.form.$setPristine();
    if(this.count === this.tests.length){
      return this.$http.get('api/units/'+this.unit._id+'/summaries/test')
      .then(
        (res) => {
          this.init(res);
          return res;
        },
        (e) => {
          this.error = e;
          return e;
        }
      );
    }
    else{
      this.item = this.test.item(this.tests, this.guess);
      if(this.shuffle.choices){
        this.tests[this.item].choices = _.shuffle(this.tests[this.item].choices);
      }
      this.response = this.test.input(this.tests[this.item]);
      this.output = null;
    }
  }
  getGuesses(){
    const config = {
      method: 'GET',
      url: 'api/guesses',
      params: {
        conditions: {unit: this.unit._id}
      }
    };
    return this.$http(config)
    .then(
      (res) => {
        this.guesses = res.data;
        function points(guess, i){
          this.guesses[i].score = this.test.runPoints(this.tests, guess);
        }
        _.each(this.guesses, _.bind(points, this));
        if(this.guesses[this.guesses.length-1].responses.length < this.tests.length){
          this.guesses.pop();
        }
        return res;
      },
      (e) => {
        this.error = e;
        return e;
      }
    );
  }
  reload(){
    return this.$window.location.reload();
  }
}
TestCtrl.$inject = ['test', '$http', 'tests', 'unit', '$window', 'user'];
<commit_msg>Fix api call for tests<commit_after>import _ from 'lodash';
export default class TestCtrl{
  constructor(test, $http, tests, unit, $window, user){
    this.$http = $http;
    this.test = test;
    this.unit = unit.data;
    this.shuffle = test.shuffle(unit.data);
    this.$window = $window;
    this.user = user;
    this.init(tests);
    this.feedback = {
      right: 'Korrekt',
      wrong: 'Leider nicht korrekt'
    };
  }
  init(tests){
    this.tests = tests.data.tests;
    if(this.shuffle.items){this.tests = _.shuffle(this.tests);}
    this.guess = tests.data.guess;
    this.run = tests.data.run;
    this.count = this.guess.responses.length;
    this.item = this.test.item(this.tests, this.guess);
    if(this.shuffle.choices){
      this.tests[this.item].choices = _.shuffle(this.tests[this.item].choices);
    }
    this.score = {
      max: _.sumBy(this.tests, this.test.maxPoints) || 0,
      current: this.test.runPoints(this.tests, this.guess)
    };
    this.response = this.test.input(this.tests[this.item]);
    this.output = null;
  }
  submit(){
    const item = this.tests[this.item];
    const response = this.test.response(item, this.response);
    const config = {
      method: 'POST',
      url: `api/guesses/${this.guess._id}/responses`,
      data: response,
      headers: {'if-unmodified-since': this.guess.updatedAt}
    };
    return this.$http(config)
    .then(
      (res) => {
        this.guess.responses.push(res.data);
        this.guess.updatedAt = res.headers('last-modified');
        this.score.current += this.test.points(item, response.value);
        if(item.type === 'input'){
          this.output = _.find(item.choices,{text: response.value});
          if(!this.output){
            this.output = {
              correct: false,
              feedback: 'Diese Antwort ist leider falsch'
            };
          }
        }
        this.count+=1;
        if(this.count === this.tests.length){
          return this.user.addUnit(this.unit._id);
        }
        return res;
      },
      (e) => {
        this.error = e;
        this.form.$submitted = false;
        return e;
      }
    );
  }
  next(){
    this.form.$submitted = false;
    this.form.$setPristine();
    if(this.count === this.tests.length){
      return this.$http.get('api/units/'+this.unit._id+'/summaries/test')
      .then(
        (res) => {
          this.init(res);
          return res;
        },
        (e) => {
          this.error = e;
          return e;
        }
      );
    }
    else{
      this.item = this.test.item(this.tests, this.guess);
      if(this.shuffle.choices){
        this.tests[this.item].choices = _.shuffle(this.tests[this.item].choices);
      }
      this.response = this.test.input(this.tests[this.item]);
      this.output = null;
    }
  }
  getGuesses(){
    const config = {
      method: 'GET',
      url: 'api/guesses',
      params: {
        conditions: {unit: this.unit._id}
      }
    };
    return this.$http(config)
    .then(
      (res) => {
        this.guesses = res.data;
        function points(guess, i){
          this.guesses[i].score = this.test.runPoints(this.tests, guess);
        }
        _.each(this.guesses, _.bind(points, this));
        if(this.guesses[this.guesses.length-1].responses.length < this.tests.length){
          this.guesses.pop();
        }
        return res;
      },
      (e) => {
        this.error = e;
        return e;
      }
    );
  }
  reload(){
    return this.$window.location.reload();
  }
}
TestCtrl.$inject = ['test', '$http', 'tests', 'unit', '$window', 'user'];
<|endoftext|>