<commit_before>/**
 * # Match
 *
 * Retrieves selector
 */

const defaultIgnore = {
  attribute (attributeName) {
    return [
      'style',
      'data-reactid',
      'data-react-checksum'
    ].indexOf(attributeName) > -1
  }
}

/**
 * Get the path of the element
 * @param  {HTMLElement} node    - [description]
 * @param  {Object}      options - [description]
 * @return {String}              - [description]
 */
export default function match (node, options) {
  const path = []
  var element = node
  var length = path.length

  const {
    root = document,
    skip = null,
    ignore = {}
  } = options

  const skipCompare = skip && (Array.isArray(skip) ? skip : [skip]).map((entry) => {
    if (typeof entry !== 'function') {
      return (element) => element === entry
    }
    return entry
  })

  const skipChecks = (element) => {
    return skip && skipCompare.some((compare) => compare(element))
  }

  var ignoreClass = false

  Object.keys(ignore).forEach((type) => {
    if (type === 'class') {
      ignoreClass = true
    }
    var predicate = ignore[type]
    if (typeof predicate === 'function') return
    if (typeof predicate === 'number') {
      predicate = predicate.toString()
    }
    if (typeof predicate === 'string') {
      predicate = new RegExp(predicate)
    }
    // check class-/attributename for regex
    ignore[type] = predicate.test.bind(predicate)
  })

  if (ignoreClass) {
    const ignoreAttribute = ignore.attribute
    ignore.attribute = (name, value, defaultPredicate) => {
      return ignore.class(value) || ignoreAttribute && ignoreAttribute(name, value, defaultPredicate)
    }
  }

  while (element !== root) {

    if (skipChecks(element) !== true) {
      // global
      if (checkId(element, path, ignore)) break
      if (checkClassGlobal(element, path, ignore, root)) break
      if (checkAttributeGlobal(element, path, ignore, root)) break
      if (checkTagGlobal(element, path, ignore, root)) break

      // local
      checkClassLocal(element, path, ignore)

      // define only one selector each iteration
      if (path.length === length) {
        checkAttributeLocal(element, path, ignore)
      }
      if (path.length === length) {
        checkTagLocal(element, path, ignore)
      }

      if (path.length === length) {
        checkClassChild(element, path, ignore)
      }
      if (path.length === length) {
        checkAttributeChild(element, path, ignore)
      }
      if (path.length === length) {
        checkTagChild(element, path, ignore)
      }
    }

    element = element.parentNode
    length = path.length
  }

  if (element === root) {
    path.unshift('*')
  }

  return path.join(' ')
}

/**
 * [checkClassGlobal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkClassGlobal (element, path, ignore, root) {
  return checkClass(element, path, ignore, root)
}

/**
 * [checkClassLocal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkClassLocal (element, path, ignore) {
  return checkClass(element, path, ignore, element.parentNode)
}

/**
 * [checkClassChild description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkClassChild (element, path, ignore) {
  const className = element.getAttribute('class')
  if (checkIgnore(ignore.class, className)) {
    return false
  }
  return checkChild(element, path, `.${className.trim().replace(/\s+/g, '.')}`)
}

/**
 * [checkAttributeGlobal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttributeGlobal (element, path, ignore, root) {
  return checkAttribute(element, path, ignore, root)
}

/**
 * [checkAttributeLocal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttributeLocal (element, path, ignore) {
  return checkAttribute(element, path, ignore, element.parentNode)
}

/**
 * [checkAttributeChild description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttributeChild (element, path, ignore) {
  const attributes = element.attributes
  return Object.keys(attributes).some((key) => {
    const attribute = attributes[key]
    const attributeName = attribute.name
    const attributeValue = attribute.value
    if (checkIgnore(ignore.attribute, attributeName, attributeValue, defaultIgnore.attribute)) {
      return false
    }
    const pattern = `[${attributeName}="${attributeValue}"]`
    return checkChild(element, path, pattern)
  })
}

/**
 * [checkTagGlobal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTagGlobal (element, path, ignore, root) {
  return checkTag(element, path, ignore, root)
}

/**
 * [checkTagLocal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTagLocal (element, path, ignore) {
  return checkTag(element, path, ignore, element.parentNode)
}

/**
 * [checkTabChildren description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTagChild (element, path, ignore) {
  const tagName = element.tagName.toLowerCase()
  if (checkIgnore(ignore.tag, tagName)) {
    return false
  }
  return checkChild(element, path, tagName)
}

/**
 * [checkId description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkId (element, path, ignore) {
  const id = element.getAttribute('id')
  if (checkIgnore(ignore.id, id)) {
    return false
  }
  path.unshift(`#${id}`)
  return true
}

/**
 * [checkClass description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @param  {HTMLElement} parent  - [description]
 * @return {Boolean}             - [description]
 */
function checkClass (element, path, ignore, parent) {
  const className = element.getAttribute('class')
  if (checkIgnore(ignore.class, className)) {
    return false
  }
  const matches = parent.getElementsByClassName(className)
  if (matches.length === 1) {
    path.unshift(`.${className.trim().replace(/\s+/g, '.')}`)
    return true
  }
  return false
}

/**
 * [checkAttribute description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @param  {HTMLElement} parent  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttribute (element, path, ignore, parent) {
  const attributes = element.attributes
  return Object.keys(attributes).some((key) => {
    const attribute = attributes[key]
    const attributeName = attribute.name
    const attributeValue = attribute.value
    if (checkIgnore(ignore.attribute, attributeName, attributeValue, defaultIgnore.attribute)) {
      return false
    }
    const pattern = `[${attributeName}="${attributeValue}"]`
    const matches = parent.querySelectorAll(pattern)
    if (matches.length === 1) {
      path.unshift(pattern)
      return true
    }
  })
}

/**
 * [checkTag description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {HTMLElement} parent  - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTag (element, path, ignore, parent) {
  const tagName = element.tagName.toLowerCase()
  if (checkIgnore(ignore.tag, tagName)) {
    return false
  }
  const matches = parent.getElementsByTagName(tagName)
  if (matches.length === 1) {
    path.unshift(tagName)
    return true
  }
  return false
}

/**
 * [checkChild description]
 * Note: childTags is a custom property to use a view filter for tags on for virutal elements
 * @param  {HTMLElement} element  - [description]
 * @param  {Array}       path     - [description]
 * @param  {String}      selector - [description]
 * @return {Boolean}              - [description]
 */
function checkChild (element, path, selector) {
  const parent = element.parentNode
  const children = parent.childTags || parent.children
  for (var i = 0, l = children.length; i < l; i++) {
    if (children[i] === element) {
      path.unshift(`> ${selector}:nth-child(${i+1})`)
      return true
    }
  }
  return false
}

/**
 * [checkIgnore description]
 * @param  {Function} predicate        [description]
 * @param  {string}   name             [description]
 * @param  {string}   value            [description]
 * @param  {Function} defaultPredicate [description]
 * @return {boolean}                   [description]
 */
function checkIgnore (predicate, name, value, defaultPredicate) {
  if (!name) {
    return true
  }
  const check = predicate || defaultPredicate
  if (!check) {
    return false
  }
  return check(name, value, defaultPredicate)
}
<commit_msg>use name fallback for class ignore<commit_after>/**
 * # Match
 *
 * Retrieves selector
 */

const defaultIgnore = {
  attribute (attributeName) {
    return [
      'style',
      'data-reactid',
      'data-react-checksum'
    ].indexOf(attributeName) > -1
  }
}

/**
 * Get the path of the element
 * @param  {HTMLElement} node    - [description]
 * @param  {Object}      options - [description]
 * @return {String}              - [description]
 */
