<commit_before>/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen(val) {
  let len = 0
  for (let i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/ig) != null) {
      len += 1
    } else { len += 0.5 }
  }
  return Math.floor(len)
}

export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function param(json) {
  if (!json) return ''
  return cleanArray(Object.keys(json).map(key => {
    if (json[key] === undefined) return ''
    return encodeURIComponent(key) + '=' +
            encodeURIComponent(json[key])
  })).join('&')
}

export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}

export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

export function objectMerge(target, source) {
  /* Merges two  objects,
     giving the last one precedence */

  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

export function scrollTo(element, to, duration) {
  if (duration <= 0) return
  const difference = to - element.scrollTop
  const perTick = difference / duration * 10
  setTimeout(() => {
    console.log(new Date())
    element.scrollTop = element.scrollTop + perTick
    if (element.scrollTop === to) return
    scrollTo(element, to, duration - 10)
  }, 10)
}

export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

export const pickerOptions = [
  {
    text: '今天',
    onClick(picker) {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      end.setTime(start.getTime())
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一周',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }]

export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = source[keys].constructor === Array ? [] : {}
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}
<commit_msg>perf[utils.js]: Add code comments to deepClone and remove redundant code<commit_after>/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

// 格式化时间
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen(val) {
  let len = 0
  for (let i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/ig) != null) {
      len += 1
    } else { len += 0.5 }
  }
  return Math.floor(len)
}

export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function param(json) {
  if (!json) return ''
  return cleanArray(Object.keys(json).map(key => {
    if (json[key] === undefined) return ''
    return encodeURIComponent(key) + '=' +
            encodeURIComponent(json[key])
  })).join('&')
}

export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}

export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

export function objectMerge(target, source) {
  /* Merges two  objects,
     giving the last one precedence */

  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

export function scrollTo(element, to, duration) {
  if (duration <= 0) return
  const difference = to - element.scrollTop
  const perTick = difference / duration * 10
  setTimeout(() => {
    console.log(new Date())
    element.scrollTop = element.scrollTop + perTick
    if (element.scrollTop === to) return
    scrollTo(element, to, duration - 10)
  }, 10)
}

export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

export const pickerOptions = [
  {
    text: '今天',
    onClick(picker) {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      end.setTime(start.getTime())
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一周',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近三个月',
    onClick(picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }]

export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}
<|endoftext|>


<commit_before>import Events from 'events';

class Store extends Events.EventEmitter {

  constructor(Dispatcher, data) {
    super();

    var _store = this;

    this.data = data;

    this.dispatchToken = Dispatcher.register(this.dispatcherCallback);
  }

  addChangeListener = (callback) => {
    this.on('change', callback);
  };

  removeChangeListener = (callback) => {
    this.removeListener('change', callback);
  };

  getState = () => {
    return this.data;
  };

  dispatcherCallback = (action) => {
    if (this[action.actionType]) {
      this[action.actionType].call(this, action)
      this.emit('change');
    }
  }
}

export default Store
<commit_msg>removed extraneous assigment<commit_after>import Events from 'events';

class Store extends Events.EventEmitter {

  constructor(Dispatcher, data) {
    super();

    this.data = data;

    this.dispatchToken = Dispatcher.register(this.dispatcherCallback);
  }

  addChangeListener = (callback) => {
    this.on('change', callback);
  };

  removeChangeListener = (callback) => {
    this.removeListener('change', callback);
  };

  getState = () => {
    return this.data;
  };

  dispatcherCallback = (action) => {
    if (this[action.actionType]) {
      this[action.actionType].call(this, action)
      this.emit('change');
    }
  }
}

export default Store
<|endoftext|>


<commit_before>export function trim(string){
  return String(string).replace(/^\s+|\s+$/g, '');
}

export function exists(input){
  return input !== null && input !== undefined
}

export function itemsEqual(a,b){
  //perhaps an immutable library would not require such horrors?
  if(JSON.stringify(a)===JSON.stringify(b)){
    return true
  }
  return false
}

/*converts input data to array if it is not already an array*/
export function toArray(data){
  if(!data) return []
  if(data.constructor !== Array) return [data]
  return data
}

/* JSON parse that always returns an object*/
export function safeJSONParse(str){
  try{
    return JSON.parse(str) || {} //from cycle.js
  }catch(error){
    throw new Error("Error parsing data",JSON.stringify(str))
  }
}

//file utils ??
export function getExtension(fname){
  return fname.substr((~-fname.lastIndexOf(".") >>> 0) + 2).toLowerCase()
}

//TODO: taken from three.js ,do correct attribution
export function generateUUID() {

  // http://www.broofa.com/Tools/Math.uuid.htm

  let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  let uuid = new Array( 36 );
  let rnd = 0, r;

  return function () {

    for ( let i = 0; i < 36; i ++ ) {

      if ( i == 8 || i == 13 || i == 18 || i == 23 ) {

        uuid[ i ] = '-';

      } else if ( i == 14 ) {

        uuid[ i ] = '4';

      } else {

        if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];

      }
    }
    return uuid.join( '' )
  }()
}<commit_msg>feature(utils): added isEmpty utiity to determine if a string is empty etc<commit_after>export function trim(string){
  return String(string).replace(/^\s+|\s+$/g, '');
}

export function exists(input){
  return input !== null && input !== undefined
}

//utiity to determine if a string is empty, null, or full of whitespaces
export function isEmpty(str) {
    return (!str || /^\s*$/.test(str) || str.length === 0 || !str.trim())
}

export function itemsEqual(a,b){
  //perhaps an immutable library would not require such horrors?
  if(JSON.stringify(a)===JSON.stringify(b)){
    return true
  }
  return false
}

/*converts input data to array if it is not already an array*/
export function toArray(data){
  if(!data) return []
  if(data.constructor !== Array) return [data]
  return data
}

/* JSON parse that always returns an object*/
export function safeJSONParse(str){
  try{
    return JSON.parse(str) || {} //from cycle.js
  }catch(error){
    throw new Error("Error parsing data",JSON.stringify(str))
  }
}

//file utils ??
export function getExtension(fname){
  return fname.substr((~-fname.lastIndexOf(".") >>> 0) + 2).toLowerCase()
}

//TODO: taken from three.js ,do correct attribution
export function generateUUID() {

  // http://www.broofa.com/Tools/Math.uuid.htm

  let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  let uuid = new Array( 36 );
  let rnd = 0, r;

  return function () {

    for ( let i = 0; i < 36; i ++ ) {

      if ( i == 8 || i == 13 || i == 18 || i == 23 ) {

        uuid[ i ] = '-';

      } else if ( i == 14 ) {

        uuid[ i ] = '4';

      } else {

        if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[ i ] = chars[ ( i == 19 ) ? ( r & 0x3 ) | 0x8 : r ];

      }
    }
    return uuid.join( '' )
  }()
}<|endoftext|>


<commit_before>/**
 * Init wrapper for the core module.
 * @param {Object} The Object that the library gets attached to in library.init.js. If the library was not loaded with an AMD loader such as require.js, this is the global Object.
 */
function initVlilleCore(context) {
    'use strict';

    /**
     * @constructor
     * @param  {Object} opt_config [description]
     * @return {Vlille}            [description]
     */
    function Vlille(opt_config) {
        // enforces new
        if (!(this instanceof Vlille)) {
            return new Vlille(opt_config);
        }

        opt_config = opt_config || {};

        if (!opt_config.apiProxyUrl) {
            throw new Error('You need tp provide a proxy URL.');
        }

        this.apiProxyBase = opt_config.apiProxyUrl;

        return this;
    }

    context.Vlille = Vlille;

    /**
     * Privates
     */

    /**
     *
     * @param  {Document} xml [description]
     * @return {Object}       [description]
     */
    function xmlStationsToJson(xml) {
        var i,
            j,
            len,
            len2,
            markers = xml.childNodes[0].children || [],
            attributes,
            jsonMarker,
            jsonArray = [];

        // imperative way
        for (i = 0, len = markers.length; i < len; i += 1) {
            jsonMarker = {};
            attributes = markers[i].attributes;

            for (j = 0, len2 = attributes.length; j < len2; j += 1) {
                jsonMarker[attributes[j].name] = attributes[j].value;
            }

            jsonArray.push(jsonMarker);
        }

        return jsonArray;
    }

    /**
     *
     * @param  {Document} xmlNode [description]
     * @return {Object}           [description]
     */
    function xmlStationToJson(xml) {
        var i,
            len,
            stationData = xml.childNodes[0].children || [],
            jsonStation = {};

        for (i = 0, len = stationData.length; i < len; i += 1) {
            jsonStation[stationData[i].nodeName] = stationData[i].innerHTML;
        }

        return jsonStation;
    }

    /**
     * Publics
     */

    /**
     * Gets full stations list.
     * @return {Promise} [description]
     */
    Vlille.prototype.stations = function () {
        return Vlille.requestXML(this.apiProxyBase + 'xml-stations.aspx', null).then(function (xml) {
            return xmlStationsToJson(xml);
        });
    };

    /**
     * Gets informations about the station whit the given `id`.
     * @param  {String} id [description]
     * @return {Promise}   [description]
     */
    Vlille.prototype.station = function (id) {
        var params = {
            borne: id
        };

        return Vlille.requestXML(this.apiProxyBase + 'xml-station.aspx', params).then(function (xml) {
            return xmlStationToJson(xml);
        });
    };

    /**
     * Gets closest stations using Haversine formula.
     * The second parameter `max` (default value = 3) allow one to configure the maximum number of results.
     * @param  {Object} coord [description]
     * @param  {Int} max      [description]
     * @return {Promise}      [description]
     */
    Vlille.prototype.closestStations = function (coords, max) {
        if (max === undefined) {
            max = 3;
        }

        return this.stations().then(function (stations) {
            var closetStations = stations
                // computes distances
                .map(function (station) {
                    var stationCoords = {
                        lat: parseFloat(station.lat),
                        lon: parseFloat(station.lng)
                    };

                    station.distance = Vlille.haversineDistance(coords, stationCoords);

                    return station;
                })
                // sort by distance
                .sort(function (a, b) {
                    return a.distance - b.distance;
                });

            if (closetStations.length > max) {
                closetStations.length = max;
            }

            return closetStations;
        });
    };
}<commit_msg>Fix typo<commit_after>/**
 * Init wrapper for the core module.
 * @param {Object} The Object that the library gets attached to in library.init.js. If the library was not loaded with an AMD loader such as require.js, this is the global Object.
 */
function initVlilleCore(context) {
    'use strict';

    /**
     * @constructor
     * @param  {Object} opt_config [description]
     * @return {Vlille}            [description]
     */
    function Vlille(opt_config) {
        // enforces new
        if (!(this instanceof Vlille)) {
            return new Vlille(opt_config);
        }

        opt_config = opt_config || {};

        if (!opt_config.apiProxyUrl) {
            throw new Error('You have to provide a proxy URL.');
        }

        this.apiProxyBase = opt_config.apiProxyUrl;

        return this;
    }

    context.Vlille = Vlille;

    /**
     * Privates
     */

    /**
     *
     * @param  {Document} xml [description]
     * @return {Object}       [description]
     */
    function xmlStationsToJson(xml) {
        var i,
            j,
            len,
            len2,
            markers = xml.childNodes[0].children || [],
            attributes,
            jsonMarker,
            jsonArray = [];

        // imperative way
        for (i = 0, len = markers.length; i < len; i += 1) {
            jsonMarker = {};
            attributes = markers[i].attributes;

            for (j = 0, len2 = attributes.length; j < len2; j += 1) {
                jsonMarker[attributes[j].name] = attributes[j].value;
            }

            jsonArray.push(jsonMarker);
        }

        return jsonArray;
    }

    /**
     *
     * @param  {Document} xmlNode [description]
     * @return {Object}           [description]
     */
    function xmlStationToJson(xml) {
        var i,
            len,
            stationData = xml.childNodes[0].children || [],
            jsonStation = {};

        for (i = 0, len = stationData.length; i < len; i += 1) {
            jsonStation[stationData[i].nodeName] = stationData[i].innerHTML;
        }

        return jsonStation;
    }

    /**
     * Publics
     */

    /**
     * Gets full stations list.
     * @return {Promise} [description]
     */
    Vlille.prototype.stations = function () {
        return Vlille.requestXML(this.apiProxyBase + 'xml-stations.aspx', null).then(function (xml) {
            return xmlStationsToJson(xml);
        });
    };

    /**
     * Gets informations about the station whit the given `id`.
     * @param  {String} id [description]
     * @return {Promise}   [description]
     */
    Vlille.prototype.station = function (id) {
        var params = {
            borne: id
        };

        return Vlille.requestXML(this.apiProxyBase + 'xml-station.aspx', params).then(function (xml) {
            return xmlStationToJson(xml);
        });
    };

    /**
     * Gets closest stations using Haversine formula.
     * The second parameter `max` (default value = 3) allow one to configure the maximum number of results.
     * @param  {Object} coord [description]
     * @param  {Int} max      [description]
     * @return {Promise}      [description]
     */
    Vlille.prototype.closestStations = function (coords, max) {
        if (max === undefined) {
            max = 3;
        }

        return this.stations().then(function (stations) {
            var closetStations = stations
                // computes distances
                .map(function (station) {
                    var stationCoords = {
                        lat: parseFloat(station.lat),
                        lon: parseFloat(station.lng)
                    };

                    station.distance = Vlille.haversineDistance(coords, stationCoords);

                    return station;
                })
                // sort by distance
                .sort(function (a, b) {
                    return a.distance - b.distance;
                });

            if (closetStations.length > max) {
                closetStations.length = max;
            }

            return closetStations;
        });
    };
}<|endoftext|>


<commit_before>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
	// cms
	.sass('resources/assets/sass/cms.scss', 'public/assets/cms/css/cms.css')

    // frontend
    .sass('resources/assets/sass/frontend.scss', 'public/assets/frontend/css/frontend.css')

    // wysiwyg
    .sass('resources/assets/sass/wysiwyg.scss', 'public/assets/cms/css/wysiwyg.css')

    .scripts([

        'resources/assets/js/gateway.js',
        'resources/assets/js/model.js',
        'resources/assets/js/menu.js',
        'resources/assets/js/input/multi-checkbox.js',
        'resources/assets/js/input/aspect-ratio.js',
        'resources/assets/js/input/labeled-multi-checkbox.js',
        'resources/assets/js/input/gallery.js',
        'resources/assets/js/input/cropper.js',
        'resources/assets/js/input/image.js',
        'resources/assets/js/cms.js',
    ], 'public/assets/cms/js/cms.js')

    // auth
    .scripts([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
        'resources/assets/js/auth.js',
    ], 'public/assets/cms/js/auth.js');<commit_msg>forgot to put back the js dependencies<commit_after>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
	// cms
	.sass('resources/assets/sass/cms.scss', 'public/assets/cms/css/cms.css')

    // frontend
    .sass('resources/assets/sass/frontend.scss', 'public/assets/frontend/css/frontend.css')

    // wysiwyg
    .sass('resources/assets/sass/wysiwyg.scss', 'public/assets/cms/css/wysiwyg.css')

    .scripts([
        '../../../node_modules/jquery/dist/jquery.min.js',
        '../../../node_modules/jqueryui/jquery-ui.min.js',
        '../../../node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
        '../../../node_modules/moment/min/moment.min.js',
        '../../../node_modules/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js',
        '../../../node_modules/q/q.js',
        '../../../node_modules/cropper/dist/cropper.min.js',
        '../../../node_modules/dropzone/dist/min/dropzone.min.js',
        '../../../node_modules/nestedSortable/jquery.mjs.nestedSortable.js',
        'resources/assets/js/gateway.js',
        'resources/assets/js/model.js',
        'resources/assets/js/menu.js',
        'resources/assets/js/input/multi-checkbox.js',
        'resources/assets/js/input/aspect-ratio.js',
        'resources/assets/js/input/labeled-multi-checkbox.js',
        'resources/assets/js/input/gallery.js',
        'resources/assets/js/input/cropper.js',
        'resources/assets/js/input/image.js',
        'resources/assets/js/cms.js',
    ], 'public/assets/cms/js/cms.js')

    // auth
    .scripts([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
        'resources/assets/js/auth.js',
    ], 'public/assets/cms/js/auth.js');<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch'

import config from './config'

async function fetchJson(url, options) {
  const response = await fetch(url, options)
  if (response.status < 200 || response.status >= 300) {
    throw new Error(`'${url}' returned the unexpected return code: '${response.status}'.`)
  }
  const data = await response.json()
  return {
    data,
    'country-package': response.headers.get('country-package'),
    'country-package-version': response.headers.get('country-package-version'),
  }
}

export function fetchParameters(apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/parameters`)
}

export function fetchVariables(apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/variables`)
}