export default function match (node, options) {
  const path = []
  var element = node
  var length = path.length

  const {
    root = document,
    skip = null,
    ignore = {}
  } = options

  const skipCompare = skip && (Array.isArray(skip) ? skip : [skip]).map((entry) => {
    if (typeof entry !== 'function') {
      return (element) => element === entry
    }
    return entry
  })

  const skipChecks = (element) => {
    return skip && skipCompare.some((compare) => compare(element))
  }

  var ignoreClass = false

  Object.keys(ignore).forEach((type) => {
    if (type === 'class') {
      ignoreClass = true
    }
    var predicate = ignore[type]
    if (typeof predicate === 'function') return
    if (typeof predicate === 'number') {
      predicate = predicate.toString()
    }
    if (typeof predicate === 'string') {
      predicate = new RegExp(predicate)
    }
    // check class-/attributename for regex
    ignore[type] = predicate.test.bind(predicate)
  })

  if (ignoreClass) {
    const ignoreAttribute = ignore.attribute
    ignore.attribute = (name, value, defaultPredicate) => {
      return ignore.class(value) || ignoreAttribute && ignoreAttribute(name, value, defaultPredicate)
    }
  }

  while (element !== root) {

    if (skipChecks(element) !== true) {
      // global
      if (checkId(element, path, ignore)) break
      if (checkClassGlobal(element, path, ignore, root)) break
      if (checkAttributeGlobal(element, path, ignore, root)) break
      if (checkTagGlobal(element, path, ignore, root)) break

      // local
      checkClassLocal(element, path, ignore)

      // define only one selector each iteration
      if (path.length === length) {
        checkAttributeLocal(element, path, ignore)
      }
      if (path.length === length) {
        checkTagLocal(element, path, ignore)
      }

      if (path.length === length) {
        checkClassChild(element, path, ignore)
      }
      if (path.length === length) {
        checkAttributeChild(element, path, ignore)
      }
      if (path.length === length) {
        checkTagChild(element, path, ignore)
      }
    }

    element = element.parentNode
    length = path.length
  }

  if (element === root) {
    path.unshift('*')
  }

  return path.join(' ')
}

/**
 * [checkClassGlobal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkClassGlobal (element, path, ignore, root) {
  return checkClass(element, path, ignore, root)
}

/**
 * [checkClassLocal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkClassLocal (element, path, ignore) {
  return checkClass(element, path, ignore, element.parentNode)
}

/**
 * [checkClassChild description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkClassChild (element, path, ignore) {
  const className = element.getAttribute('class')
  if (checkIgnore(ignore.class, className)) {
    return false
  }
  return checkChild(element, path, `.${className.trim().replace(/\s+/g, '.')}`)
}

/**
 * [checkAttributeGlobal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttributeGlobal (element, path, ignore, root) {
  return checkAttribute(element, path, ignore, root)
}

/**
 * [checkAttributeLocal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttributeLocal (element, path, ignore) {
  return checkAttribute(element, path, ignore, element.parentNode)
}

/**
 * [checkAttributeChild description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttributeChild (element, path, ignore) {
  const attributes = element.attributes
  return Object.keys(attributes).some((key) => {
    const attribute = attributes[key]
    const attributeName = attribute.name
    const attributeValue = attribute.value
    if (checkIgnore(ignore.attribute, attributeName, attributeValue, defaultIgnore.attribute)) {
      return false
    }
    const pattern = `[${attributeName}="${attributeValue}"]`
    return checkChild(element, path, pattern)
  })
}

/**
 * [checkTagGlobal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTagGlobal (element, path, ignore, root) {
  return checkTag(element, path, ignore, root)
}

/**
 * [checkTagLocal description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTagLocal (element, path, ignore) {
  return checkTag(element, path, ignore, element.parentNode)
}

/**
 * [checkTabChildren description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTagChild (element, path, ignore) {
  const tagName = element.tagName.toLowerCase()
  if (checkIgnore(ignore.tag, tagName)) {
    return false
  }
  return checkChild(element, path, tagName)
}

/**
 * [checkId description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkId (element, path, ignore) {
  const id = element.getAttribute('id')
  if (checkIgnore(ignore.id, id)) {
    return false
  }
  path.unshift(`#${id}`)
  return true
}

/**
 * [checkClass description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @param  {HTMLElement} parent  - [description]
 * @return {Boolean}             - [description]
 */
function checkClass (element, path, ignore, parent) {
  const className = element.getAttribute('class')
  if (checkIgnore(ignore.class, className)) {
    return false
  }
  const matches = parent.getElementsByClassName(className)
  if (matches.length === 1) {
    path.unshift(`.${className.trim().replace(/\s+/g, '.')}`)
    return true
  }
  return false
}

/**
 * [checkAttribute description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {Object}      ignore  - [description]
 * @param  {HTMLElement} parent  - [description]
 * @return {Boolean}             - [description]
 */
function checkAttribute (element, path, ignore, parent) {
  const attributes = element.attributes
  return Object.keys(attributes).some((key) => {
    const attribute = attributes[key]
    const attributeName = attribute.name
    const attributeValue = attribute.value
    if (checkIgnore(ignore.attribute, attributeName, attributeValue, defaultIgnore.attribute)) {
      return false
    }
    const pattern = `[${attributeName}="${attributeValue}"]`
    const matches = parent.querySelectorAll(pattern)
    if (matches.length === 1) {
      path.unshift(pattern)
      return true
    }
  })
}

/**
 * [checkTag description]
 * @param  {HTMLElement} element - [description]
 * @param  {Array}       path    - [description]
 * @param  {HTMLElement} parent  - [description]
 * @param  {Object}      ignore  - [description]
 * @return {Boolean}             - [description]
 */
function checkTag (element, path, ignore, parent) {
  const tagName = element.tagName.toLowerCase()
  if (checkIgnore(ignore.tag, tagName)) {
    return false
  }
  const matches = parent.getElementsByTagName(tagName)
  if (matches.length === 1) {
    path.unshift(tagName)
    return true
  }
  return false
}

/**
 * [checkChild description]
 * Note: childTags is a custom property to use a view filter for tags on for virutal elements
 * @param  {HTMLElement} element  - [description]
 * @param  {Array}       path     - [description]
 * @param  {String}      selector - [description]
 * @return {Boolean}              - [description]
 */
function checkChild (element, path, selector) {
  const parent = element.parentNode
  const children = parent.childTags || parent.children
  for (var i = 0, l = children.length; i < l; i++) {
    if (children[i] === element) {
      path.unshift(`> ${selector}:nth-child(${i+1})`)
      return true
    }
  }
  return false
}

/**
 * [checkIgnore description]
 * @param  {Function} predicate        [description]
 * @param  {string}   name             [description]
 * @param  {string}   value            [description]
 * @param  {Function} defaultPredicate [description]
 * @return {boolean}                   [description]
 */
function checkIgnore (predicate, name, value, defaultPredicate) {
  if (!name) {
    return true
  }
  const check = predicate || defaultPredicate
  if (!check) {
    return false
  }
  return check(name, value || name, defaultPredicate)
}
<|endoftext|>


<commit_before>import './assets/styles/main.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/components/App/App.jsx';
import NotFound from './app/components/NotFound/NotFound.jsx';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import 'normalize.css';

ReactDOM.render(
  <Router>
    <Switch>
      <Route path="/" exact component={App}/>
      <Route component={NotFound}/>
    </Switch>
  </Router>,
  document.getElementById('app')
);<commit_msg>FIX Router<commit_after>import 'normalize.css';
import './assets/styles/main.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/components/App/App.jsx';
import NotFound from './app/components/NotFound/NotFound.jsx';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

ReactDOM.render(
  <Router>
    <Switch>
      <Route path="/" component={App}/>
      <Route component={NotFound}/>
    </Switch>
  </Router>,
  document.querySelector('#app')
);<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign */

const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const Raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, captureUncaught = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = Raven.config(...args);
    if (captureUncaught) {
      this._client.install();
    }
  }
  _write(data, encoding, cb) {
    const extra = {
      level: ((tags = []) => {
        tags = (typeof tags === 'string') ? [tags] : tags;
        if (hoek.contain(tags, ['fatal'], { part: true })) {
          return 'fatal';
        } else if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(data.tags),
      extra: {
        event: data.event,
        tags: data.tags || [],
      },
    };

    this._client.captureMessage(data.data, extra, () => cb());
  }
}

module.exports = GoodSentry;
<commit_msg>Send tags as k/v map<commit_after>/* eslint-disable no-param-reassign */

const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const Raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, captureUncaught = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = Raven.config(...args);
    if (captureUncaught) {
      this._client.install();
    }
  }
  _write(data, encoding, cb) {
    const additionalData = {
      level: ((tags = []) => {
        tags = (typeof tags === 'string') ? [tags] : tags;
        if (hoek.contain(tags, ['fatal'], { part: true })) {
          return 'fatal';
        } else if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(data.tags),
      tags: ((tags = []) => tags.filter(
        (tag) => [
          'fatal',
          'error',
          'warning',
          'info',
          'debug',
        ].includes(tag) === false,
      ).reduce((acc, curr) => {
        acc[curr] = true;
        return acc;
      }, {}))(data.tags),
      extra: {
        event: data.event,
      },
    };

    this._client.captureMessage(data.data, additionalData, () => cb());
  }
}

module.exports = GoodSentry;
<|endoftext|>


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

'use strict';

var Microphone = require('./Microphone');
var models = require('./data/models.json').models;
var initViews = require('./views').initViews;
var utils = require('./utils');
var pkg = require('../package');

window.BUFFERSIZE = 8192;

$(document).ready(function() {

  // Temporary app data
  $('#appSettings')
    .html(
      '
Version: ' + pkg.version + '
'
      + '
Buffer Size: ' + BUFFERSIZE + '
'
    );

  // Make call to API to try and get token
  utils.getToken(function(token) {

    window.onbeforeunload = function(e) {
      localStorage.clear();
    };

    if (!token) {
      console.error('No authorization token available');
      console.error('Attempting to reconnect...');
    }

    var viewContext = {
      models: models,
      token: token,
      bufferSize: BUFFERSIZE
    };

    initViews(viewContext);

    utils.initPubSub();

    // Save models to localstorage
    localStorage.setItem('models', JSON.stringify(models));

    // Set default current model
    localStorage.setItem('currentModel', 'en-US_BroadbandModel');
    localStorage.setItem('sessionPermissions', 'true');

    $.subscribe('clearscreen', function() {
      $('#resultsText').text('');
      $('#resultsJSON').text('');
      $('.error-row').hide();
      $('.notification-row').hide();
      $('.hypotheses > ul').empty();
      $('#metadataTableBody').empty();
    });

  });

});

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

'use strict';

var Microphone = require('./Microphone');
var models = require('./data/models.json').models;
var initViews = require('./views').initViews;
var utils = require('./utils');
var pkg = require('../package');

window.BUFFERSIZE = 8192;

$(document).ready(function() {

  // Temporary app data
  $('#appSettings')
    .html(
      '
Version: ' + pkg.version + '
'
      + '
Buffer Size: ' + BUFFERSIZE + '
'
    );

  // Make call to API to try and get token
  utils.getToken(function(token) {

    window.onbeforeunload = function(e) {
      localStorage.clear();
    };

    if (!token) {
      console.error('No authorization token available');
      console.error('Attempting to reconnect...');
    }

    var viewContext = {
      currentModel: 'en-US_BroadbandModel',
      models: models,
      token: token,
      bufferSize: BUFFERSIZE
    };

    initViews(viewContext);

    utils.initPubSub();

    // Save models to localstorage
    localStorage.setItem('models', JSON.stringify(models));

    // Set default current model
    localStorage.setItem('currentModel', 'en-US_BroadbandModel');
    localStorage.setItem('sessionPermissions', 'true');

    $.subscribe('clearscreen', function() {
      $('#resultsText').text('');
      $('#resultsJSON').text('');
      $('.error-row').hide();
      $('.notification-row').hide();
      $('.hypotheses > ul').empty();
      $('#metadataTableBody').empty();
    });

  });

});<|endoftext|>


<commit_before>(function() {
  // next-tick requiring stream so that by the time i actually need it webpack has processed the
  // Readable and PassThrough exports
  require('stream');
  const browser = require('os').platform() === 'browser';
  const http = require('http');
  const https = require('https');
  const URL = require('url');
  const zlib = require('zlib');
  const Stream = require('stream');
  const FormData = require('./FormData');
  const Package = require('../package.json');

  class Snekfetch extends Stream.Readable {
    constructor(method, url) {
      super();
      const { hostname, path, protocol } = URL.parse(url);
      this.protocol = protocol;
      this.url = url;
      this.options = {
        method: method.toUpperCase(),
        hostname,
        path,
        headers: {},
      };
      this.data = null;
      this.ended = false;
    }

    set(name, value) {
      if (name !== null && typeof name === 'object') {
        for (const key of Object.keys(name)) this.set(key, name[key]);
      } else {
        this.options.headers[name.toLowerCase()] = value;
      }
      return this;
    }

    attach(name, data, filename) {
      const form = this._getFormData();
      this.set('Content-Type', `multipart/form-data; boundary=${form.boundary}`);
      form.append(name, data, filename);
      this.data = form;
      return this;
    }

    send(data) {
      if (typeof data === 'object') {
        this.set('Content-Type', 'application/json');
        this.data = JSON.stringify(data);
      } else {
        this.data = data;
      }
      return this;
    }

    go() {
      return new Promise((resolve) => {
        this.ended = true;
        if (!this.options.headers['user-agent']) {
          this.set('user-agent', `snekfetch/${Snekfetch.version} (${Package.repository.url.replace(/\.?git/, '')})`);
        }
        const request = (this.protocol === 'https:' ? https : http)
        .request(this.options, (response) => {
          response.request = request;
          const stream = new Stream.PassThrough();
          if (this._shouldUnzip(response)) {
            response.pipe(zlib.createUnzip({
              flush: zlib.Z_SYNC_FLUSH,
              finishFlush: zlib.Z_SYNC_FLUSH,
            })).pipe(stream);
          } else {
            response.pipe(stream);
          }

          let body = [];
          stream.on('data', (chunk) => {
            if (!this.push(chunk)) this.pause();
            body.push(Buffer.from(chunk));
          });
          stream.on('end', () => {
            this.push(null);
            const concated = Buffer.concat(body);
            if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
              resolve(Snekfetch[this.options.method.toLowerCase()](URL.resolve(this.url, response.headers.location)));
              return;
            }

            const res = {
              request: this.options,
              body: concated,
              text: concated.toString(),
              ok: response.statusCode >= 200 && response.statusCode < 300,
              headers: response.headers,
              status: response.statusCode,
              statusText: response.statusText || http.STATUS_CODES[response.statusCode],
              url: this.url,
            };

            const type = response.headers['content-type'];
            if (type.includes('application/json')) {
              try {
                res.body = JSON.parse(res.text);
              } catch (err) {} // eslint-disable-line no-empty
            } else if (type.includes('application/x-www-form-urlencoded')) {
              res.body = {};
              for (const [k, v] of res.text.split('&').map(q => q.split('='))) res.body[k] = v;
            }

            resolve(res);
          });
        });
        const data = this.data ? this.data.end ? this.data.end() : this.data : null;
        request.end(data);
      });
    }

    then(s, f) {
      return this.go()
      .then((res) => s ? s(res) : res)
      .catch((err) => f ? f(err) : err);
    }

    end(cb) {
      return this.go().then((res) => {
        if (res.ok) return cb(null, res);
        else return cb(res, res);
      }).catch((err) => cb(err));
    }

    catch(f) {
      return this.then(null, f);
    }

    _read() {
      this.resume();
      if (this.ended) return;
      this.end(() => {}); // eslint-disable-line no-empty-function
    }

    _shouldUnzip(res) {
      if (res.statusCode === 204 || res.statusCode === 304) return false;
      if (res.headers['content-length'] === '0') return false;
      return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']);
    }

    _getFormData() {
      if (!this._formData) this._formData = new FormData();
      return this._formData;
    }
  }

  Snekfetch.version = Package.version;

  Snekfetch.METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH', 'BREW'];
  for (const method of Snekfetch.METHODS) Snekfetch[method.toLowerCase()] = (url) => new Snekfetch(method, url);

  module.exports = Snekfetch;
  if (browser) window.Snekfetch = Snekfetch;
}());
<commit_msg>change things for good<commit_after>(function() {
  // next-tick requiring stream so that by the time i actually need it webpack has processed the
  // Readable and PassThrough exports
  require('stream');
  const browser = require('os').platform() === 'browser';
  const http = require('http');
  const https = require('https');
  const URL = require('url');
  const zlib = require('zlib');
  const Stream = require('stream');
  const FormData = require('./FormData');
  const Package = require('../package.json');

  class Snekfetch extends Stream.Readable {
    constructor(method, url) {
      super();
      this.method = method.toUpperCase();
      this.url = url;
      this.headers = {};
      this.data = null;
      this.spent = false;
    }

    set(name, value) {
      if (name !== null && typeof name === 'object') {
        for (const key of Object.keys(name)) this.set(key, name[key]);
      } else {
        this.headers[name.toLowerCase()] = value;
      }
      return this;
    }

    attach(name, data, filename) {
      const form = this._getFormData();
      this.set('Content-Type', `multipart/form-data; boundary=${form.boundary}`);
      form.append(name, data, filename);
      this.data = form;
      return this;
    }

    send(data) {
      if (typeof data === 'object') {
        this.set('Content-Type', 'application/json');
        this.data = JSON.stringify(data);
      } else {
        this.data = data;
      }
      return this;
    }

    go() {
      if (this.spent) return Promise.reject(new Error('Request has been spent!'));
      return new Promise((resolve) => {
        this.spent = true;
        if (!this.headers['user-agent']) {
          this.set('user-agent', `snekfetch/${Snekfetch.version} (${Package.repository.url.replace(/\.?git/, '')})`);
        }

        const options = URL.parse(this.url);
        options.method = this.method;
        options.headers = this.headers;

        const request = (options.protocol === 'https:' ? https : http)
        .request(options, (response) => {
          response.request = request;
          const stream = new Stream.PassThrough();
          if (this._shouldUnzip(response)) {
            response.pipe(zlib.createUnzip({
              flush: zlib.Z_SYNC_FLUSH,
              finishFlush: zlib.Z_SYNC_FLUSH,
            })).pipe(stream);
          } else {
            response.pipe(stream);
          }

          let body = [];
          stream.on('data', (chunk) => {
            if (!this.push(chunk)) this.pause();
            body.push(Buffer.from(chunk));
          });
          stream.on('end', () => {
            this.push(null);
            const concated = Buffer.concat(body);
            if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
              resolve(new Snekfetch(this.method, URL.resolve(this.url, response.headers.location)));
              return;
            }

            const res = {
              request: this.options,
              body: concated,
              text: concated.toString(),
              ok: response.statusCode >= 200 && response.statusCode < 300,
              headers: response.headers,
              status: response.statusCode,
              statusText: response.statusText || http.STATUS_CODES[response.statusCode],
              url: this.url,
            };

            const type = response.headers['content-type'];
            if (type.includes('application/json')) {
              try {
                res.body = JSON.parse(res.text);
              } catch (err) {} // eslint-disable-line no-empty
            } else if (type.includes('application/x-www-form-urlencoded')) {
              res.body = {};
              for (const [k, v] of res.text.split('&').map(q => q.split('='))) res.body[k] = v;
            }

            resolve(res);
          });
        });
        const data = this.data ? this.data.end ? this.data.end() : this.data : null;
        request.end(data);
      });
    }

    then(s, f) {
      return this.go()
      .then((res) => s ? s(res) : res)
      .catch((err) => f ? f(err) : err);
    }

    end(cb) {
      return this.go().then((res) => {
        if (res.ok) return cb(null, res);
        else return cb(res, res);
      }).catch((err) => cb(err));
    }

    catch(f) {
      return this.then(null, f);
    }

    _read() {
      if (this.spent) return;
      this.resume();
      this.end(() => {}); // eslint-disable-line no-empty-function
    }

    _shouldUnzip(res) {
      if (res.statusCode === 204 || res.statusCode === 304) return false;
      if (res.headers['content-length'] === '0') return false;
      return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']);
    }

    _getFormData() {
      if (!this._formData) this._formData = new FormData();
      return this._formData;
    }
  }

  Snekfetch.version = Package.version;

  Snekfetch.METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH', 'BREW'];
  for (const method of Snekfetch.METHODS) Snekfetch[method.toLowerCase()] = (url) => new Snekfetch(method, url);

  module.exports = Snekfetch;
  if (browser) window.Snekfetch = Snekfetch;
}());
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Portal from 'react-minimalist-portal';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import classNames from 'classnames';
import injectSheet from 'react-jss';
import styles from './styles';