export function fetchParameter(parameterId, apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/parameter/${parameterId}`)
}

export function fetchVariable(variableId, apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/variable/${variableId}`)
}

export function fetchSwagger(apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/spec`)
}
<commit_msg>Improve error is API is dead<commit_after>import fetch from 'isomorphic-fetch'

import config from './config'

async function fetchJson(url, options) {
  const response = await fetch(url, options)
    .catch(() => { throw new Error(`Could not fetch '${url}'.`)})
  if (response.status < 200 || response.status >= 300) {
    throw new Error(`'${url}' returned the unexpected return code: '${response.status}'.`)
  }
  const data = await response.json()
  return {
    data,
    'country-package': response.headers.get('country-package'),
    'country-package-version': response.headers.get('country-package-version'),
  }
}

export function fetchParameters(apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/parameters`)
}

export function fetchVariables(apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/variables`)
}

export function fetchParameter(parameterId, apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/parameter/${parameterId}`)
}

export function fetchVariable(variableId, apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/variable/${variableId}`)
}

export function fetchSwagger(apiBaseUrl = config.apiBaseUrl) {
  return fetchJson(`${apiBaseUrl}/spec`)
}
<|endoftext|>


<commit_before>var service = new rpc.ServiceProxy("/jsonrpc", {methods: ['nodeInfo','connectTo','listGateways','pollCallStatus','listSessions','startScan','getGraphSince','status']});

function logAppendMessage(type, msg)
{
	if($("#log div").length >= 5)
		$("#log").children().first().remove();
	$("#log").append($("
").text(msg));
}

function nonBlockingCallWrapper(result, callback)
{
	if(result.callId)
	{
		var id = result.callId;
		setTimeout(function(){
			service.pollCallStatus({
				params: [id],
				onSuccess: function(result) {
					nonBlockingCallWrapper(result, callback);
				},
				onException: function(e) {
					logAppendMessage('danger', e);
					return true;
				}
			});
		},1000);
	}
	else
		callback(result);
}

function bootstrap()
{
	if($("#gateways").length>0)
		reloadGateways();
	if($("#sessions").length>0)
		reloadSessions();
	if($("#status").length>0)
		reloadStatus();
	if($("#startScan").length>0)
		$("#startScan").click(startScan);
	if($("#network").length>0)
		startNetworkGraph();
}

var nodeInfo;
$(document).ready(function(){
	$("#gateways").hide();
	$("#sessions").hide();
	service.nodeInfo({
		params: [],
		onSuccess: function(result) {
			nonBlockingCallWrapper(result, function(result) {
				if(result.success==true)
				{
					nodeInfo = result;

					$(document).prop('title', nodeInfo.name);
					$('.navbar-brand').text(nodeInfo.name);

					if(nodeInfo.gateway || !nodeInfo.authorized)
					{
						$("#gateways").remove();
					}
					else
					{
						$("#gateways").show();
					}

					if(nodeInfo.authorized)
					{
						$("#sessions").show();
					}
					else
					{
						$("#sessions").remove();
					}

					bootstrap();
				}
				else
				{
					logAppendMessage('danger', result.errorMsg);
				}
			});
		},
		onException: function(e) {
			logAppendMessage('danger', e);
			return true;
		}
	});
});
<commit_msg>Bug fix<commit_after>var service = new rpc.ServiceProxy("/jsonrpc", {methods: ['nodeInfo','connectTo','disconnect','listGateways','pollCallStatus','listSessions','startScan','getGraphSince','status']});

function logAppendMessage(type, msg)
{
	if($("#log div").length >= 5)
		$("#log").children().first().remove();
	$("#log").append($("
").text(msg));
}

function nonBlockingCallWrapper(result, callback)
{
	if(result.callId)
	{
		var id = result.callId;
		setTimeout(function(){
			service.pollCallStatus({
				params: [id],
				onSuccess: function(result) {
					nonBlockingCallWrapper(result, callback);
				},
				onException: function(e) {
					logAppendMessage('danger', e);
					return true;
				}
			});
		},1000);
	}
	else
		callback(result);
}

function bootstrap()
{
	if($("#gateways").length>0)
		reloadGateways();
	if($("#sessions").length>0)
		reloadSessions();
	if($("#status").length>0)
		reloadStatus();
	if($("#startScan").length>0)
		$("#startScan").click(startScan);
	if($("#network").length>0)
		startNetworkGraph();
}

var nodeInfo;
$(document).ready(function(){
	$("#gateways").hide();
	$("#sessions").hide();
	service.nodeInfo({
		params: [],
		onSuccess: function(result) {
			nonBlockingCallWrapper(result, function(result) {
				if(result.success==true)
				{
					nodeInfo = result;

					$(document).prop('title', nodeInfo.name);
					$('.navbar-brand').text(nodeInfo.name);

					if(nodeInfo.gateway || !nodeInfo.authorized)
					{
						$("#gateways").remove();
					}
					else
					{
						$("#gateways").show();
					}

					if(nodeInfo.authorized)
					{
						$("#sessions").show();
					}
					else
					{
						$("#sessions").remove();
					}

					bootstrap();
				}
				else
				{
					logAppendMessage('danger', result.errorMsg);
				}
			});
		},
		onException: function(e) {
			logAppendMessage('danger', e);
			return true;
		}
	});
});
<|endoftext|>


<commit_before>const chalk = require('chalk');

exports.log = log;
function log(msg)
{
	console.log(chalk.green(msg));
},

exports.warn = warn;
function warn(msg)
{
	console.log(chalk.yellow(msg));
}
exports.error = error;
function error(msg)
{
	console.log(chalk.red(msg));
}
<commit_msg>first<commit_after>const chalk = require('chalk');

exports.log = log;
function log(msg)
{
	console.log(chalk.green(msg));
}

exports.warn = warn;
function warn(msg)
{
	console.log(chalk.yellow(msg));
}
exports.error = error;
function error(msg)
{
	console.log(chalk.red(msg));
}
<|endoftext|>


<commit_before>if (typeof jQuery === "undefined") {
    throw new Error("jQuery plugins need to be before this file");
}

$.AdminBSB = {};
$.AdminBSB.options = {
    colors: {
        red: '#F44336',
        pink: '#E91E63',
        purple: '#9C27B0',
        deepPurple: '#673AB7',
        indigo: '#3F51B5',
        blue: '#2196F3',
        lightBlue: '#03A9F4',
        cyan: '#00BCD4',
        teal: '#009688',
        green: '#4CAF50',
        lightGreen: '#8BC34A',
        lime: '#CDDC39',
        yellow: '#ffe821',
        amber: '#FFC107',
        orange: '#FF9800',
        deepOrange: '#FF5722',
        brown: '#795548',
        grey: '#9E9E9E',
        blueGrey: '#607D8B',
        black: '#000000',
        white: '#ffffff'
    },
    leftSideBar: {
        scrollColor: 'rgba(0,0,0,0.5)',
        scrollWidth: '4px',
        scrollAlwaysVisible: false,
        scrollBorderRadius: '0',
        scrollRailBorderRadius: '0'
    },
    dropdownMenu: {
        effectIn: 'fadeIn',
        effectOut: 'fadeOut'
    }
}

/* Left Sidebar - Function =================================================================================================
*  You can manage the left sidebar menu options
*
*/
$.AdminBSB.leftSideBar = {
    activate: function () {
        var _this = this;
        var $body = $('body');
        var $overlay = $('.overlay');

        //Close sidebar
        $(window).click(function (e) {
            var $target = $(e.target);
            if (e.target.nodeName.toLowerCase() === 'i') { $target = $(e.target).parent(); }

            if (!$target.hasClass('bars') && _this.isOpen() && $target.parents('#leftsidebar').length === 0) {
                if (!$target.hasClass('js-right-sidebar')) $overlay.fadeOut();
                $body.removeClass('overlay-open');
            }
        });

        $.each($('.menu-toggle.toggled'), function (i, val) {
            $(val).next().slideToggle(0);
        });

        //When page load
        $.each($('.menu .list li.active'), function (i, val) {
            var $activeAnchors = $(val).find('a:eq(0)');

            $activeAnchors.addClass('toggled');
            $activeAnchors.next().show();
        });

        //Collapse or Expand Menu
        $('.menu-toggle').on('click', function (e) {
            var $this = $(this);
            var $content = $this.next();

            if ($($this.parents('ul')[0]).hasClass('list')) {
                var $not = $(e.target).hasClass('menu-toggle') ? e.target : $(e.target).parents('.menu-toggle');

                $.each($('.menu-toggle.toggled').not($not).next(), function (i, val) {
                    if ($(val).is(':visible')) {
                        $(val).prev().toggleClass('toggled');
                        $(val).slideUp();
                    }
                });
            }

            $this.toggleClass('toggled');
            $content.slideToggle(320);
        });

        //Set menu height
        _this.setMenuHeight();
        //_this.checkStatuForResize(true);
        $(window).resize(function () {
            _this.setMenuHeight();
           // _this.checkStatuForResize(false);
        });

        //Set Waves
        Waves.attach('.menu .list a', ['waves-block']);
        Waves.init();
    },
    setMenuHeight: function () {
        if (typeof $.fn.slimScroll != 'undefined') {
            var configs = $.AdminBSB.options.leftSideBar;
            var height = ($(window).height() - ($('.legal').outerHeight() + $('.user-info').outerHeight() + $('.navbar').innerHeight()));
            var $el = $('.list');

            $el.slimScroll({ destroy: true }).height("auto");
            $el.parent().find('.slimScrollBar, .slimScrollRail').remove();

            $el.slimscroll({
                height: height + "px",
                color: configs.scrollColor,
                size: configs.scrollWidth,
                alwaysVisible: configs.scrollAlwaysVisible,
                borderRadius: configs.scrollBorderRadius,
                railBorderRadius: configs.scrollRailBorderRadius
            });
        }
    },
    checkStatuForResize: function (firstTime) {
        var $body = $('body');
        var $openCloseBar = $('.navbar .navbar-header .bars');
        var width = $body.width();

        if (firstTime) {
            $body.find('.content, .sidebar').addClass('no-animate').delay(1000).queue(function () {
                $(this).removeClass('no-animate').dequeue();
            });
        }

        if (width < 1170) {
            $body.addClass('ls-closed');
            $openCloseBar.fadeIn();
        }
        else {
            $body.removeClass('ls-closed');
            $openCloseBar.fadeOut();
        }
    },
    isOpen: function () {
        return $('body').hasClass('overlay-open');
    }
};
//==========================================================================================================================

/* Right Sidebar - Function ================================================================================================
*  You can manage the right sidebar menu options
*
*/
$.AdminBSB.rightSideBar = {
    activate: function () {
        var _this = this;
        var $sidebar = $('#rightsidebar');
        var $overlay = $('.overlay');

        //Close sidebar
        $(window).click(function (e) {
            var $target = $(e.target);
            if (e.target.nodeName.toLowerCase() === 'i') { $target = $(e.target).parent(); }

            if (!$target.hasClass('js-right-sidebar') && _this.isOpen() && $target.parents('#rightsidebar').length === 0) {
                if (!$target.hasClass('bars')) $overlay.fadeOut();
                $sidebar.removeClass('open');
            }
        });

        $('.js-right-sidebar').on('click', function () {
            $sidebar.toggleClass('open');
            if (_this.isOpen()) { $overlay.fadeIn(); } else { $overlay.fadeOut(); }
        });
    },
    isOpen: function () {
        return $('.right-sidebar').hasClass('open');
    }
}
//==========================================================================================================================

/* Searchbar - Function ================================================================================================
*  You can manage the search bar
*
*/
var $searchBar = $('.search-bar');
$.AdminBSB.search = {
    activate: function () {
        var _this = this;

        //Search button click event
        $('.js-search').on('click', function () {
            _this.showSearchBar();
        });

        //Close search click event
        $searchBar.find('.close-search').on('click', function () {
            _this.hideSearchBar();
        });

        //ESC key on pressed
        $searchBar.find('input[type="text"]').on('keyup', function (e) {
            if (e.keyCode == 27) {
                _this.hideSearchBar();
            }
        });
    },
    showSearchBar: function () {
        $searchBar.addClass('open');
        $searchBar.find('input[type="text"]').focus();
    },
    hideSearchBar: function () {
        $searchBar.removeClass('open');
        $searchBar.find('input[type="text"]').val('');
    }
}
//==========================================================================================================================

/* Navbar - Function =======================================================================================================
*  You can manage the navbar
*
*/
$.AdminBSB.navbar = {
    activate: function () {
        var $body = $('body');
        var $overlay = $('.overlay');

        //Open left sidebar panel
        $('.bars').on('click', function () {
            $body.toggleClass('overlay-open');
            if ($body.hasClass('overlay-open')) { $overlay.fadeIn(); } else { $overlay.fadeOut(); }
        });

        //Close collapse bar on click event
        $('.nav [data-close="true"]').on('click', function () {
            var isVisible = $('.navbar-toggle').is(':visible');
            var $navbarCollapse = $('.navbar-collapse');

            if (isVisible) {
                $navbarCollapse.slideUp(function () {
                    $navbarCollapse.removeClass('in').removeAttr('style');
                });
            }
        });
    }
}
//==========================================================================================================================

/* Input - Function ========================================================================================================
*  You can manage the inputs(also textareas) with name of class 'form-control'
*
*/
$.AdminBSB.input = {
    activate: function () {
        //On focus event
        $('.form-control').focus(function () {
            $(this).parent().addClass('focused');
        });

        //On focusout event
        $('.form-control').focusout(function () {
            var $this = $(this);
            if ($this.parents('.form-group').hasClass('form-float')) {
                if ($this.val() == '') { $this.parents('.form-line').removeClass('focused'); }
            }
            else {
                $this.parents('.form-line').removeClass('focused');
            }
        });

        //On label click
        $('body').on('click', '.form-float .form-line .form-label', function () {
            $(this).parent().find('input').focus();
        });
    }
}
//==========================================================================================================================

/* Form - Select - Function ================================================================================================
*  You can manage the 'select' of form elements
*
*/
$.AdminBSB.select = {
    activate: function () {
        if ($.fn.selectpicker) { $('select:not(.ms)').selectpicker(); }
    }
}
//==========================================================================================================================

/* DropdownMenu - Function =================================================================================================
*  You can manage the dropdown menu
*
*/

$.AdminBSB.dropdownMenu = {
    activate: function () {
        var _this = this;

        $('.dropdown, .dropup, .btn-group').on({
            "show.bs.dropdown": function () {
                var dropdown = _this.dropdownEffect(this);
                _this.dropdownEffectStart(dropdown, dropdown.effectIn);
            },
            "shown.bs.dropdown": function () {
                var dropdown = _this.dropdownEffect(this);
                if (dropdown.effectIn && dropdown.effectOut) {
                    _this.dropdownEffectEnd(dropdown, function () { });
                }
            },
            "hide.bs.dropdown": function (e) {
                var dropdown = _this.dropdownEffect(this);
                if (dropdown.effectOut) {
                    e.preventDefault();
                    _this.dropdownEffectStart(dropdown, dropdown.effectOut);
                    _this.dropdownEffectEnd(dropdown, function () {
                        dropdown.dropdown.removeClass('open');
                    });
                }
            }
        });

        //Set Waves
        Waves.attach('.dropdown-menu li a', ['waves-block']);
        Waves.init();
    },
    dropdownEffect: function (target) {
        var effectIn = $.AdminBSB.options.dropdownMenu.effectIn, effectOut = $.AdminBSB.options.dropdownMenu.effectOut;
        var dropdown = $(target), dropdownMenu = $('.dropdown-menu', target);

        if (dropdown.size() > 0) {
            var udEffectIn = dropdown.data('effect-in');
            var udEffectOut = dropdown.data('effect-out');
            if (udEffectIn !== undefined) { effectIn = udEffectIn; }
            if (udEffectOut !== undefined) { effectOut = udEffectOut; }
        }

        return {
            target: target,
            dropdown: dropdown,
            dropdownMenu: dropdownMenu,
            effectIn: effectIn,
            effectOut: effectOut
        };
    },
    dropdownEffectStart: function (data, effectToStart) {
        if (effectToStart) {
            data.dropdown.addClass('dropdown-animating');
            data.dropdownMenu.addClass('animated dropdown-animated');
            data.dropdownMenu.addClass(effectToStart);
        }
    },
    dropdownEffectEnd: function (data, callback) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        data.dropdown.one(animationEnd, function () {
            data.dropdown.removeClass('dropdown-animating');
            data.dropdownMenu.removeClass('animated dropdown-animated');
            data.dropdownMenu.removeClass(data.effectIn);
            data.dropdownMenu.removeClass(data.effectOut);

            if (typeof callback == 'function') {
                callback();
            }
        });
    }
}
//==========================================================================================================================

/* Browser - Function ======================================================================================================
*  You can manage browser
*
*/
var edge = 'Microsoft Edge';
var ie10 = 'Internet Explorer 10';
var ie11 = 'Internet Explorer 11';
var opera = 'Opera';
var firefox = 'Mozilla Firefox';
var chrome = 'Google Chrome';
var safari = 'Safari';

$.AdminBSB.browser = {
    activate: function () {
        var _this = this;
        var className = _this.getClassName();

        if (className !== '') $('html').addClass(_this.getClassName());
    },
    getBrowser: function () {
        var userAgent = navigator.userAgent.toLowerCase();

        if (/edge/i.test(userAgent)) {
            return edge;
        } else if (/rv:11/i.test(userAgent)) {
            return ie11;
        } else if (/msie 10/i.test(userAgent)) {
            return ie10;
        } else if (/opr/i.test(userAgent)) {
            return opera;
        } else if (/chrome/i.test(userAgent)) {
            return chrome;
        } else if (/firefox/i.test(userAgent)) {
            return firefox;
        } else if (!!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)) {
            return safari;
        }

        return undefined;
    },
    getClassName: function () {
        var browser = this.getBrowser();

        if (browser === edge) {
            return 'edge';
        } else if (browser === ie11) {
            return 'ie11';
        } else if (browser === ie10) {
            return 'ie10';
        } else if (browser === opera) {
            return 'opera';
        } else if (browser === chrome) {
            return 'chrome';
        } else if (browser === firefox) {
            return 'firefox';
        } else if (browser === safari) {
            return 'safari';
        } else {
            return '';
        }
    }
}
//==========================================================================================================================

$(function () {
    $.AdminBSB.browser.activate();
    $.AdminBSB.leftSideBar.activate();
    $.AdminBSB.rightSideBar.activate();
    $.AdminBSB.navbar.activate();
    $.AdminBSB.dropdownMenu.activate();
    $.AdminBSB.input.activate();
    $.AdminBSB.select.activate();
    $.AdminBSB.search.activate();

    setTimeout(function () { $('.page-loader-wrapper').fadeOut(); }, 50);
});
<commit_msg>Added new func<commit_after>if (typeof jQuery === "undefined") {
    throw new Error("jQuery plugins need to be before this file");
}

$.AdminBSB = {};
$.AdminBSB.options = {
    colors: {
        red: '#F44336',
        pink: '#E91E63',
        purple: '#9C27B0',
        deepPurple: '#673AB7',
        indigo: '#3F51B5',
        blue: '#2196F3',
        lightBlue: '#03A9F4',
        cyan: '#00BCD4',
        teal: '#009688',
        green: '#4CAF50',
        lightGreen: '#8BC34A',
        lime: '#CDDC39',
        yellow: '#ffe821',
        amber: '#FFC107',
        orange: '#FF9800',
        deepOrange: '#FF5722',
        brown: '#795548',
        grey: '#9E9E9E',
        blueGrey: '#607D8B',
        black: '#000000',
        white: '#ffffff'
    },
    leftSideBar: {
        scrollColor: 'rgba(0,0,0,0.5)',
        scrollWidth: '4px',
        scrollAlwaysVisible: false,
        scrollBorderRadius: '0',
        scrollRailBorderRadius: '0'
    },
    dropdownMenu: {
        effectIn: 'fadeIn',
        effectOut: 'fadeOut'
    }
}

/* Left Sidebar - Function =================================================================================================
*  You can manage the left sidebar menu options
*
*/
$.AdminBSB.leftSideBar = {
    activate: function () {
        var _this = this;
        var $body = $('body');
        var $overlay = $('.overlay');

        //Close sidebar
        $(window).click(function (e) {
            var $target = $(e.target);
            if (e.target.nodeName.toLowerCase() === 'i') { $target = $(e.target).parent(); }

            if (!$target.hasClass('bars') && _this.isOpen() && $target.parents('#leftsidebar').length === 0) {
                if (!$target.hasClass('js-right-sidebar')) $overlay.fadeOut();
                $body.removeClass('overlay-open');
            }
        });

        $.each($('.menu-toggle.toggled'), function (i, val) {
            $(val).next().slideToggle(0);
        });

        //When page load
        $.each($('.menu .list li.active'), function (i, val) {
            var $activeAnchors = $(val).find('a:eq(0)');

            $activeAnchors.addClass('toggled');
            $activeAnchors.next().show();
        });

        //Collapse or Expand Menu
        $('.menu-toggle').on('click', function (e) {
            var $this = $(this);
            var $content = $this.next();

            if ($($this.parents('ul')[0]).hasClass('list')) {
                var $not = $(e.target).hasClass('menu-toggle') ? e.target : $(e.target).parents('.menu-toggle');

                $.each($('.menu-toggle.toggled').not($not).next(), function (i, val) {
                    if ($(val).is(':visible')) {
                        $(val).prev().toggleClass('toggled');
                        $(val).slideUp();
                    }
                });
            }

            $this.toggleClass('toggled');
            $content.slideToggle(320);
        });

        //Set menu height
        _this.setMenuHeight();
        //_this.checkStatuForResize(true);
        $(window).resize(function () {
            _this.setMenuHeight();
           // _this.checkStatuForResize(false);
        });

        //Set Waves
        Waves.attach('.menu .list a', ['waves-block']);
        Waves.init();
    },
    setMenuHeight: function () {
        if (typeof $.fn.slimScroll != 'undefined') {
            var configs = $.AdminBSB.options.leftSideBar;
            var height = ($(window).height() - ($('.legal').outerHeight() + $('.user-info').outerHeight() + $('.navbar').innerHeight()));
            var $el = $('.list');

            $el.slimScroll({ destroy: true }).height("auto");
            $el.parent().find('.slimScrollBar, .slimScrollRail').remove();

            $el.slimscroll({
                height: height + "px",
                color: configs.scrollColor,
                size: configs.scrollWidth,
                alwaysVisible: configs.scrollAlwaysVisible,
                borderRadius: configs.scrollBorderRadius,
                railBorderRadius: configs.scrollRailBorderRadius
            });
        }
    },
    checkStatuForResize: function (firstTime) {
        var $body = $('body');
        var $openCloseBar = $('.navbar .navbar-header .bars');
        var width = $body.width();

        if (firstTime) {
            $body.find('.content, .sidebar').addClass('no-animate').delay(1000).queue(function () {
                $(this).removeClass('no-animate').dequeue();
            });
        }

        if (width < 1170) {
            $body.addClass('ls-closed');
            $openCloseBar.fadeIn();
        }
        else {
            $body.removeClass('ls-closed');
            $openCloseBar.fadeOut();
        }
    },
    isOpen: function () {
        return $('body').hasClass('overlay-open');
    }
};
//==========================================================================================================================

/* Right Sidebar - Function ================================================================================================
*  You can manage the right sidebar menu options
*
*/
$.AdminBSB.rightSideBar = {
    activate: function () {
        var _this = this;
        var $sidebar = $('#rightsidebar');
        var $overlay = $('.overlay');

        //Close sidebar
        $(window).click(function (e) {
            var $target = $(e.target);
            if (e.target.nodeName.toLowerCase() === 'i') { $target = $(e.target).parent(); }

            if (!$target.hasClass('js-right-sidebar') && _this.isOpen() && $target.parents('#rightsidebar').length === 0) {
                if (!$target.hasClass('bars')) $overlay.fadeOut();
                $sidebar.removeClass('open');
            }
        });

        $('.js-right-sidebar').on('click', function () {
            $sidebar.toggleClass('open');
            if (_this.isOpen()) { $overlay.fadeIn(); } else { $overlay.fadeOut(); }
        });
    },
    isOpen: function () {
        return $('.right-sidebar').hasClass('open');
    }
}
//==========================================================================================================================

/* Searchbar - Function ================================================================================================
*  You can manage the search bar
*
*/
var $searchBar = $('.search-bar');
$.AdminBSB.search = {
    activate: function () {
        var _this = this;

        //Search button click event
        $('.js-search').on('click', function () {
            _this.showSearchBar();
        });

        //Close search click event
        $searchBar.find('.close-search').on('click', function () {
            _this.hideSearchBar();
        });

        //ESC key on pressed
        $searchBar.find('input[type="text"]').on('keyup', function (e) {
            if (e.keyCode == 27) {
                _this.hideSearchBar();
            }
        });
    },
    showSearchBar: function () {
        $searchBar.addClass('open');
        $searchBar.find('input[type="text"]').focus();
    },
    hideSearchBar: function () {
        $searchBar.removeClass('open');
        $searchBar.find('input[type="text"]').val('');
    }
}
//==========================================================================================================================

/* Navbar - Function =======================================================================================================
*  You can manage the navbar
*
*/
$.AdminBSB.navbar = {
    activate: function () {
        var $body = $('body');
        var $overlay = $('.overlay');

        //Open left sidebar panel
        $('.bars').on('click', function () {
            $body.toggleClass('overlay-open');
            if ($body.hasClass('overlay-open')) { $overlay.fadeIn(); } else { $overlay.fadeOut(); }
        });

        //Close collapse bar on click event
        $('.nav [data-close="true"]').on('click', function () {
            var isVisible = $('.navbar-toggle').is(':visible');
            var $navbarCollapse = $('.navbar-collapse');

            if (isVisible) {
                $navbarCollapse.slideUp(function () {
                    $navbarCollapse.removeClass('in').removeAttr('style');
                });
            }
        });
    }
}
//==========================================================================================================================

/* Input - Function ========================================================================================================
*  You can manage the inputs(also textareas) with name of class 'form-control'
*
*/
$.AdminBSB.input = {
    activate: function () {
        //On focus event
        $('.form-control').focus(function () {
            $(this).parent().addClass('focused');
        });

        //On focusout event
        $('.form-control').focusout(function () {
            var $this = $(this);
            if ($this.parents('.form-group').hasClass('form-float')) {
                if ($this.val() == '') { $this.parents('.form-line').removeClass('focused'); }
            }
            else {
                $this.parents('.form-line').removeClass('focused');
            }
        });

        //On label click
        $('body').on('click', '.form-float .form-line .form-label', function () {
            $(this).parent().find('input').focus();
        });
    }
}
//==========================================================================================================================

/* Form - Select - Function ================================================================================================
*  You can manage the 'select' of form elements
*
*/
$.AdminBSB.select = {
    activate: function () {
        if ($.fn.selectpicker) { $('select:not(.ms)').selectpicker(); }
    }
}
//==========================================================================================================================

/* DropdownMenu - Function =================================================================================================
*  You can manage the dropdown menu
*
*/

$.AdminBSB.dropdownMenu = {
    activate: function () {
        var _this = this;

        $('.dropdown, .dropup, .btn-group').on({
            "show.bs.dropdown": function () {
                var dropdown = _this.dropdownEffect(this);
                _this.dropdownEffectStart(dropdown, dropdown.effectIn);
            },
            "shown.bs.dropdown": function () {
                var dropdown = _this.dropdownEffect(this);
                if (dropdown.effectIn && dropdown.effectOut) {
                    _this.dropdownEffectEnd(dropdown, function () { });
                }
            },
            "hide.bs.dropdown": function (e) {
                var dropdown = _this.dropdownEffect(this);
                if (dropdown.effectOut) {
                    e.preventDefault();
                    _this.dropdownEffectStart(dropdown, dropdown.effectOut);
                    _this.dropdownEffectEnd(dropdown, function () {
                        dropdown.dropdown.removeClass('open');
                    });
                }
            }
        });

        //Set Waves
        Waves.attach('.dropdown-menu li a', ['waves-block']);
        Waves.init();
    },
    dropdownEffect: function (target) {
        var effectIn = $.AdminBSB.options.dropdownMenu.effectIn, effectOut = $.AdminBSB.options.dropdownMenu.effectOut;
        var dropdown = $(target), dropdownMenu = $('.dropdown-menu', target);

        if (dropdown.size() > 0) {
            var udEffectIn = dropdown.data('effect-in');
            var udEffectOut = dropdown.data('effect-out');
            if (udEffectIn !== undefined) { effectIn = udEffectIn; }
            if (udEffectOut !== undefined) { effectOut = udEffectOut; }
        }

        return {
            target: target,
            dropdown: dropdown,
            dropdownMenu: dropdownMenu,
            effectIn: effectIn,
            effectOut: effectOut
        };
    },
    dropdownEffectStart: function (data, effectToStart) {
        if (effectToStart) {
            data.dropdown.addClass('dropdown-animating');
            data.dropdownMenu.addClass('animated dropdown-animated');
            data.dropdownMenu.addClass(effectToStart);
        }
    },
    dropdownEffectEnd: function (data, callback) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        data.dropdown.one(animationEnd, function () {
            data.dropdown.removeClass('dropdown-animating');
            data.dropdownMenu.removeClass('animated dropdown-animated');
            data.dropdownMenu.removeClass(data.effectIn);
            data.dropdownMenu.removeClass(data.effectOut);

            if (typeof callback == 'function') {
                callback();
            }
        });
    }
}
//==========================================================================================================================

/* Browser - Function ======================================================================================================
*  You can manage browser
*
*/
var edge = 'Microsoft Edge';
var ie10 = 'Internet Explorer 10';
var ie11 = 'Internet Explorer 11';
var opera = 'Opera';
var firefox = 'Mozilla Firefox';
var chrome = 'Google Chrome';
var safari = 'Safari';

$.AdminBSB.browser = {
    activate: function () {
        var _this = this;
        var className = _this.getClassName();

        if (className !== '') $('html').addClass(_this.getClassName());
    },
    getBrowser: function () {
        var userAgent = navigator.userAgent.toLowerCase();

        if (/edge/i.test(userAgent)) {
            return edge;
        } else if (/rv:11/i.test(userAgent)) {
            return ie11;
        } else if (/msie 10/i.test(userAgent)) {
            return ie10;
        } else if (/opr/i.test(userAgent)) {
            return opera;
        } else if (/chrome/i.test(userAgent)) {
            return chrome;
        } else if (/firefox/i.test(userAgent)) {
            return firefox;
        } else if (!!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)) {
            return safari;
        }

        return undefined;
    },
    getClassName: function () {
        var browser = this.getBrowser();

        if (browser === edge) {
            return 'edge';
        } else if (browser === ie11) {
            return 'ie11';
        } else if (browser === ie10) {
            return 'ie10';
        } else if (browser === opera) {
            return 'opera';
        } else if (browser === chrome) {
            return 'chrome';
        } else if (browser === firefox) {
            return 'firefox';
        } else if (browser === safari) {
            return 'safari';
        } else {
            return '';
        }
    }
}
//==========================================================================================================================

$(function () {
    $.AdminBSB.browser.activate();
    $.AdminBSB.leftSideBar.activate();
    $.AdminBSB.rightSideBar.activate();
    $.AdminBSB.navbar.activate();
    $.AdminBSB.dropdownMenu.activate();
    $.AdminBSB.input.activate();
    $.AdminBSB.select.activate();
    $.AdminBSB.search.activate();

    setTimeout(function () { $('.page-loader-wrapper').fadeOut(); }, 50);
});

//Datetimepicker plugin
$(function () {
    $('.datetimepicker').bootstrapMaterialDatePicker({
        format: 'dddd DD MMMM YYYY - HH:mm',
        clearButton: true,
        weekStart: 1
    });
});<|endoftext|>


<commit_before>function IndexesCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexNames = [];
	$scope.errorMessage = null;

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};

	$scope.refreshIndexNames = function() {
		$http.get('/api/index').success(function(data) {
            var indexNames = [];
            for (var indexName in data.indexDefs.indexDefs) {
                indexNames.push(indexName)
            }
            $scope.indexNames = indexNames;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.deleteIndexNamed = function(name) {
		if(!confirm("Are you sure you want to permanenty delete the index '" + name + "'?")) {
			return;
		}
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + name).success(function(data) {
			$scope.refreshIndexNames();
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.refreshIndexNames();
}

function IndexCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexName = $routeParams.indexName;
	$scope.indexDocCount = 0;
	$scope.indexDefStr = "";
	$scope.indexParamsStr = "";
	$scope.tab = $routeParams.tabName;
	if($scope.tab === undefined || $scope.tab === "") {
		$scope.tab = "summary";
	}
	$scope.tabPath = '/static/partials/index/tab-' + $scope.tab + '.html';

	$scope.loadIndexDetails = function() {
		$http.get('/api/index/' + $scope.indexName).success(function(data) {
            $scope.indexDefStr = JSON.stringify(data.indexDef, undefined, 2);
            $scope.indexParamsStr = JSON.stringify(data.indexParams, undefined, 2);
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.loadIndexDocCount = function() {
		$http.get('/api/index/' + $scope.indexName + '/count').success(function(data) {
            $scope.indexDocCount = data.count;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	// always load the details
	$scope.loadIndexDetails();
	// tab specific loading
	if($scope.tab === "summary") {
		$scope.loadIndexDocCount();
	} else if ($scope.tab === "params") {
	}

	$scope.indexDocument = function(id, body) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + $scope.indexName + "/doc/" + id, body).success(function(data) {
			$scope.successMessage = "Indexed Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.deleteDocument = function(id) {
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + $scope.indexName + "/" + id).success(function(data) {
			$scope.successMessage = "Deleted Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

    $scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}

function IndexNewCtrl($scope, $http, $routeParams, $log, $sce, $location) {
    $scope.newSourceParams = {};
    $scope.newIndexParams = {};
    $scope.newPlanParams = "";
    $scope.paramNumLines = {};

	$http.get('/api/managerMeta').success(function(data) {
		$scope.meta = data;

        for (var k in data.sourceTypes) {
            $scope.newSourceParams[k] =
                JSON.stringify(data.sourceTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newSourceParams[k].split("\n").length;
        }

        for (var k in data.indexTypes) {
            $scope.newIndexParams[k] =
                JSON.stringify(data.indexTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newIndexParams[k].split("\n").length;
        }

        $scope.newPlanParams = JSON.stringify(data.startSamples["planParams"], undefined, 2);
        $scope.paramNumLines["planParams"] = $scope.newPlanParams.split("\n").length;
	})

	$scope.errorMessage = null;

	$scope.newIndexNamed = function(sourceType, sourceName, sourceUUID, sourceParams,
									indexType, indexName, indexParams,
									planParams) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + indexName, "", {
			params: {
			    sourceType: sourceType,
			    sourceName: sourceName,
			    sourceUUID: sourceUUID || "",
			    sourceParams: sourceParams[sourceType],
			    indexType: indexType || "bleve",
			    indexName: indexName,
                indexParams: indexParams[indexType],
			    planParams: planParams,
		    }
		}).
		success(function(data) {
			$location.path('/indexes/' + indexName);
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}<commit_msg>remove empty if block<commit_after>function IndexesCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexNames = [];
	$scope.errorMessage = null;

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};

	$scope.refreshIndexNames = function() {
		$http.get('/api/index').success(function(data) {
            var indexNames = [];
            for (var indexName in data.indexDefs.indexDefs) {
                indexNames.push(indexName)
            }
            $scope.indexNames = indexNames;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.deleteIndexNamed = function(name) {
		if(!confirm("Are you sure you want to permanenty delete the index '" + name + "'?")) {
			return;
		}
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + name).success(function(data) {
			$scope.refreshIndexNames();
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.refreshIndexNames();
}

function IndexCtrl($scope, $http, $routeParams, $log, $sce) {

	$scope.indexName = $routeParams.indexName;
	$scope.indexDocCount = 0;
	$scope.indexDefStr = "";
	$scope.indexParamsStr = "";
	$scope.tab = $routeParams.tabName;
	if($scope.tab === undefined || $scope.tab === "") {
		$scope.tab = "summary";
	}
	$scope.tabPath = '/static/partials/index/tab-' + $scope.tab + '.html';

	$scope.loadIndexDetails = function() {
		$http.get('/api/index/' + $scope.indexName).success(function(data) {
            $scope.indexDefStr = JSON.stringify(data.indexDef, undefined, 2);
            $scope.indexParamsStr = JSON.stringify(data.indexParams, undefined, 2);
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	$scope.loadIndexDocCount = function() {
		$http.get('/api/index/' + $scope.indexName + '/count').success(function(data) {
            $scope.indexDocCount = data.count;
        }).
        error(function(data, code) {
			$scope.errorMessage = data;
        });
	};

	// always load the details
	$scope.loadIndexDetails();
	// tab specific loading
	if($scope.tab === "summary") {
		$scope.loadIndexDocCount();
	}

	$scope.indexDocument = function(id, body) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + $scope.indexName + "/doc/" + id, body).success(function(data) {
			$scope.successMessage = "Indexed Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.deleteDocument = function(id) {
		$scope.clearErrorMessage();
		$http.delete('/api/index/' + $scope.indexName + "/" + id).success(function(data) {
			$scope.successMessage = "Deleted Document: " + id;
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

    $scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}

function IndexNewCtrl($scope, $http, $routeParams, $log, $sce, $location) {
    $scope.newSourceParams = {};
    $scope.newIndexParams = {};
    $scope.newPlanParams = "";
    $scope.paramNumLines = {};

	$http.get('/api/managerMeta').success(function(data) {
		$scope.meta = data;

        for (var k in data.sourceTypes) {
            $scope.newSourceParams[k] =
                JSON.stringify(data.sourceTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newSourceParams[k].split("\n").length;
        }

        for (var k in data.indexTypes) {
            $scope.newIndexParams[k] =
                JSON.stringify(data.indexTypes[k].startSample, undefined, 2);
            $scope.paramNumLines[k] = $scope.newIndexParams[k].split("\n").length;
        }

        $scope.newPlanParams = JSON.stringify(data.startSamples["planParams"], undefined, 2);
        $scope.paramNumLines["planParams"] = $scope.newPlanParams.split("\n").length;
	})

	$scope.errorMessage = null;

	$scope.newIndexNamed = function(sourceType, sourceName, sourceUUID, sourceParams,
									indexType, indexName, indexParams,
									planParams) {
		$scope.clearErrorMessage();
		$http.put('/api/index/' + indexName, "", {
			params: {
			    sourceType: sourceType,
			    sourceName: sourceName,
			    sourceUUID: sourceUUID || "",
			    sourceParams: sourceParams[sourceType],
			    indexType: indexType || "bleve",
			    indexName: indexName,
                indexParams: indexParams[indexType],
			    planParams: planParams,
		    }
		}).
		success(function(data) {
			$location.path('/indexes/' + indexName);
		}).
		error(function(data, code) {
			$scope.errorMessage = data;
		});
	};

	$scope.clearErrorMessage = function() {
		$scope.errorMessage = null;
	};
}<|endoftext|>


<commit_before>var container = document.getElementById('container');

var camera, scene, renderer, controls, light;

var plane;
var theta = 0;

init(container);
animate();
render();

function setCameraPositionToHome() {
    camera.position.set(-1150, -400, 3100);
    camera.setViewOffset(window.innerWidth, window.innerHeight, 260, -150, window.innerWidth, window.innerHeight);
}

function init(container) {

    // Camera

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
    setCameraPositionToHome();

    scene = new THREE.Scene();

    // ambient
    scene.add(new THREE.AmbientLight(0x222222));

    // Cubes

    for (var i = 0; i < table.length; i++) {
        var count = table[i][1];

        var tableRowModule = 15;
        var height = 190;
        var width = 150;
        var margin = 60;

        var depth = Math.floor(count / 7000);

        addMesh(height, width, depth, function (mesh) {
            mesh.position.x = ((i % tableRowModule) * (height + margin)) - 1300;
            mesh.position.y = (Math.floor(i / tableRowModule) * -(width + margin)) + 550;

            mesh.position.z = depth / 2;

            mesh.c_text = "aa";

            scene.add(mesh);

            var edges = new THREE.EdgesHelper(mesh, 0x7FFFFF);
            edges.material.linewidth = 1;

            scene.add(edges);
        });
        //*/

        addTextPlane(table[i][0], height, width, depth, function(mesh) {

            mesh.position.x = ((i % tableRowModule) * (height + margin)) - 1300;
            mesh.position.y = (Math.floor(i / tableRowModule) * -(width + margin)) + 550;
            mesh.position.z = depth;
            scene.add(mesh);

            var edges = new THREE.EdgesHelper(mesh, 0x7FFFFF);
            edges.material.linewidth = 2;
            scene.add(edges);
        });
        //*/
    }

    // Canvas

    renderer = new THREE.CanvasRenderer();
    renderer.setClearColor(0x000000);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    // Controls

    controls = new THREE.OrbitControls(camera, renderer.domElement);

    controls.addEventListener('change', render);

    // Listeners

    window.addEventListener('resize', onWindowResize, false);
}

function addMesh(height, width, depth, callback) {
    var geometry = new THREE.BoxGeometry(height, width, depth);

    var material = new THREE.MeshLambertMaterial({
        color: 0x00ffff,
        polygonOffset: true,
        polygonOffsetFactor: 1,
        polygonOffsetUnits: 1,
        shading: THREE.FlatShading,
        transparent: true,
        opacity: 0.9,
        overdraw: 0.1 // for canvasRenderer only
    });

    var mesh = new THREE.Mesh(geometry, material);

    callback(mesh);
}

function addTextPlane(text, height, width, depth, callback) {
    var geometry = new THREE.BoxGeometry(height, width, 0);

    var back_color = 'rgba(0,127,127,0.5)';
    var font = "bold 40px Helvetica, sans-serif";
    var text_color = "rgba(255, 255, 255, 1)";
    var rect_width = 300; //... power of two
    var rect_depth = 150; //... power of two

    var temp_canvas = document.createElement('canvas');
    var temp_context = temp_canvas.getContext('2d');

    temp_context.fillStyle = back_color;
    temp_context.fillRect(0, 0, rect_width, rect_depth);//... fixed size rectangle, using powers of two

    temp_context.font = font;
    temp_context.fillStyle = text_color;
    temp_context.fillText(text, 103, 60); //... offset_width, offset_depth of start point of text string (bottom left corner of 1st char).

    //... NB texture doesn't need to know name of the context, just the name of the canvas
    var temp_texture = new THREE.Texture(temp_canvas);

    temp_texture.minFilter = THREE.LinearFilter;//THREE.NearestFilter;//... to avoid console warnings  about texture .NE. power of two.

    temp_texture.needsUpdate = false; //... important

    var material = new THREE.MeshBasicMaterial({map: temp_texture});

    var mesh1 = new THREE.Mesh(
        geometry,
        material
    );

    //... write custom properties to the mesh object
    mesh1.c_text = text;
    mesh1.c_back_color = back_color;
    mesh1.c_font = font;
    mesh1.c_text_color = text_color;
    mesh1.c_rect_width = rect_width; //... unchanged
    mesh1.c_rect_depth = rect_depth;

    callback(mesh1);
}

function addDataElement(width, height, data, callback) {

    var element = document.createElement('div');
    element.className = 'element';

    element.style.height = height;
    element.style.width = width;

    element.style.backgroundColor = 'rgba(0,127,127,' + 0.45 + ')';

    var symbol = document.createElement('div');
    symbol.className = 'symbol';
    symbol.textContent = data[0];
    element.appendChild(symbol);

    var details = document.createElement('div');
    details.className = 'details';
    var count = data[1];
    details.innerHTML = count + '
' + (Math.floor(count / countSum * 100000) / 1000) + '%';
    element.appendChild(details);

    callback(element);
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    render();
}

function animate() {
    requestAnimationFrame(animate);

    //theta = 0.01 //the speed of rotation
    //rotate camera
    //theta += 0.01;
    //var radius = 2500;

    //camera.position.x = radius * Math.sin( theta);
    //camera.position.y = radius * Math.sin( theta);
    //camera.position.z = radius * Math.cos( theta);
    //camera.lookAt( scene.position );

    //console.log("pos=", camera.position);

    controls.update();
}

function render() {
    renderer.render(scene, camera);
}

function degToRad(degrees) {
    return degrees * (Math.PI / 180);
}<commit_msg>tower text<commit_after>var container = document.getElementById('container');

var camera, scene, renderer, controls, light;

var plane;
var theta = 0;

init(container);
animate();
render();

function setCameraPositionToHome() {
    camera.position.set(-1150, -400, 3100);
    camera.setViewOffset(window.innerWidth, window.innerHeight, 260, -150, window.innerWidth, window.innerHeight);
}

function init(container) {

    // Camera

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
    setCameraPositionToHome();

    scene = new THREE.Scene();

    // ambient
    scene.add(new THREE.AmbientLight(0x222222));

    // Cubes

    for (var i = 0; i < table.length; i++) {
        var count = table[i][1];

        var tableRowModule = 15;
        var height = 190;
        var width = 150;
        var margin = 60;

        var depth = Math.floor(count / 7000);

        addMesh(height, width, depth, function (mesh) {
            mesh.position.x = ((i % tableRowModule) * (height + margin)) - 1300;
            mesh.position.y = (Math.floor(i / tableRowModule) * -(width + margin)) + 550;

            mesh.position.z = depth / 2;

            mesh.c_text = "aa";

            scene.add(mesh);

            var edges = new THREE.EdgesHelper(mesh, 0x7FFFFF);
            edges.material.linewidth = 1;

            scene.add(edges);
        });
        //*/

        addTextPlane(table[i], height, width, function(mesh) {

            mesh.position.x = ((i % tableRowModule) * (height + margin)) - 1300;
            mesh.position.y = (Math.floor(i / tableRowModule) * -(width + margin)) + 550;
            mesh.position.z = depth;
            scene.add(mesh);

            var edges = new THREE.EdgesHelper(mesh, 0x7FFFFF);
            edges.material.linewidth = 2;
            scene.add(edges);
        });
        //*/
    }

    // Canvas

    renderer = new THREE.CanvasRenderer();
    renderer.setClearColor(0x000000);
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    // Controls

    controls = new THREE.OrbitControls(camera, renderer.domElement);

    controls.addEventListener('change', render);

    // Listeners

    window.addEventListener('resize', onWindowResize, false);
}

function addMesh(height, width, depth, callback) {
    var geometry = new THREE.BoxGeometry(height, width, depth);

    var material = new THREE.MeshLambertMaterial({
        color: 0x00ffff,
        polygonOffset: true,
        polygonOffsetFactor: 1,
        polygonOffsetUnits: 1,
        shading: THREE.FlatShading,
        transparent: true,
        opacity: 0.9,
        overdraw: 0.1 // for canvasRenderer only
    });

    var mesh = new THREE.Mesh(geometry, material);

    callback(mesh);
}

function addTextPlane(data, height, width, callback) {
    var text = data[0];
    var geometry = new THREE.BoxGeometry(height, width, 0);

    var back_color = 'rgba(0,127,127,0.5)';
    var font = "bold 40px Helvetica, sans-serif";
    var text_color = "rgba(255, 255, 255, 1)";
    var rect_width = 300; //... power of two
    var rect_depth = 150; //... power of two

    var temp_canvas = document.createElement('canvas');
    var temp_context = temp_canvas.getContext('2d');

    temp_context.fillStyle = back_color;
    temp_context.fillRect(0, 0, rect_width, rect_depth);//... fixed size rectangle, using powers of two

    temp_context.font = font;
    temp_context.fillStyle = text_color;
    temp_context.fillText(text, 70, 55); //... offset_width, offset_depth of start point of text string (bottom left corner of 1st char).
    temp_context.fillText(data[1], 115, 135);

    //... NB texture doesn't need to know name of the context, just the name of the canvas
    var temp_texture = new THREE.Texture(temp_canvas);

    temp_texture.minFilter = THREE.LinearFilter;//THREE.NearestFilter;//... to avoid console warnings  about texture .NE. power of two.

    temp_texture.needsUpdate = false; //... important

    var material = new THREE.MeshBasicMaterial({map: temp_texture});

    var mesh1 = new THREE.Mesh(
        geometry,
        material
    );

    //... write custom properties to the mesh object
    mesh1.c_text = text;
    mesh1.c_back_color = back_color;
    mesh1.c_font = font;
    mesh1.c_text_color = text_color;
    mesh1.c_rect_width = rect_width; //... unchanged
    mesh1.c_rect_depth = rect_depth;

    callback(mesh1);
}

function addDataElement(width, height, data, callback) {

    var element = document.createElement('div');
    element.className = 'element';

    element.style.height = height;
    element.style.width = width;

    element.style.backgroundColor = 'rgba(0,127,127,' + 0.45 + ')';

    var symbol = document.createElement('div');
    symbol.className = 'symbol';
    symbol.textContent = data[0];
    element.appendChild(symbol);

    var details = document.createElement('div');
    details.className = 'details';
    var count = data[1];
    details.innerHTML = count + '
' + (Math.floor(count / countSum * 100000) / 1000) + '%';
    element.appendChild(details);

    callback(element);
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    render();
}

function animate() {
    requestAnimationFrame(animate);

    //theta = 0.01 //the speed of rotation
    //rotate camera
    //theta += 0.01;
    //var radius = 2500;

    //camera.position.x = radius * Math.sin( theta);
    //camera.position.y = radius * Math.sin( theta);
    //camera.position.z = radius * Math.cos( theta);
    //camera.lookAt( scene.position );

    //console.log("pos=", camera.position);

    controls.update();
}

function render() {
    renderer.render(scene, camera);
}

function degToRad(degrees) {
    return degrees * (Math.PI / 180);
}<|endoftext|>


<commit_before>(function (load, morgen, __morgen) {
    'use strict';

    function encodeData (data) {
        var query = [];
        for (var key in data)
            query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        return query.join('&');
    }

    function updateDict (src, dest) {
        for (var key in src)
            if (typeof(src[key]) == 'object')
                updateDict(src[key], dest[key]);
            else
                dest[key] = src[key];
    }

    function isEmpty(obj) {
        if (!obj)
            return false;

        for (var prop in obj)
            if (obj.hasOwnProperty(prop)) return false;

        return true;
    }

    morgen.updateConfig = function (data) {
        updateDict(data, __morgen.config);
    };

    morgen.uid = function () {
        return __morgen.uid++;
    };

    morgen.run = function (options) {
        load('__morgen_broadcast');
        load('__morgen_history');
        load('__morgen_data_events');

        if (options.watch)
            load('__morgen_watchdog');
    };

    morgen.broadcast = function (msg) {
        __morgen.ws.send(JSON.stringify(msg));
    };

    morgen.httpSend = function (method, url, data, success, error) {
        var xhr = new XMLHttpRequest(),
            contentType = method == 'get' ? 'text/plain' : 'application/x-www-form-urlencoded'

        if (__morgen.config.http.apiRoot)
            url = __morgen.config.http.apiRoot + url

        if (!isEmpty(__morgen.config.http.appendParams))
            url = [url, encodeData(__morgen.config.http.appendParams)].join(url.indexOf('?') == -1 ? '?' : '&');

        xhr.open(method, url, true);
        xhr.withCredentials = __morgen.config.http.withCredentials;
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.setRequestHeader('Content-Type', contentType + ';charset=UTF-8');
        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                if (xhr.status == 200 || xhr.status === 0)
                    success && success(JSON.parse(xhr.responseText));
                else
                    error && error();
            }
        };

        xhr.onerror = error;
        xhr.ontimeout = error;

        try {
            xhr.send(data);
        } catch (e) {
            error && error();
        }

        return xhr;
    };

    morgen.httpGet = function (url, data, success, error) {
        // FIXME: this is a bit shitty
        if (typeof(data) == 'function') {
            error = success;
            success = data;
            data = null;
        }
        if (data) {
            url = url + '?' + encodeData(data)
        }
        return morgen.httpSend('get', url, null, success, error);
    };

    morgen.httpPost = function (url, data, success, error) {
        // FIXME: this is a bit shitty
        if (typeof(data) == 'function') {
            error = success;
            success = data;
            data = null;
        }
        return morgen.httpSend('post', url, data instanceof FormData ? data : encodeData(data), success, error);
    };

    morgen.cookie = function (name, value) {
        // thanks to:
        //  - http://stackoverflow.com/a/11344672/597097
        //  - https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

        // read cookie
        if (value === undefined) {
            var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
            return result === null ? undefined : JSON.parse(decodeURIComponent(result[1]));
        }
        // delete cookie
        else if (value === null) {
              document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;'].join('');
        }
        // write cookie
        else {
              document.cookie = [name, '=', encodeURIComponent(JSON.stringify(value)), '; path=/', '; max-age=', 60*60*24*365].join('');
        }
    };
}) (window.morgen.load,
    window.morgen,
    window.__morgen);

<commit_msg>Add utils to interact with history API<commit_after>(function (load, morgen, __morgen) {
    'use strict';

    function encodeData (data) {
        var query = [];
        for (var key in data)
            query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
        return query.join('&');
    }

    function updateDict (src, dest) {
        for (var key in src)
            if (typeof(src[key]) == 'object')
                updateDict(src[key], dest[key]);
            else
                dest[key] = src[key];
    }

    function isEmpty(obj) {
        if (!obj)
            return false;

        for (var prop in obj)
            if (obj.hasOwnProperty(prop)) return false;

        return true;
    }

    morgen.updateConfig = function (data) {
        updateDict(data, __morgen.config);
    };

    morgen.uid = function () {
        return __morgen.uid++;
    };

    morgen.run = function (options) {
        load('__morgen_broadcast');
        load('__morgen_history');
        load('__morgen_data_events');

        if (options.watch)
            load('__morgen_watchdog');
    };

    morgen.broadcast = function (msg) {
        __morgen.ws.send(JSON.stringify(msg));
    };

    morgen.httpSend = function (method, url, data, success, error) {
        var xhr = new XMLHttpRequest(),
            contentType = method == 'get' ? 'text/plain' : 'application/x-www-form-urlencoded'

        if (__morgen.config.http.apiRoot)
            url = __morgen.config.http.apiRoot + url

        if (!isEmpty(__morgen.config.http.appendParams))
            url = [url, encodeData(__morgen.config.http.appendParams)].join(url.indexOf('?') == -1 ? '?' : '&');

        xhr.open(method, url, true);
        xhr.withCredentials = __morgen.config.http.withCredentials;
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.setRequestHeader('Content-Type', contentType + ';charset=UTF-8');
        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                if (xhr.status == 200 || xhr.status === 0)
                    success && success(JSON.parse(xhr.responseText));
                else
                    error && error();
            }
        };

        xhr.onerror = error;
        xhr.ontimeout = error;

        try {
            xhr.send(data);
        } catch (e) {
            error && error();
        }

        return xhr;
    };

    morgen.httpGet = function (url, data, success, error) {
        // FIXME: this is a bit shitty
        if (typeof(data) == 'function') {
            error = success;
            success = data;
            data = null;
        }
        if (data) {
            url = url + '?' + encodeData(data)
        }
        return morgen.httpSend('get', url, null, success, error);
    };

    morgen.httpPost = function (url, data, success, error) {
        // FIXME: this is a bit shitty
        if (typeof(data) == 'function') {
            error = success;
            success = data;
            data = null;
        }
        return morgen.httpSend('post', url, data instanceof FormData ? data : encodeData(data), success, error);
    };

    morgen.cookie = function (name, value) {
        // thanks to:
        //  - http://stackoverflow.com/a/11344672/597097
        //  - https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

        // read cookie
        if (value === undefined) {
            var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
            return result === null ? undefined : JSON.parse(decodeURIComponent(result[1]));
        }
        // delete cookie
        else if (value === null) {
              document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;'].join('');
        }
        // write cookie
        else {
              document.cookie = [name, '=', encodeURIComponent(JSON.stringify(value)), '; path=/', '; max-age=', 60*60*24*365].join('');
        }
    };

    morgen.historyPush = function (href) {
        window.history.pushState({ href: href }, '', href);
        morgen.dispatch('route', { href: href });
    };

    morgen.historyReplace= function (href) {
        window.history.replaceState({ href: href }, '', href);
        morgen.dispatch('route', { href: href });
    };

}) (window.morgen.load,
    window.morgen,
    window.__morgen);

<|endoftext|>