class Modal extends Component {
  constructor(props) {
    super(props);
    this.handleKeydown = this.handleKeydown.bind(this);
    this.onClickOverlay = this.onClickOverlay.bind(this);
    this.onClickCloseIcon = this.onClickCloseIcon.bind(this);
    this.state = {
      showPortal: props.open,
      open: props.open,
    };
  }

  componentDidMount() {
    if (this.props.closeOnEsc) {
      document.addEventListener('keydown', this.handleKeydown);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!this.props.open && nextProps.open) {
      this.setState({
        open: true,
        showPortal: true,
        previousBodyStyleOverflow: document.body.style.overflow,
      },
      () => {
        document.body.style.overflow = 'hidden';
      });
    }
    if (this.props.open && !nextProps.open) {
      this.setState({ open: false });
      // Let the animation finish
      this.timeout = setTimeout(() => {
        this.setState({ showPortal: false });
        document.body.style.overflow = this.state.previousBodyStyleOverflow;
      }, 500);
    }
  }

  componentWillUnmount() {
    if (this.props.closeOnEsc) {
      document.removeEventListener('keydown', this.handleKeydown);
    }
    document.body.style.overflow = null;
    if (this.timeout) {
      clearTimeout(this.timeout);
    }
  }

  onClickOverlay(e) {
    const { sheet: { classes }, closeOnOverlayClick } = this.props;
    if (!closeOnOverlayClick) return;
    const className = e.target.className.split(' ');
    if (className.indexOf(classes.overlay) !== -1) {
      e.stopPropagation();
      this.props.onClose();
    }
  }

  onClickCloseIcon(e) {
    e.stopPropagation();
    this.props.onClose();
  }

  handleKeydown(e) {
    if (e.keyCode === 27) {
      this.props.onClose();
    }
  }

  render() {
    const {
      little,
      sheet: { classes },
      overlayClassName,
      modalClassName,
      closeIconClassName,
      overlayStyle,
      modalStyle,
      showCloseIcon,
      closeIconSize,
    } = this.props;
    const { open, showPortal } = this.state;
    if (!showPortal) return null;
    return (
      <Portal>
        <ReactCSSTransitionGroup
          transitionName={{
            appear: classes.transitionEnter,
            appearActive: classes.transitionEnterActive,
            enter: classes.transitionEnter,
            enterActive: classes.transitionEnterActive,
            leave: classes.transitionLeave,
            leaveActive: classes.transitionLeaveActive,
          }}
          transitionAppear
          transitionLeave
          transitionAppearTimeout={500}
          transitionEnterTimeout={500}
          transitionLeaveTimeout={500}
        >
          {open &&

                {showCloseIcon ?
                  <svg className={classNames(classes.closeIcon, closeIconClassName)} onClick={this.onClickCloseIcon} xmlns="http://www.w3.org/2000/svg" width={closeIconSize} height={closeIconSize} viewBox="0 0 36 36"><path d="M28.5 9.62L26.38 7.5 18 15.88 9.62 7.5 7.5 9.62 15.88 18 7.5 26.38l2.12 2.12L18 20.12l8.38 8.38 2.12-2.12L20.12 18z" /></svg>
                  : null}
                {this.props.children}

          }
        </ReactCSSTransitionGroup>
      </Portal>
    );
  }
}

Modal.propTypes = {
  closeOnEsc: PropTypes.bool,
  closeOnOverlayClick: PropTypes.bool,
  onClose: PropTypes.func.isRequired,
  open: PropTypes.bool.isRequired,
  overlayClassName: PropTypes.string,
  modalClassName: PropTypes.string,
  closeIconClassName: PropTypes.string,
  overlayStyle: PropTypes.object,
  modalStyle: PropTypes.object,
  children: PropTypes.node,
  sheet: PropTypes.object,
  little: PropTypes.bool,
  showCloseIcon: PropTypes.bool,
  closeIconSize: PropTypes.number,
};

Modal.defaultProps = {
  closeOnEsc: true,
  closeOnOverlayClick: true,
  showCloseIcon: true,
  closeIconSize: 28,
};

export default injectSheet(styles)(Modal);
<commit_msg>IE 11 Fix<commit_after>import React, { Component, PropTypes } from 'react';
import Portal from 'react-minimalist-portal';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import classNames from 'classnames';
import injectSheet from 'react-jss';
import styles from './styles';

class Modal extends Component {
  constructor(props) {
    super(props);
    this.handleKeydown = this.handleKeydown.bind(this);
    this.onClickOverlay = this.onClickOverlay.bind(this);
    this.onClickCloseIcon = this.onClickCloseIcon.bind(this);
    this.state = {
      showPortal: props.open,
      open: props.open,
    };
  }

  componentDidMount() {
    if (this.props.closeOnEsc) {
      document.addEventListener('keydown', this.handleKeydown);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (!this.props.open && nextProps.open) {
      this.setState({
        open: true,
        showPortal: true,
        previousBodyStyleOverflow: document.body.style.overflow,
      },
      () => {
        document.body.style.overflow = 'hidden';
      });
    }
    if (this.props.open && !nextProps.open) {
      this.setState({ open: false });
      // Let the animation finish
      this.timeout = setTimeout(() => {
        this.setState({ showPortal: false });
        document.body.style.overflow = this.state.previousBodyStyleOverflow;
      }, 500);
    }
  }

  componentWillUnmount() {
    if (this.props.closeOnEsc) {
      document.removeEventListener('keydown', this.handleKeydown);
    }
    document.body.style.overflow = this.state.previousBodyStyleOverflow;
    if (this.timeout) {
      clearTimeout(this.timeout);
    }
  }

  onClickOverlay(e) {
    const { sheet: { classes }, closeOnOverlayClick } = this.props;
    if (!closeOnOverlayClick) return;
    const className = e.target.className.split(' ');
    if (className.indexOf(classes.overlay) !== -1) {
      e.stopPropagation();
      this.props.onClose();
    }
  }

  onClickCloseIcon(e) {
    e.stopPropagation();
    this.props.onClose();
  }

  handleKeydown(e) {
    if (e.keyCode === 27) {
      this.props.onClose();
    }
  }

  render() {
    const {
      little,
      sheet: { classes },
      overlayClassName,
      modalClassName,
      closeIconClassName,
      overlayStyle,
      modalStyle,
      showCloseIcon,
      closeIconSize,
    } = this.props;
    const { open, showPortal } = this.state;
    if (!showPortal) return null;
    return (
      <Portal>
        <ReactCSSTransitionGroup
          transitionName={{
            appear: classes.transitionEnter,
            appearActive: classes.transitionEnterActive,
            enter: classes.transitionEnter,
            enterActive: classes.transitionEnterActive,
            leave: classes.transitionLeave,
            leaveActive: classes.transitionLeaveActive,
          }}
          transitionAppear
          transitionLeave
          transitionAppearTimeout={500}
          transitionEnterTimeout={500}
          transitionLeaveTimeout={500}
        >
          {open &&

                {showCloseIcon ?
                  <svg className={classNames(classes.closeIcon, closeIconClassName)} onClick={this.onClickCloseIcon} xmlns="http://www.w3.org/2000/svg" width={closeIconSize} height={closeIconSize} viewBox="0 0 36 36"><path d="M28.5 9.62L26.38 7.5 18 15.88 9.62 7.5 7.5 9.62 15.88 18 7.5 26.38l2.12 2.12L18 20.12l8.38 8.38 2.12-2.12L20.12 18z" /></svg>
                  : null}
                {this.props.children}

          }
        </ReactCSSTransitionGroup>
      </Portal>
    );
  }
}

Modal.propTypes = {
  closeOnEsc: PropTypes.bool,
  closeOnOverlayClick: PropTypes.bool,
  onClose: PropTypes.func.isRequired,
  open: PropTypes.bool.isRequired,
  overlayClassName: PropTypes.string,
  modalClassName: PropTypes.string,
  closeIconClassName: PropTypes.string,
  overlayStyle: PropTypes.object,
  modalStyle: PropTypes.object,
  children: PropTypes.node,
  sheet: PropTypes.object,
  little: PropTypes.bool,
  showCloseIcon: PropTypes.bool,
  closeIconSize: PropTypes.number,
};

Modal.defaultProps = {
  closeOnEsc: true,
  closeOnOverlayClick: true,
  showCloseIcon: true,
  closeIconSize: 28,
};

export default injectSheet(styles)(Modal);
<|endoftext|>


<commit_before>angular.module('angular-cordova-file')
    .factory('CordovaFile', function ($q, $upload, Model) {
        var CordovaFile = Model.extend({
            /**
             * Get the preview URL of file.
             *
             * @return promise
             */
            getPreviewUrl: function () {
                var deferred = $q.defer();

                if (this.has('dataUrl')) {
                    deferred.resolve(this.get('dataUrl'));
                } else if (this.has('uri')) {
                    if (window.resolveLocalFileSystemURL !== undefined) {
                        window.resolveLocalFileSystemURL(this.get('uri'), function (fileEntry) {
                            deferred.resolve(fileEntry.toURL());
                        });
                    } else {
                        deferred.resolve(this.get('uri'));
                    }
                } else if (this.has('file')) {
                    var reader = new FileReader();

                    reader.onloadend = function (e) {
                        deferred.resolve(e.target.result);
                    };
                    reader.onerror = function (reason) {
                        deferred.reject(reason);
                    };

                    reader.readAsDataURL(this.get('file'));
                } else {
                    deferred.reject('Unable to get preview URL');
                }

                return deferred.promise;
            },
            /**
             * Upload the file using `ng-file-upload` or `FileTransfer` if
             * available.
             *
             * @param options
             *  Must contain the following options:
             *  - url
             *  - fileKey
             *
             * @return promise
             */
            upload: function (options) {
                var deferred = $q.defer();
                options = options || {};

                if (typeof FileTransfer == "undefined") {
                    $upload.upload({
                        url: options.url,
                        // method: POST or PUT,
                        headers: options.headers,
                        // withCredentials: true,
                        data: options.data,
                        file: this.get('file'),
                        fileFormDataName: options.fileKey
                    }).progress(function(evt) {
                        var percent = parseInt(100.0 * evt.loaded / evt.total);
                        deferred.notify(percent);
                    }).success(function(data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function(reason){
                        deferred.reject(reason);
                    });
                } else if (this.has('uri')) {
                    var uri = this.get('uri'),
                        uploadOptions = new FileUploadOptions();

                    uploadOptions.fileKey = options.fileKey;
                    uploadOptions.fileName = uri.substr(uri.lastIndexOf('/') + 1);
                    uploadOptions.mimeType = this.get('contentType');
                    uploadOptions.headers = options.headers;

                    uploadOptions.params = options.data;

                    var ft = new FileTransfer();
                    ft.onprogress = function (evt) {
                        var percent = parseInt(100.0 * evt.loaded / evt.total);
                        deferred.notify(percent);
                    };

                    ft.upload(
                        uri,
                        encodeURI(options.url),
                        function (result) {
                            // Deserialize json response
                            var response = angular.fromJson(result.response);
                            deferred.resolve(response);
                        },
                        function (error) {
                            deferred.reject(error);
                        },
                        uploadOptions
                    );
                } else {
                    deferred.reject('There\'s not URI');
                }

                return deferred.promise;
            }
        }, {
            fromFile: function (file) {
                return new CordovaFile({
                    file: file,
                    contentType: file.type
                });
            },
            fromUri: function (uri) {
                return new CordovaFile({
                    uri: uri
                });
            }
        });

        return CordovaFile;
    });<commit_msg>Allow method and withCredentials use for http upload<commit_after>angular.module('angular-cordova-file')
    .factory('CordovaFile', function ($q, $upload, Model) {
        var CordovaFile = Model.extend({
            /**
             * Get the preview URL of file.
             *
             * @return promise
             */
            getPreviewUrl: function () {
                var deferred = $q.defer();

                if (this.has('dataUrl')) {
                    deferred.resolve(this.get('dataUrl'));
                } else if (this.has('uri')) {
                    if (window.resolveLocalFileSystemURL !== undefined) {
                        window.resolveLocalFileSystemURL(this.get('uri'), function (fileEntry) {
                            deferred.resolve(fileEntry.toURL());
                        });
                    } else {
                        deferred.resolve(this.get('uri'));
                    }
                } else if (this.has('file')) {
                    var reader = new FileReader();

                    reader.onloadend = function (e) {
                        deferred.resolve(e.target.result);
                    };
                    reader.onerror = function (reason) {
                        deferred.reject(reason);
                    };

                    reader.readAsDataURL(this.get('file'));
                } else {
                    deferred.reject('Unable to get preview URL');
                }

                return deferred.promise;
            },
            /**
             * Upload the file using `ng-file-upload` or `FileTransfer` if
             * available.
             *
             * @param options
             *  Must contain the following options:
             *  - url
             *  - fileKey
             *
             * @return promise
             */
            upload: function (options) {
                var deferred = $q.defer();
                options = options || {};

                if (typeof FileTransfer == "undefined") {
                    $upload.upload({
                        url: options.url,
                        method: options.method,
                        headers: options.headers,
                        withCredentials: options.withCredentials,
                        data: options.data,
                        file: this.get('file'),
                        fileFormDataName: options.fileKey
                    }).progress(function(evt) {
                        var percent = parseInt(100.0 * evt.loaded / evt.total);
                        deferred.notify(percent);
                    }).success(function(data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function(reason){
                        deferred.reject(reason);
                    });
                } else if (this.has('uri')) {
                    var uri = this.get('uri'),
                        uploadOptions = new FileUploadOptions();

                    uploadOptions.fileKey = options.fileKey;
                    uploadOptions.fileName = uri.substr(uri.lastIndexOf('/') + 1);
                    uploadOptions.mimeType = this.get('contentType');
                    uploadOptions.headers = options.headers;

                    uploadOptions.params = options.data;

                    var ft = new FileTransfer();
                    ft.onprogress = function (evt) {
                        var percent = parseInt(100.0 * evt.loaded / evt.total);
                        deferred.notify(percent);
                    };

                    ft.upload(
                        uri,
                        encodeURI(options.url),
                        function (result) {
                            // Deserialize json response
                            var response = angular.fromJson(result.response);
                            deferred.resolve(response);
                        },
                        function (error) {
                            deferred.reject(error);
                        },
                        uploadOptions
                    );
                } else {
                    deferred.reject('There\'s not URI');
                }

                return deferred.promise;
            }
        }, {
            fromFile: function (file) {
                return new CordovaFile({
                    file: file,
                    contentType: file.type
                });
            },
            fromUri: function (uri) {
                return new CordovaFile({
                    uri: uri
                });
            }
        });

        return CordovaFile;
    });<|endoftext|>


<commit_before>// Model CLASS
// ===============================
/**
 * Main object storing data model and emitting events
 * ---------
 * Access Node object stored in jQuery objects
 * @param el {jQuery|Node}
 * @return {Node}
 */
function Model(el) {
    if (!(this instanceof Model)) {
        return Model.getModel(el);
    }

    this.root = null;
    this.$ = $(this);
}

$.extend(Model.prototype, {
    trigger: function(type) {
        this.$.triggerHandler(type, Array.prototype.slice.call(arguments, 1));
        return this;
    },

    on: function() {
        this.$.on.apply(this.$, Array.prototype.slice.call(arguments));
        return this;
    },

    off: function() {
        this.$.off.apply(this.$, Array.prototype.slice.call(arguments));
        return this;
    },

    once: function() {
        this.$.one.apply(this.$, Array.prototype.slice.call(arguments));
        return this;
    }
});

/**
 * Access Node object stored in jQuery objects
 * @param el {jQuery|Node}
 * @return {Node}
 */
Model.getModel = function(el) {
    if (!el) {
        return null;
    }
    else if (el instanceof Node) {
        return el;
    }
    else {
        return $(el).data('queryBuilderModel');
    }
};

/*
 * Define Node properties with getter and setter
 * Update events are emitted in the setter through root Model (if any)
 */
function defineModelProperties(obj, fields) {
    fields.forEach(function(field) {
        Object.defineProperty(obj.prototype, field, {
            enumerable: true,
            get: function() {
                return this.__[field];
            },
            set: function(value) {
                var oldValue = (this.__[field] !== null && typeof this.__[field] == 'object') ?
                  $.extend({}, this.__[field]) :
                  this.__[field];

                this.__[field] = value;

                if (this.model !== null) {
                    this.model.trigger('update', this, field, value, oldValue);
                }
            }
        });
    });
}

// Node abstract CLASS
// ===============================
/**
 * @param {Node}
 * @param {jQuery}
 */
var Node = function(parent, $el) {
    if (!(this instanceof Node)) {
        return new Node();
    }

    Object.defineProperty(this, '__', { value: {} });

    $el.data('queryBuilderModel', this);

    this.__.level = 1;
    this.__.error = null;
    this.__.data = undefined;
    this.$el = $el;
    this.id = $el[0].id;
    this.model = null;
    this.parent = parent;
};

defineModelProperties(Node, ['level', 'error', 'data', 'flags']);

Object.defineProperty(Node.prototype, 'parent', {
    enumerable: true,
    get: function() {
        return this.__.parent;
    },
    set: function(value) {
        this.__.parent = value;
        this.level = value === null ? 1 : value.level + 1;
        this.model = value === null ? null : value.model;
    }
});

/**
 * Check if this Node is the root
 * @return {boolean}
 */
Node.prototype.isRoot = function() {
    return (this.level === 1);
};

/**
 * Return node position inside parent
 * @return {int}
 */
Node.prototype.getPos = function() {
    if (this.isRoot()) {
        return -1;
    }
    else {
        return this.parent.getNodePos(this);
    }
};

/**
 * Delete self
 */
Node.prototype.drop = function() {
    var model = this.model;

    if (!this.isRoot()) {
        this.parent._removeNode(this);
    }

    if (model !== null) {
        model.trigger('drop', this);
    }
};

/**
 * Move itself after another Node
 * @param {Node}
 * @return {Node} self
 */
Node.prototype.moveAfter = function(node) {
    if (this.isRoot()) return;

    this._move(node.parent, node.getPos() + 1);

    return this;
};

/**
 * Move itself at the beginning of parent or another Group
 * @param {Group,optional}
 * @return {Node} self
 */
Node.prototype.moveAtBegin = function(target) {
    if (this.isRoot()) return;

    if (target === undefined) {
        target = this.parent;
    }

    this._move(target, 0);

    return this;
};

/**
 * Move itself at the end of parent or another Group
 * @param {Group,optional}
 * @return {Node} self
 */
Node.prototype.moveAtEnd = function(target) {
    if (this.isRoot()) return;

    if (target === undefined) {
        target = this.parent;
    }

    this._move(target, target.length());

    return this;
};

/**
 * Move itself at specific position of Group
 * @param {Group}
 * @param {int}
 */
Node.prototype._move = function(group, index) {
    this.parent._removeNode(this);
    group._appendNode(this, index, false);

    if (this.model !== null) {
        this.model.trigger('move', this, group, index);
    }
};

// GROUP CLASS
// ===============================
/**
 * @param {Group}
 * @param {jQuery}
 */
var Group = function(parent, $el) {
    if (!(this instanceof Group)) {
        return new Group(parent, $el);
    }

    Node.call(this, parent, $el);

    this.rules = [];
    this.__.condition = null;
};

Group.prototype = Object.create(Node.prototype);
Group.prototype.constructor = Group;

defineModelProperties(Group, ['condition']);

/**
 * Empty the Group
 */
Group.prototype.empty = function() {
    this.each('reverse', function(rule) {
        rule.drop();
    }, function(group) {
        group.drop();
    });
};

/**
 * Delete self
 */
Group.prototype.drop = function() {
    this.empty();
    Node.prototype.drop.call(this);
};

/**
 * Return the number of children
 * @return {int}
 */
Group.prototype.length = function() {
    return this.rules.length;
};

/**
 * Add a Node at specified index
 * @param {Node}
 * @param {int,optional}
 * @param {boolean,optional}
 * @return {Node} the inserted node
 */
Group.prototype._appendNode = function(node, index, trigger) {
    if (index === undefined) {
        index = this.length();
    }

    this.rules.splice(index, 0, node);
    node.parent = this;

    if (trigger && this.model !== null) {
        this.model.trigger('add', node, index);
    }

    return node;
};

/**
 * Add a Group by jQuery element at specified index
 * @param {jQuery}
 * @param {int,optional}
 * @return {Group} the inserted group
 */
Group.prototype.addGroup = function($el, index) {
    return this._appendNode(new Group(this, $el), index, true);
};

/**
 * Add a Rule by jQuery element at specified index
 * @param {jQuery}
 * @param {int,optional}
 * @return {Rule} the inserted rule
 */
Group.prototype.addRule = function($el, index) {
    return this._appendNode(new Rule(this, $el), index, true);
};

/**
 * Delete a specific Node
 * @param {Node}
 * @return {Group} self
 */
Group.prototype._removeNode = function(node) {
    var index = this.getNodePos(node);
    if (index !== -1) {
        node.parent = null;
        this.rules.splice(index, 1);
    }

    return this;
};

/**
 * Return position of a child Node
 * @param {Node}
 * @return {int}
 */
Group.prototype.getNodePos = function(node) {
    return this.rules.indexOf(node);
};

/**
 * Iterate over all Nodes
 * @param {boolean,optional} iterate in reverse order, required if you delete nodes
 * @param {function} callback for Rules
 * @param {function,optional} callback for Groups
 * @return {boolean}
 */
Group.prototype.each = function(reverse, cbRule, cbGroup, context) {
    if (typeof reverse == 'function') {
        context = cbGroup;
        cbGroup = cbRule;
        cbRule = reverse;
        reverse = false;
    }
    context = context === undefined ? null : context;

    var i = reverse ? this.rules.length - 1 : 0;
    var l = reverse ? 0 : this.rules.length - 1;
    var c = reverse ? -1 : 1;
    var next = function() { return reverse ? i >= l : i <= l; };
    var stop = false;

    for (; next(); i+= c) {
        if (this.rules[i] instanceof Group) {
            if (cbGroup !== undefined) {
                stop = cbGroup.call(context, this.rules[i]) === false;
            }
        }
        else {
            stop = cbRule.call(context, this.rules[i]) === false;
        }

        if (stop) {
            break;
        }
    }

    return !stop;
};

/**
 * Return true if the group contains a particular Node
 * @param {Node}
 * @param {boolean,optional} recursive search
 * @return {boolean}
 */
Group.prototype.contains = function(node, deep) {
    if (this.getNodePos(node) !== -1) {
        return true;
    }
    else if (!deep) {
        return false;
    }
    else {
        // the loop will return with false as soon as the Node is found
        return !this.each(function(rule) {
            return true;
        }, function(group) {
            return !group.contains(node, true);
        });
    }
};

// RULE CLASS
// ===============================
/**
 * @param {Group}
 * @param {jQuery}
 */
var Rule = function(parent, $el) {
    if (!(this instanceof Rule)) {
        return new Rule(parent, $el);
    }

    Node.call(this, parent, $el);

    this.__.filter = null;
    this.__.operator = null;
    this.__.flags = {};
    this.__.value = undefined;
};

Rule.prototype = Object.create(Node.prototype);
Rule.prototype.constructor = Rule;

defineModelProperties(Rule, ['filter', 'operator', 'value']);

// EXPORT
// ===============================
QueryBuilder.Group = Group;
QueryBuilder.Rule = Rule;
<commit_msg>Fix #285 sortable drop element glitch<commit_after>// Model CLASS
// ===============================
/**
 * Main object storing data model and emitting events
 * ---------
 * Access Node object stored in jQuery objects
 * @param el {jQuery|Node}
 * @return {Node}
 */
function Model(el) {
    if (!(this instanceof Model)) {
        return Model.getModel(el);
    }

    this.root = null;
    this.$ = $(this);
}

$.extend(Model.prototype, {
    trigger: function(type) {
        this.$.triggerHandler(type, Array.prototype.slice.call(arguments, 1));
        return this;
    },

    on: function() {
        this.$.on.apply(this.$, Array.prototype.slice.call(arguments));
        return this;
    },

    off: function() {
        this.$.off.apply(this.$, Array.prototype.slice.call(arguments));
        return this;
    },

    once: function() {
        this.$.one.apply(this.$, Array.prototype.slice.call(arguments));
        return this;
    }
});

/**
 * Access Node object stored in jQuery objects
 * @param el {jQuery|Node}
 * @return {Node}
 */
Model.getModel = function(el) {
    if (!el) {
        return null;
    }
    else if (el instanceof Node) {
        return el;
    }
    else {
        return $(el).data('queryBuilderModel');
    }
};

/*
 * Define Node properties with getter and setter
 * Update events are emitted in the setter through root Model (if any)
 */
function defineModelProperties(obj, fields) {
    fields.forEach(function(field) {
        Object.defineProperty(obj.prototype, field, {
            enumerable: true,
            get: function() {
                return this.__[field];
            },
            set: function(value) {
                var oldValue = (this.__[field] !== null && typeof this.__[field] == 'object') ?
                  $.extend({}, this.__[field]) :
                  this.__[field];

                this.__[field] = value;

                if (this.model !== null) {
                    this.model.trigger('update', this, field, value, oldValue);
                }
            }
        });
    });
}

// Node abstract CLASS
// ===============================
/**
 * @param {Node}
 * @param {jQuery}
 */
var Node = function(parent, $el) {
    if (!(this instanceof Node)) {
        return new Node();
    }

    Object.defineProperty(this, '__', { value: {} });

    $el.data('queryBuilderModel', this);

    this.__.level = 1;
    this.__.error = null;
    this.__.data = undefined;
    this.$el = $el;
    this.id = $el[0].id;
    this.model = null;
    this.parent = parent;
};

defineModelProperties(Node, ['level', 'error', 'data', 'flags']);

Object.defineProperty(Node.prototype, 'parent', {
    enumerable: true,
    get: function() {
        return this.__.parent;
    },
    set: function(value) {
        this.__.parent = value;
        this.level = value === null ? 1 : value.level + 1;
        this.model = value === null ? null : value.model;
    }
});

/**
 * Check if this Node is the root
 * @return {boolean}
 */
Node.prototype.isRoot = function() {
    return (this.level === 1);
};

/**
 * Return node position inside parent
 * @return {int}
 */
Node.prototype.getPos = function() {
    if (this.isRoot()) {
        return -1;
    }
    else {
        return this.parent.getNodePos(this);
    }
};

/**
 * Delete self
 */
Node.prototype.drop = function() {
    var model = this.model;

    if (!this.isRoot()) {
        this.parent._removeNode(this);
    }

    if (model !== null) {
        model.trigger('drop', this);
    }
};

/**
 * Move itself after another Node
 * @param {Node}
 * @return {Node} self
 */
Node.prototype.moveAfter = function(node) {
    if (this.isRoot()) return;

    this._move(node.parent, node.getPos() + 1);

    return this;
};

/**
 * Move itself at the beginning of parent or another Group
 * @param {Group,optional}
 * @return {Node} self
 */
Node.prototype.moveAtBegin = function(target) {
    if (this.isRoot()) return;

    if (target === undefined) {
        target = this.parent;
    }

    this._move(target, 0);

    return this;
};

/**
 * Move itself at the end of parent or another Group
 * @param {Group,optional}
 * @return {Node} self
 */
Node.prototype.moveAtEnd = function(target) {
    if (this.isRoot()) return;

    if (target === undefined) {
        target = this.parent;
    }

    this._move(target, target.length() - 1);

    return this;
};

/**
 * Move itself at specific position of Group
 * @param {Group}
 * @param {int}
 */
Node.prototype._move = function(group, index) {
    this.parent._removeNode(this);
    group._appendNode(this, index, false);

    if (this.model !== null) {
        this.model.trigger('move', this, group, index);
    }
};

// GROUP CLASS
// ===============================
/**
 * @param {Group}
 * @param {jQuery}
 */
var Group = function(parent, $el) {
    if (!(this instanceof Group)) {
        return new Group(parent, $el);
    }

    Node.call(this, parent, $el);

    this.rules = [];
    this.__.condition = null;
};

Group.prototype = Object.create(Node.prototype);
Group.prototype.constructor = Group;

defineModelProperties(Group, ['condition']);

/**
 * Empty the Group
 */
Group.prototype.empty = function() {
    this.each('reverse', function(rule) {
        rule.drop();
    }, function(group) {
        group.drop();
    });
};

/**
 * Delete self
 */
Group.prototype.drop = function() {
    this.empty();
    Node.prototype.drop.call(this);
};

/**
 * Return the number of children
 * @return {int}
 */
Group.prototype.length = function() {
    return this.rules.length;
};

/**
 * Add a Node at specified index
 * @param {Node}
 * @param {int,optional}
 * @param {boolean,optional}
 * @return {Node} the inserted node
 */
Group.prototype._appendNode = function(node, index, trigger) {
    if (index === undefined) {
        index = this.length();
    }

    this.rules.splice(index, 0, node);
    node.parent = this;

    if (trigger && this.model !== null) {
        this.model.trigger('add', node, index);
    }

    return node;
};

/**
 * Add a Group by jQuery element at specified index
 * @param {jQuery}
 * @param {int,optional}
 * @return {Group} the inserted group
 */
Group.prototype.addGroup = function($el, index) {
    return this._appendNode(new Group(this, $el), index, true);
};

/**
 * Add a Rule by jQuery element at specified index
 * @param {jQuery}
 * @param {int,optional}
 * @return {Rule} the inserted rule
 */
Group.prototype.addRule = function($el, index) {
    return this._appendNode(new Rule(this, $el), index, true);
};

/**
 * Delete a specific Node
 * @param {Node}
 * @return {Group} self
 */
Group.prototype._removeNode = function(node) {
    var index = this.getNodePos(node);
    if (index !== -1) {
        node.parent = null;
        this.rules.splice(index, 1);
    }

    return this;
};

/**
 * Return position of a child Node
 * @param {Node}
 * @return {int}
 */
Group.prototype.getNodePos = function(node) {
    return this.rules.indexOf(node);
};

/**
 * Iterate over all Nodes
 * @param {boolean,optional} iterate in reverse order, required if you delete nodes
 * @param {function} callback for Rules
 * @param {function,optional} callback for Groups
 * @return {boolean}
 */
Group.prototype.each = function(reverse, cbRule, cbGroup, context) {
    if (typeof reverse == 'function') {
        context = cbGroup;
        cbGroup = cbRule;
        cbRule = reverse;
        reverse = false;
    }
    context = context === undefined ? null : context;

    var i = reverse ? this.rules.length - 1 : 0;
    var l = reverse ? 0 : this.rules.length - 1;
    var c = reverse ? -1 : 1;
    var next = function() { return reverse ? i >= l : i <= l; };
    var stop = false;

    for (; next(); i+= c) {
        if (this.rules[i] instanceof Group) {
            if (cbGroup !== undefined) {
                stop = cbGroup.call(context, this.rules[i]) === false;
            }
        }
        else {
            stop = cbRule.call(context, this.rules[i]) === false;
        }

        if (stop) {
            break;
        }
    }

    return !stop;
};

/**
 * Return true if the group contains a particular Node
 * @param {Node}
 * @param {boolean,optional} recursive search
 * @return {boolean}
 */
Group.prototype.contains = function(node, deep) {
    if (this.getNodePos(node) !== -1) {
        return true;
    }
    else if (!deep) {
        return false;
    }
    else {
        // the loop will return with false as soon as the Node is found
        return !this.each(function(rule) {
            return true;
        }, function(group) {
            return !group.contains(node, true);
        });
    }
};

// RULE CLASS
// ===============================
/**
 * @param {Group}
 * @param {jQuery}
 */
var Rule = function(parent, $el) {
    if (!(this instanceof Rule)) {
        return new Rule(parent, $el);
    }

    Node.call(this, parent, $el);

    this.__.filter = null;
    this.__.operator = null;
    this.__.flags = {};
    this.__.value = undefined;
};

Rule.prototype = Object.create(Node.prototype);
Rule.prototype.constructor = Rule;

defineModelProperties(Rule, ['filter', 'operator', 'value']);

// EXPORT
// ===============================
QueryBuilder.Group = Group;
QueryBuilder.Rule = Rule;
<|endoftext|>