<commit_before>var nj = require('../src/base'),
  utils = require('../src/utils/utils'),
  compiler = require('../src/compiler/compile'),
  compile = compiler.compile,
  _ = require('lodash'),
  React = require('react'),
  ReactDOM = require('react-dom'),
  ReactDOMServer = require('react-dom/server'),
  Handlebars = require('handlebars');

describe('test speed', function () {
  var tmpl = nj`
  <{div} id="{num '_100'}">
    <#each {arr}>

        test_{../num}
        <#each {../list2}>

            <#params>
              <#if {../#:five}>
                <#p {'name'}>five</#p>
              </#if>
            </#params>
            span{no}
            {no}

        </#each>

      <#if {#:five:test}>

      <#else />

      </#if>
    </#each>
  </{div}>
  `;

  var tmplHbs = `
  <{{div}} id="{{num}}_100">
    {{#each arr}}

        test_{{../num}}
        {{#each ../list2}}

            span{{no}}
            {{no}}

        {{/each}}

      {{#five @index}}

      {{else}}

      {{/five}}
    {{/each}}
  </{{div}}>
  `;

  var tmplNj = nj`
  <{div} id="{num}_100">
    <#each {arr}>

        test_{../num}
        <#each {../list2}>

            <#params>
              <#if {../#:five}>
                <#p {'name'}>five</#p>
              </#if>
            </#params>
            span{no}
            {no}

        </#each>

      <#if {#:five}>

      <#else />

      </#if>
    </#each>
  </{div}>
  `;

  beforeAll(function () {
    nj.setComponentEngine('react', React, ReactDOM);

    nj.registerFilter('five', function (obj) {
      if (obj % 5 == 0) {
        return true;
      }
    });

    nj.registerFilter('test', function (obj) {
      return obj;
    });

    Handlebars.registerHelper('five', function (num, options) {
      if (num % 5 == 0) {
        return options.fn(this);
      }
      else {
        return options.inverse(this);
      }
    });
  });

  it('test render to component by jsx', function () {
    var start;
    var TestComponent = React.createClass({
      getInitialState: function () {
        start = Date.now();

        return {
          num: 100
        };
      },
      onClick: function () {
        start = Date.now();
        this.setState({ num: Date.now() }, function () {
          console.log('total:' + (Date.now() - start));
        });
      },
      render: function () {
        var start = Date.now();
        var ret = React.createElement('div', { id: this.state.num + '_100' }, this.props.arr.map(function (o, i) {
          return [
              React.createElement('span', { className: 'test_' + i, style: { color: 'blue' }, onClick: this.onClick },
                'test_' + this.state.num,
                list2.map(function (p, j) {
                  return React.createElement('div', i % 5 == 0 ? { name: 'five', key: j } : { key: j },
                    React.createElement('span', null, 'span' + p.no),
                    React.createElement('i', null, p.no)
                  );
                })
              ),
              i % 5 == 0 ? React.createElement('br') : React.createElement('img')
          ];
        }.bind(this)));

        //var params = ['div', null];
        //this.props.arr.forEach(function (o, i) {
        //  params.push(React.createElement('span', { className: 'test_' + i }, 'test_' + i));
        //});
        //ret = React.createElement.apply(React, params);

        console.log('jsx:' + (Date.now() - start));
        return ret;
      }
    });

    var list2 = _.times(100, function (n) {
      return { no: n + 1 };
    });

    var html = ReactDOMServer.renderToStaticMarkup(React.createElement(TestComponent, {
      arr: _.times(100, function (n) {
        return n;
      }),
      a: 1,
      list: [{ no: 1, b: 1 }, { no: 2, b: 0 }, { no: 3, b: 1 }]
    }));

    //console.log(html);
    expect(html).toBeTruthy();
  });

  it('test render to component by nj', function () {
    var start;
    var TestComponent = React.createClass({
      getInitialState: function () {
        start = Date.now();

        return {
          num: 100
        };
      },
      template: nj.compileComponent(tmpl, 'tmpl1'),
      onClick: function () {
        start = Date.now();
        this.setState({ num: Date.now() }, function () {
          console.log('total:' + (Date.now() - start));
        });
      },
      render: function () {
        var params = {
          arr: this.props.arr,
          num: this.state.num,
          list2: list2,
          onClick: this.onClick,
          params: {
            'data-a': 1,
            'data-b': 2
          },
          styles: {
            color: 'blue'
          },
          div: 'div'
        };

        var ret = this.template(params);
        console.log('nj:' + (Date.now() - start));
        return ret;
      }
    });

    var list2 = _.times(100, function (n) {
      return { no: n + 1 };
    });

    var html = ReactDOMServer.renderToStaticMarkup(React.createElement(TestComponent, {
      arr: _.times(100, function (n) {
        return n;
      }),
      a: 1,
      list: [{ no: 1, b: 1 }, { no: 2, b: 0 }, { no: 3, b: 1 }]
    }));

    //console.log(JSON.stringify(nj.templates['tmpl1']));
    //console.log(html);
    expect(html).toBeTruthy();
  });

  it('test render to string by hbs', function () {
    var data = {
      div: 'div',
      num: 100,
      arr: _.times(1000, function (n) {
        return n;
      }),
      list2: _.times(100, function (n) {
        return { no: n + 1 };
      })
    };
    var tmplFn = Handlebars.compile(tmplHbs);
    var start = Date.now();
    var ret = tmplFn(data);
    //console.log(ret);
    console.log('hbs:' + (Date.now() - start));
    expect(ret).toBeTruthy();
  });

  it('test render to string by nj', function () {
    var data = {
      div: 'div',
      num: 100,
      arr: _.times(1000, function (n) {
        return n;
      }),
      list2: _.times(100, function (n) {
        return { no: n + 1 };
      })
    };
    var tmplFn = nj.compile(tmplNj);
    var start = Date.now();
    var ret = tmplFn(data);
    //console.log(ret);
    console.log('nj:' + (Date.now() - start));
    expect(ret).toBeTruthy();
  });
});
<commit_msg>Updated spec<commit_after>var nj = require('../src/base'),
  utils = require('../src/utils/utils'),
  compiler = require('../src/compiler/compile'),
  compile = compiler.compile,
  _ = require('lodash'),
  React = require('react'),
  ReactDOM = require('react-dom'),
  ReactDOMServer = require('react-dom/server'),
  Handlebars = require('handlebars');

describe('test speed', function () {
  var tmpl = nj`
  <{div} id="{num '_100'}">
    <#each {arr}>

        test_{../num}
        <#each {../list2}>

            <#params>
              <#if {../#:five}>
                <#p {'name'}>five</#p>
              </#if>
            </#params>
            span{no}
            {no}

        </#each>

      <#if {#:five:test}>

      <#else />

      </#if>
    </#each>
  </{div}>
  `;

  var tmplHbs = `
  <{{div}} id="{{num}}_100">
    {{#each arr}}

        test_{{../num}}
        {{#each ../list2}}

            span{{no}}
            {{no}}

        {{/each}}

      {{#five @index}}

      {{else}}

      {{/five}}
    {{/each}}
  </{{div}}>
  `;

  var tmplNj = nj`
  <{div} id="{num}_100">
    <#each {arr}>

        test_{../num}
        <#each {../list2}>

            <#params>
              <#if {../#:five}>
                <#p {'name'}>five</#p>
              </#if>
            </#params>
            span{no}
            {no}

        </#each>

      <#if {#:five}>

      <#else />

      </#if>
    </#each>
  </{div}>
  `;

  beforeAll(function () {
    nj.setComponentEngine('react', React, ReactDOM);

    nj.registerFilter('five', function (obj) {
      if (obj % 5 == 0) {
        return true;
      }
    });

    nj.registerFilter('test', function (obj) {
      return obj;
    });

    Handlebars.registerHelper('five', function (num, options) {
      if (num % 5 == 0) {
        return options.fn(this);
      }
      else {
        return options.inverse(this);
      }
    });
  });

  xit('test render to string by hbs', function () {
    var data = {
      div: 'div',
      num: 100,
      arr: _.times(1000, function (n) {
        return n;
      }),
      list2: _.times(100, function (n) {
        return { no: n + 1 };
      })
    };

    var tmplFn = Handlebars.compile(tmplHbs);
    var start = Date.now();
    var ret = tmplFn(data);
    //console.log(ret);
    console.log('hbs:' + (Date.now() - start));
    expect(ret).toBeTruthy();
  });

  xit('test render to string by nj', function () {
    var data = {
      div: 'div',
      num: 100,
      arr: _.times(1000, function (n) {
        return n;
      }),
      list2: _.times(100, function (n) {
        return { no: n + 1 };
      })
    };

    var tmplFn = nj.compile(tmplNj);
    var start = Date.now();
    var ret = tmplFn(data);
    //console.log(ret);
    console.log('nj:' + (Date.now() - start));
    expect(ret).toBeTruthy();
  });

  it('test render to component by jsx', function () {
    var start;
    var TestComponent = React.createClass({
      getInitialState: function () {
        return {
          num: 100
        };
      },
      onClick: function () {
        this.setState({ num: Date.now() }, function () {
          console.log('total:' + (Date.now() - start));
        });
      },
      render: function () {
        start = Date.now();
        var ret = React.createElement('div', { id: this.state.num + '_100' }, this.props.arr.map(function (o, i) {
          return [
              React.createElement('span', { className: 'test_' + i, style: { color: 'blue' }, onClick: this.onClick },
                'test_' + this.state.num,
                list2.map(function (p, j) {
                  return React.createElement('div', i % 5 == 0 ? { name: 'five', key: j } : { key: j },
                    React.createElement('span', null, 'span' + p.no),
                    React.createElement('i', null, p.no)
                  );
                })
              ),
              i % 5 == 0 ? React.createElement('br') : React.createElement('img')
          ];
        }.bind(this)));

        //var params = ['div', null];
        //this.props.arr.forEach(function (o, i) {
        //  params.push(React.createElement('span', { className: 'test_' + i }, 'test_' + i));
        //});
        //ret = React.createElement.apply(React, params);

        console.log('jsx:' + (Date.now() - start));
        return ret;
      }
    });

    var list2 = _.times(100, function (n) {
      return { no: n + 1 };
    });

    var html = ReactDOMServer.renderToStaticMarkup(React.createElement(TestComponent, {
      arr: _.times(100, function (n) {
        return n;
      }),
      a: 1,
      list: [{ no: 1, b: 1 }, { no: 2, b: 0 }, { no: 3, b: 1 }]
    }));

    //console.log(html);
    expect(html).toBeTruthy();
  });

  it('test render to component by nj', function () {
    var start;
    var TestComponent = React.createClass({
      getInitialState: function () {
        return {
          num: 100
        };
      },
      template: nj.compileComponent(tmpl, 'tmpl1'),
      onClick: function () {
        this.setState({ num: Date.now() }, function () {
          console.log('total:' + (Date.now() - start));
        });
      },
      render: function () {
        start = Date.now();
        var params = {
          arr: this.props.arr,
          num: this.state.num,
          list2: list2,
          onClick: this.onClick,
          params: {
            'data-a': 1,
            'data-b': 2
          },
          styles: {
            color: 'blue'
          },
          div: 'div'
        };

        var ret = this.template(params);
        console.log('nj:' + (Date.now() - start));
        return ret;
      }
    });

    var list2 = _.times(100, function (n) {
      return { no: n + 1 };
    });

    var html = ReactDOMServer.renderToStaticMarkup(React.createElement(TestComponent, {
      arr: _.times(100, function (n) {
        return n;
      }),
      a: 1,
      list: [{ no: 1, b: 1 }, { no: 2, b: 0 }, { no: 3, b: 1 }]
    }));

    //console.log(JSON.stringify(nj.templates['tmpl1']));
    //console.log(html);
    expect(html).toBeTruthy();
  });
});
<|endoftext|>


<commit_before>'use strict'

var ref = require('../../util/get/reference')
var Event = require('../../event')

exports.inject = require('./retrieve')

exports.define = {
  subscribe (path, type, val, key, fire, event) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }
    let index = 0
    let length = path.length
    // unsubs will not work now
    this.on('remove', function () {
      unsubscribe(this, path, index, length, id)
    }, id)
    return subscribe(this, path, index, length, type, val, id, fire, this, event)
  },

  // test and make better -- the uid is crap now
  unsubscribe (path, key) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    // make shared shit
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }

    let index = 0
    let length = path.length
    return unsubscribe(this, path, index, length, id)
  }
}

// subscriptions have to take care of references
// we have to add walking over the refs here

function subscribe (obs, path, index, length, type, val, id, fire, origin, event) {
  if (index === length) {
    obs.on('remove', function () {
      // null
      subscribe(origin, path, 0, length, type, val, id, false, origin)
    }, id)
    obs.on(type, val, id)
    if (fire) {
      // **TODO** SUPER DIRTY
      // need to have some godamn arguments

      console.log('WTF WTF', obs, event)

      if (event === void 0) {
        var trigger = true
        event = new Event('data') // wrong
      }

      if (typeof val === 'function') {
        console.log('do it bitch')
        var data = obs._input
        val.call(obs, data, event)
      } else {
        console.log('do it bitch', data)
        var data = obs._input // if property if data haha lulllzzzz
        //ref and value
        val[0].call(obs, data, event, val[1])
      }

      if (trigger) {
        event.trigger()
      }

      // val.call(obs, event, )
      // obs.emit(type, void 0, event)
    }
    return obs
  } else {
    let key = path[index]
    let property = obs[key]
    let result

    if (property && property._input !== null) {
      result = subscribe(property, path, index + 1, length, type, val, id, fire, origin)
    } else {
      let listenerType = key === 'parent' ? key : 'property'
      let listener = function (data, event) {
        let property = obs[key]
        if (property) {
          obs.off(listenerType, id)
          subscribe(property, path, index + 1, length, type, val, id, true, origin)
        }
      }
      obs.on(listenerType, listener, id)
    }

    // if sub is not fulfilled look in the reference
    if (!result) {
      let reference = ref(obs)
      if (reference) {
        subscribe(reference, path, index, length, type, val, id, fire, origin)
      }
    }
  }
}

function unsubscribe (obs, path, index, length, id) {
  console.log('REMOVE!')
  obs.off(void 0, id)
  let key = path[index]
  let property = obs[key]
  if (property) {
    unsubscribe(property, path, index + 1, length, id)
  }
  let reference = ref(obs)
  if (reference) {
    unsubscribe(obs, path, index, length, id)
  }
}
<commit_msg>update<commit_after>'use strict'

var ref = require('../../util/get/reference')
var Event = require('../../event')

exports.inject = require('./retrieve')

exports.define = {
  subscribe (path, type, val, key, fire, event) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }
    let index = 0
    let length = path.length
    // unsubs will not work now
    this.on('remove', function () {
      unsubscribe(this, path, index, length, id)
    }, id)
    return subscribe(this, path, index, length, type, val, id, fire, this, event)
  },

  // test and make better -- the uid is crap now
  unsubscribe (path, key) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    // make shared shit
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }

    let index = 0
    let length = path.length
    return unsubscribe(this, path, index, length, id)
  }
}

// subscriptions have to take care of references
// we have to add walking over the refs here
function subscribe (obs, path, index, length, type, val, id, fire, origin, event) {
  if (index === length) {
    obs.on('remove', function () {
      // null
      subscribe(origin, path, 0, length, type, val, id, false, origin)
    }, id)
    obs.on(type, val, id)
    if (fire) {
      // **TODO** SUPER DIRTY
      // need to have some godamn arguments

      // console.log('WTF WTF', obs, event)

      if (event === void 0) {
        var trigger = true
        event = new Event('data') // wrong
      }

      if (typeof val === 'function') {
        // console.log('do it bitch')
        var data = obs._input
        val.call(obs, data, event)
      } else {
        // console.log('do it bitch', data)
        var data = obs._input // if property if data haha lulllzzzz
        //ref and value
        val[0].call(obs, data, event, val[1])
      }

      if (trigger) {
        event.trigger()
      }

      // val.call(obs, event, )
      // obs.emit(type, void 0, event)
    }
    return obs
  } else {
    let key = path[index]
    let property = obs[key]
    let result

    if (property && property._input !== null) {
      result = subscribe(property, path, index + 1, length, type, val, id, fire, origin)
    } else {
      let listenerType = key === 'parent' ? key : 'property'
      let listener = function (data, event) {
        let property = obs[key]
        if (property) {
          obs.off(listenerType, id)
          subscribe(property, path, index + 1, length, type, val, id, true, origin)
        }
      }
      obs.on(listenerType, listener, id)
    }

    // if sub is not fulfilled look in the reference
    if (!result) {
      let reference = ref(obs)
      if (reference) {
        subscribe(reference, path, index, length, type, val, id, fire, origin)
      }
    }
  }
}

function unsubscribe (obs, path, index, length, id) {
  // console.log('REMOVE!')
  obs.off(void 0, id)
  let key = path[index]
  let property = obs[key]
  if (property) {
    unsubscribe(property, path, index + 1, length, id)
  }
  let reference = ref(obs)
  if (reference) {
    unsubscribe(obs, path, index, length, id)
  }
}
<|endoftext|>


<commit_before>/*global OJ:true,$:true,window:true,Number:true*/
(function() {

	OJ.makeSubNameSpace('to');

	OJ.to.lift('bool', function bool(str) {
		var retBool = OJ.is.true(str);
        if(retBool === false || retBool !== true) {
            retBool = false;
        }
		return retBool;
	});

	OJ.to.lift('ES5_ToBool', function(val) {
	    return (val !== false &&
            val !== 0 &&
            val !== '' &&
            val !== null &&
            val !== undefined &&
            (typeof val !== 'number' || !isNaN(val)));
	});

	OJ.to.lift('dateFromTicks', function(tickStr) {
		var ticsDateTime = OJ.string(tickStr);
        var ret, ticks, offset, localOffset, arr;

        if (false === OJ.is.nullOrEmpty(ticsDateTime)) {
            ticsDateTime = ticsDateTime.replace('/', '');
            ticsDateTime = ticsDateTime.replace('Date', '');
            ticsDateTime = ticsDateTime.replace('(', '');
            ticsDateTime = ticsDateTime.replace(')', '');
            arr = ticsDateTime.split('-');
            if (arr.length > 1) {
                ticks = OJ.number(arr[0]);
                offset = OJ.number(arr[1]);
                localOffset = new Date().getTimezoneOffset();
                ret = new Date((ticks - ((localOffset + (offset / 100 * 60)) * 1000)));
            } else if (arr.length === 1) {
                ticks = OJ.number(arr[0]);
                ret = new Date(ticks);
            }
        }
        return ret;
    });

    OJ.to.lift('binary', function(obj){
        var ret = -1;
        if(obj === 0 || obj === '0' || obj === '' || obj === false || OJ.to.string(obj).toLowerCase().trim() === 'false') {
            ret = 0;
        }
        else if (obj === 1 || obj === '1' || obj === true || OJ.to.string(obj).toLowerCase().trim() === 'true') {
            ret = 1;
        }
        return ret;
    });

    /**
    *   Attempts to converts an arbitrary value to a Number.
    *   Loose falsy values are converted to 0.
    *   Loose truthy values are converted to 1.
    *   All other values are parsed as Integers.
    *   Failures return as NaN.
    *
    */
	OJ.to.lift('number', function(inputNum, defaultNum) {
        'use strict';
        function tryGetNumber(val) {
            var ret;
            if(OJ.is.number(val)) {
                ret = val;
            }
            else if(OJ.is.string(val) || OJ.is.bool(val)) {

                var getNumber = function(value) {
                    var num = OJ.to.binary(value);
                    if(num < 0) {
                        num = Number.NaN;
                    }
                    if (!OJ.is.number(num) && value) {
                        num = +value;
                    }
                    if (!OJ.is.number(num)) {
                        num = parseInt(value, 0);
                    }
                    return num;
                };

                var tryGet = getNumber(val);

                if (OJ.is.number(tryGet)) {
                    ret = tryGet;
                }
                return ret;
            }
        }

        var retVal = tryGetNumber(inputNum);
        if (!OJ.is.number(retVal)) {
            retVal = tryGetNumber(defaultNum);
            if(!OJ.is.number(retVal)) {
                retVal = Number.NaN;
            }
        }
        return retVal;
    });

	OJ.to.lift('string', function (inputStr, defaultStr) {
        function tryGetString(str) {
            var ret;
            if(OJ.is.string(str)) {
                ret = str;
            } else {
                ret = '';
                if (OJ.is.bool(str) || OJ.is.number(str) || OJ.is.date(str)) {
                    ret = str.toString();
                }
            }
            return ret;
        }

        var ret1 = tryGetString(inputStr);
        var ret2 = tryGetString(defaultStr);
        var retVal = '';
        if(ret1.length !== 0) {
            retVal = ret1;
        }
        else if(ret1 === ret2 || ret2.length === 0) {
            retVal = ret1;
        } else {
            retVal = ret2;
        }

        return retVal;
    });

}());<commit_msg>OJ.to.number optimizations.<commit_after>/*global OJ:true,$:true,window:true,Number:true*/
(function() {

	OJ.makeSubNameSpace('to');

	OJ.to.lift('bool', function bool(str) {
		var retBool = OJ.is.true(str);
        if(retBool === false || retBool !== true) {
            retBool = false;
        }
		return retBool;
	});

	OJ.to.lift('ES5_ToBool', function(val) {
	    return (val !== false &&
            val !== 0 &&
            val !== '' &&
            val !== null &&
            val !== undefined &&
            (typeof val !== 'number' || !isNaN(val)));
	});

	OJ.to.lift('dateFromTicks', function(tickStr) {
		var ticsDateTime = OJ.string(tickStr);
        var ret, ticks, offset, localOffset, arr;

        if (false === OJ.is.nullOrEmpty(ticsDateTime)) {
            ticsDateTime = ticsDateTime.replace('/', '');
            ticsDateTime = ticsDateTime.replace('Date', '');
            ticsDateTime = ticsDateTime.replace('(', '');
            ticsDateTime = ticsDateTime.replace(')', '');
            arr = ticsDateTime.split('-');
            if (arr.length > 1) {
                ticks = OJ.number(arr[0]);
                offset = OJ.number(arr[1]);
                localOffset = new Date().getTimezoneOffset();
                ret = new Date((ticks - ((localOffset + (offset / 100 * 60)) * 1000)));
            } else if (arr.length === 1) {
                ticks = OJ.number(arr[0]);
                ret = new Date(ticks);
            }
        }
        return ret;
    });

    OJ.to.lift('binary', function(obj){
        var ret = NaN;
        if(obj === 0 || obj === '0' || obj === '' || obj === false || OJ.to.string(obj).toLowerCase().trim() === 'false') {
            ret = 0;
        }
        else if (obj === 1 || obj === '1' || obj === true || OJ.to.string(obj).toLowerCase().trim() === 'true') {
            ret = 1;
        }
        return ret;
    });

    /**
    *   Attempts to converts an arbitrary value to a Number.
    *   Loose falsy values are converted to 0.
    *   Loose truthy values are converted to 1.
    *   All other values are parsed as Integers.
    *   Failures return as NaN.
    *
    */
	OJ.to.lift('number', function(inputNum, defaultNum) {
        'use strict';
        function tryGetNumber(val) {
            var ret;
            if(OJ.is.number(val)) {
                ret = val;
            }
            else if(OJ.is.string(val) || OJ.is.bool(val)) {

                var tryGet = (function(value) {
                    var num = OJ.to.binary(value);
                    if (!OJ.is.number(num) && value) {
                        num = +value;
                    }
                    if (!OJ.is.number(num)) {
                        num = parseInt(value, 0);
                    }
                    return num;
                }(val));

                if (OJ.is.number(tryGet)) {
                    ret = tryGet;
                }
                return ret;
            }
        }

        var retVal = tryGetNumber(inputNum);
        if (!OJ.is.number(retVal)) {
            retVal = tryGetNumber(defaultNum);
            if(!OJ.is.number(retVal)) {
                retVal = Number.NaN;
            }
        }
        return retVal;
    });

	OJ.to.lift('string', function (inputStr, defaultStr) {
        function tryGetString(str) {
            var ret;
            if(OJ.is.string(str)) {
                ret = str;
            } else {
                ret = '';
                if (OJ.is.bool(str) || OJ.is.number(str) || OJ.is.date(str)) {
                    ret = str.toString();
                }
            }
            return ret;
        }

        var ret1 = tryGetString(inputStr);
        var ret2 = tryGetString(defaultStr);
        var retVal = '';
        if(ret1.length !== 0) {
            retVal = ret1;
        }
        else if(ret1 === ret2 || ret2.length === 0) {
            retVal = ret1;
        } else {
            retVal = ret2;
        }

        return retVal;
    });

}());<|endoftext|>


<commit_before>var navh, sh, sideNavh, sideNavAh;
$(window).resize(function () {
    // Formatting with jQuery
    navh = $(".navbar").innerHeight();
    sh = $(window).height();
    var remainH = Math.max(sh - navh, 512);
    sideNavh = remainH / 5;
    sideNavAh = $(".sideNav a:last").height();
    $(".setMargin").css("margin-top", navh);
    $(".setMargin").css("height", remainH);
    $(".sideNav").css("height", sideNavh);
    $("#profilePic a").css("height", sideNavh);
    $(".sideNav a").css("padding-top", (sideNavh - sideNavAh) / 2);
});
$(window).trigger('resize');

$(document).ready(function () {
    // Default hidden classes
    $(".updateProfileView").hide();
    $(".searchResultView").hide();
    $(".outboxView").hide();
    $(".createEventView").hide();
    $(".updateTeamInfoView").hide();
    $(".updateEventInfoView").hide();

    // Formatting with jQuery
    $(window).trigger('resize');

    // click functions that toggle the view
    // toggle the dashboard view
    $("#updateProfile").click(function () {
        $(".profileView").hide();
        $(".updateProfileView").show();
    });
    // toggle the explore view
    $("#searchButton").click(function(){
        $(".recommendationView").hide();
        $(".searchResultView").show();
    });

    // toggle the message view
    $("#inboxButton").click(function(){
        $("#inboxButton").attr("class", "active");
        $("#outboxButton").attr("class", "");
        $(".outboxView").hide();
        $(".inboxView").show();
    });
    $("#outboxButton").click(function(){
        $("#inboxButton").attr("class", "");
        $("#outboxButton").attr("class", "active");
        $(".inboxView").hide();
        $(".outboxView").show();
    });
    $(".inboxView .messageBrief").click(function(){
        $(".inboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    $(".outboxView .messageBrief").click(function(){
        $(".outboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    // toggle the event view
    $("#createNewEvent").click(function(){
        $(".eventView").hide();
        $(".createEventView").show();
    });
    // toggle the team management view
    $("#updateTeamInfo").click(function() {
        $(".teamInfoView").hide();
        $(".updateTeamInfoView").show();
    });
    $("#updateEventInfo").click(function() {
        $(".eventInfoView").hide();
        $(".updateEventInfoView").show();
    });
    $(".fa-times").click(function() {
        $(this).parent().hide();
    });
});

angular.module('teamform-dashboard-app', ['firebase'])
.controller('DashboardCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

    initializeFirebase();
    uid = getCookie("uid");

    //////////////////////////////////////////////////////////////SCOPE FUNCTIONS

    $scope.loadFunc = function() {
        if(uid != "")
        {
            var refPath = "Users/" + getURLParameter("q") + uid;
            retrieveOnceFirebase(firebase, refPath, function(data) {

                if ( data.child("name").val() != null ) {
                    $scope.username = data.child("name").val();
                } else {
                    $scope.username = "";
                }

                if ( data.child("email").val() != null ) {
                    $scope.email = data.child("email").val();
                } else {
                    $scope.email = "";
                }

                if ( data.child("gender").val() != null ) {
                    $scope.gender = data.child("gender").val();
                } else {
                    $scope.gender = "";
                }

                if ( data.child("birthday").val() != null ) {
                    $scope.birthday = data.child("birthday").val();
                } else {
                    $scope.birthday = "";
                }

                if ( data.child("languages").val() != null ) {
                    $scope.languages = data.child("languages").val();
                } else {
                    $scope.languages = "";
                }

                if ( data.child("country").val() != null ) {
                    $scope.country = data.child("country").val();
                } else {
                    $scope.country = "";
                }

                if ( data.child("city").val() != null ) {
                    $scope.city = data.child("city").val();
                } else {
                    $scope.city = "";
                }

                if ( data.child("education").val() != null ) {
                    $scope.education = data.child("education").val();
                } else {
                    $scope.education = "";
                }

                if ( data.child("skills").val() != null ) {
                    $scope.skills = data.child("skills").val();
                } else {
                    $scope.skills = "";
                }

                if ( data.child("introduction").val() != null ) {
                    $scope.introduction = data.child("introduction").val();
                } else {
                    $scope.introduction = "";
                }

                $scope.$apply();
            });
        }
    }

    $scope.UpdateUser = function()
    {
        var userInfo;
        userInfo.Name = username;
        userInfo.Email = email;
        userInfo.Gender = gender;
        userInfo.Birthday = birthday;
        userInfo.Languages = languages;
        userInfo.Country = country;
        userInfo.City = city;
        userInfo.Education = education;
        userInfo.Skills = skills;
        userInfo.Introduction = introduction;

        var refPath = "Users/" + getURLParameter("q") + $scope.uid;
        var ref = firebase.database().ref(refPath);

        ref.set(userInfo, function(){
            window.location.href= "dashboard.html";
        }).catch(function(error) {
            console.log(error);
        });
    }

    //////////////////////////////////////////////////END FUNCTIONS

    $scope.username;
    $scope.email;
    $scope.photoUrl;
    $scope.gender;
    $scope.birthday;
    $scope.languages;
    $scope.education;
    $scope.skills
    $scope.intoduction;

    $scope.loadFunc();

}]);

<commit_msg>moved variable placement<commit_after>var navh, sh, sideNavh, sideNavAh;
$(window).resize(function () {
    // Formatting with jQuery
    navh = $(".navbar").innerHeight();
    sh = $(window).height();
    var remainH = Math.max(sh - navh, 512);
    sideNavh = remainH / 5;
    sideNavAh = $(".sideNav a:last").height();
    $(".setMargin").css("margin-top", navh);
    $(".setMargin").css("height", remainH);
    $(".sideNav").css("height", sideNavh);
    $("#profilePic a").css("height", sideNavh);
    $(".sideNav a").css("padding-top", (sideNavh - sideNavAh) / 2);
});
$(window).trigger('resize');

$(document).ready(function () {
    // Default hidden classes
    $(".updateProfileView").hide();
    $(".searchResultView").hide();
    $(".outboxView").hide();
    $(".createEventView").hide();
    $(".updateTeamInfoView").hide();
    $(".updateEventInfoView").hide();

    // Formatting with jQuery
    $(window).trigger('resize');

    // click functions that toggle the view
    // toggle the dashboard view
    $("#updateProfile").click(function () {
        $(".profileView").hide();
        $(".updateProfileView").show();
    });
    // toggle the explore view
    $("#searchButton").click(function(){
        $(".recommendationView").hide();
        $(".searchResultView").show();
    });

    // toggle the message view
    $("#inboxButton").click(function(){
        $("#inboxButton").attr("class", "active");
        $("#outboxButton").attr("class", "");
        $(".outboxView").hide();
        $(".inboxView").show();
    });
    $("#outboxButton").click(function(){
        $("#inboxButton").attr("class", "");
        $("#outboxButton").attr("class", "active");
        $(".inboxView").hide();
        $(".outboxView").show();
    });
    $(".inboxView .messageBrief").click(function(){
        $(".inboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    $(".outboxView .messageBrief").click(function(){
        $(".outboxView .messageBrief.active").attr("class", "messageBrief");
        $(this).attr("class", "messageBrief active");
    });
    // toggle the event view
    $("#createNewEvent").click(function(){
        $(".eventView").hide();
        $(".createEventView").show();
    });
    // toggle the team management view
    $("#updateTeamInfo").click(function() {
        $(".teamInfoView").hide();
        $(".updateTeamInfoView").show();
    });
    $("#updateEventInfo").click(function() {
        $(".eventInfoView").hide();
        $(".updateEventInfoView").show();
    });
    $(".fa-times").click(function() {
        $(this).parent().hide();
    });
});

angular.module('teamform-dashboard-app', ['firebase'])
.controller('DashboardCtrl', ['$scope', '$firebaseObject', '$firebaseArray', function($scope, $firebaseObject, $firebaseArray) {

    initializeFirebase();
    uid = getCookie("uid");

    $scope.username;
    $scope.email;
    $scope.photoUrl;
    $scope.gender;
    $scope.birthday;
    $scope.languages;
    $scope.education;
    $scope.skills
    $scope.intoduction;

    //////////////////////////////////////////////////////////////SCOPE FUNCTIONS

    $scope.loadFunc = function() {
        if(uid != "")
        {
            var refPath = "Users/" + getURLParameter("q") + uid;
            retrieveOnceFirebase(firebase, refPath, function(data) {

                if ( data.child("name").val() != null ) {
                    $scope.username = data.child("name").val();
                } else {
                    $scope.username = "";
                }

                if ( data.child("email").val() != null ) {
                    $scope.email = data.child("email").val();
                } else {
                    $scope.email = "";
                }

                if ( data.child("gender").val() != null ) {
                    $scope.gender = data.child("gender").val();
                } else {
                    $scope.gender = "";
                }

                if ( data.child("birthday").val() != null ) {
                    $scope.birthday = data.child("birthday").val();
                } else {
                    $scope.birthday = "";
                }

                if ( data.child("languages").val() != null ) {
                    $scope.languages = data.child("languages").val();
                } else {
                    $scope.languages = "";
                }

                if ( data.child("country").val() != null ) {
                    $scope.country = data.child("country").val();
                } else {
                    $scope.country = "";
                }

                if ( data.child("city").val() != null ) {
                    $scope.city = data.child("city").val();
                } else {
                    $scope.city = "";
                }

                if ( data.child("education").val() != null ) {
                    $scope.education = data.child("education").val();
                } else {
                    $scope.education = "";
                }

                if ( data.child("skills").val() != null ) {
                    $scope.skills = data.child("skills").val();
                } else {
                    $scope.skills = "";
                }

                if ( data.child("introduction").val() != null ) {
                    $scope.introduction = data.child("introduction").val();
                } else {
                    $scope.introduction = "";
                }

                $scope.$apply();
            });
        }
    }

    $scope.UpdateUser = function()
    {
        var userInfo;
        userInfo.Name = username;
        userInfo.Email = email;
        userInfo.Gender = gender;
        userInfo.Birthday = birthday;
        userInfo.Languages = languages;
        userInfo.Country = country;
        userInfo.City = city;
        userInfo.Education = education;
        userInfo.Skills = skills;
        userInfo.Introduction = introduction;

        var refPath = "Users/" + getURLParameter("q") + $scope.uid;
        var ref = firebase.database().ref(refPath);

        ref.set(userInfo, function(){
            window.location.href= "dashboard.html";
        }).catch(function(error) {
            console.log(error);
        });
    }

    //////////////////////////////////////////////////END FUNCTIONS

    $scope.loadFunc();

}]);

<|endoftext|>


<commit_before>/*global $:false */
'use strict';

var MovieApp = MovieApp || {
    url: 'http://localhost:3000'
};

MovieApp.createMovie = function(event){
  if (event.preventDefault) {
    event.preventDefault();
  }
  $.ajax({
    url: MovieApp.url + '/movies',
    type: 'POST',
    data: {
      movie: {
        title: $('input#movieTitle').val(),
        gross: $('input#movieGross').val(),
        release: $('input#movieRelease').val(),
        rating: $('input#movierating').val(),
        description: $('textarea#movieDescription').val()
      }
    }
  }).done(function(data){
    MovieApp.resetMovieForm();
    MovieApp.goToMovie(data);
  }).fail();
};

MovieApp.resetMovieForm = function(){
  $('input#movieTitle').val('');
  $('input#movieGross').val('');
  $('input#movieRelease').val('');
  $('input#movieRating').val('');
  $('textArea#movieDescription').val('');
};

MovieApp.goToMovie = function(data){
  console.log(data);
  window.location.href = 'http://localhost:9000/show.html?movie=' + data.id;
};

$(document).ready(function(){
  console.log('movie_new loaded');
  $('#movieForm').submit(MovieApp.createMovie);
});
<commit_msg>resolved conflict<commit_after>/*global $:false */
'use strict';

var MovieApp = MovieApp || {
    url: 'http://localhost:3000'
};

MovieApp.createMovie = function(event){
  if (event.preventDefault) {
    event.preventDefault();
  }
  $.ajax({
    url: MovieApp.url + '/movies',
    type: 'POST',
    data: {
      movie: {
        title: $('input#movieTitle').val(),
        gross: $('input#movieGross').val(),
        release: $('input#movieRelease').val(),
        rating: $('input#movierating').val(),
        description: $('textarea#movieDescription').val()
      }
    }
  }).done(function(data){
    MovieApp.resetMovieForm();
    MovieApp.goToMovie(data);
  }).fail();
};

MovieApp.resetMovieForm = function(){
  $('input#movieTitle').val('');
  $('input#movieGross').val('');
  $('input#movieRelease').val('');
  $('input#movieRating').val('');
  $('textArea#movieDescription').val('');
};

MovieApp.goToMovie = function(data){
  window.location.href = 'http://localhost:9000/show.html?movie=' + data.id;

};

$(document).ready(function(){
  console.log('movie_new loaded');
  $('#movieForm').submit(MovieApp.createMovie);
});
<|endoftext|>


<commit_before>const async = require('async')
const fs = require('fs')
const later = require('later')
const path = require('path')

const getOrderedSchedules = (schedules) => {
  return Object.keys(schedules)
    .sort((a, b) => {
      let sched_a = later.parse.cron(schedules[a].crontab)
      let sched_b = later.parse.cron(schedules[b].crontab)
      schedules[a].prev = new Date(later.schedule(sched_a).prev().getTime())
      schedules[b].prev = new Date(later.schedule(sched_b).prev().getTime())
      return schedules[a].prev > schedules[b].prev
    })
    .map((a) => {
      console.log(schedules[a].prev)
      return schedules[a]
    })
}

const getNextSchedule = (schedules) => {
  let nextSchedule = schedules[Object.keys(schedules)[0]]
  Object.keys(schedules).forEach((a) => {
    let crtab = schedules[a].crontab
    let sched = later.parse.cron(crtab)
    let now = new Date()
    now.setSeconds(now.getSeconds() + 1)
    schedules[a].next = new Date(later.schedule(sched).next(1, now).getTime())
    if (nextSchedule.next < schedules[a].next) {
      nextSchedule = schedules[a]
    }
  })
  return nextSchedule
}

module.exports.render = (_G, configuration, mainCallback) => {
  _G.playbackLog.write(new Date().toJSON() + '\n')
  document.body.style.cursor = 'none'
  if (_G.DEV_MODE) {
    document.body.style.cursor = 'crosshair'
  }
  while (document.getElementById('player').hasChildNodes()) {
    document.getElementById('player').removeChild(document.getElementById('player').lastChild)
  }
  let playerRootNode = document.createElement('div')
  playerRootNode.id = configuration.screenEid
  playerRootNode.className = 'screen'
  document.getElementById('player').appendChild(playerRootNode)

  playerRootNode.stopPlayback = function () {
    playerRootNode.playbackStatus = 'stopped'
    _G.playbackLog.write(new Date().toJSON() + ' Stop  all' + '\n')
    Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
  }

  let configurationNode = document.createElement('pre')
  configurationNode.className = 'configuration'
  configurationNode.innerHTML = JSON.stringify(configuration, null, 4)
  document.getElementById('player').appendChild(configurationNode)

  // Schedules->layouts
  async.forEachOf(configuration.schedules, (schedule, scheduleEid, callback) => {
    schedule.layoutNode = document.createElement('div')
    let layoutNode = schedule.layoutNode
    layoutNode.swConfiguration = configuration
    // layoutNode.swSchedule = schedule
    playerRootNode.appendChild(layoutNode)
    layoutNode.id = layoutNode.parentNode.id + '.' + schedule.layoutEid
    layoutNode.className = 'layout'
    layoutNode.getNextSchedule = getNextSchedule

    layoutNode.stopPlayback = function () {
      layoutNode.playbackStatus = 'stopped'
      _G.playbackLog.write(new Date().toJSON() + ' Stop  layout ' + layoutNode.id + '\n')
      Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
    }

    layoutNode.startPlayback = function () { // this === layoutNode
      layoutNode.playbackStatus = 'started'
      if (schedule.cleanup) {
        playerRootNode.stopPlayback()
      }
      let nextSchedule = this.getNextSchedule(this.swConfiguration.schedules)
      _G.playbackLog.write(new Date().toJSON() + ' Start layout ' + layoutNode.id + '. Play for ' + (nextSchedule.next - new Date()) + ' ms.' + '\n')
      Array.from(this.childNodes).forEach((a) => {
        // console.log(a)
        a.startPlayback()
      })
      let self = this
      setTimeout(() => {
        nextSchedule.layoutNode.startPlayback()
        self.stopPlayback()
      }, nextSchedule.next - new Date())
    }

    // Playlists
    async.forEachOf(schedule.layoutPlaylists, (playlist, layoutPlaylistEid, callback) => {
      playlist.playlistNode = document.createElement('div')
      let playlistNode = playlist.playlistNode
      // playlistNode.swPlaylist = playlist
      layoutNode.appendChild(playlistNode)
      playlistNode.id = playlistNode.parentNode.id + '.' + playlist.playlistEid
      playlistNode.className = 'playlist'
      if (playlist.inPixels) {
        playlistNode.style.top = (playlist.top / schedule.height * 100) + '%'
        playlistNode.style.left = (playlist.left / schedule.width * 100) + '%'
        playlistNode.style.width = (playlist.width / schedule.width * 100) + '%'
        playlistNode.style.height = (playlist.height / schedule.height * 100) + '%'
      }
      else {
        playlistNode.style.top = playlist.top + '%'
        playlistNode.style.left = playlist.left + '%'
        playlistNode.style.width = playlist.width + '%'
        playlistNode.style.height = playlist.height + '%'
      }

      playlistNode.stopPlayback = function () {
        playlistNode.playbackStatus = 'stopped'
        _G.playbackLog.write(new Date().toJSON() + ' Stop  playlist ' + playlistNode.id + '\n')
        Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
      }

      playlistNode.startPlayback = function () { // this === playlistNode
        playlistNode.playbackStatus = 'started'
        _G.playbackLog.write(new Date().toJSON() + ' Start playlist ' + playlistNode.id + '\n')
        this.firstChild.startPlayback()
      }

      // Medias
      let firstMediaNode
      let lastMediaNode
      async.forEachOf(playlist.playlistMedias, (swMedia, playlistMediaEid, callback) => {
        swMedia.mediaNode = document.createElement('div')
        let mediaNode = swMedia.mediaNode
        mediaNode.playlistNode = playlistNode
        mediaNode.swMedia = swMedia

        if (firstMediaNode === undefined) { firstMediaNode = mediaNode }
        if (lastMediaNode !== undefined) {
          lastMediaNode.nextMediaNode = mediaNode
        }
        lastMediaNode = mediaNode

        playlistNode.appendChild(mediaNode)
        mediaNode.id = mediaNode.parentNode.id + '.' + swMedia.mediaEid
        mediaNode.style.visibility = 'hidden'
        mediaNode.className = 'media'

        mediaNode.stopPlayback = function () {
          mediaNode.timers.forEach((timer) => {
            clearTimeout(timer)
          })
          mediaNode.playbackStatus = 'stopped'
          _G.playbackLog.write(new Date().toJSON() + ' Stop  media ' + mediaNode.id + '\n')
          mediaNode.style.visibility = 'hidden'
          this.firstChild.pause()
          this.firstChild.currentTime = 0
        }

        mediaNode.startPlayback = function () { // this === mediaNode
          if (mediaNode.playlistNode.playbackStatus === 'started') {
            mediaNode.playbackStatus = 'started'
            _G.playbackLog.write(new Date().toJSON() + ' Start media ' + mediaNode.id + '\n')
            mediaNode.style.visibility = 'visible'
            this.firstChild.currentTime = 0
            this.firstChild.play()
          }
        }
        insertMedia(_G, mediaNode, swMedia, callback)
      }, function (err) {
        lastMediaNode.nextMediaNode = firstMediaNode
        if (err) { console.error(err.message) }
        callback()
      })
    }, function (err) {
      if (err) { console.error(err.message) }
      callback()
    })
  }, function (err) {
    if (err) { console.error(err.message) }
    mainCallback(null, _G.codes.DOM_RENDERED)
    console.log(_G.codes.DOM_RENDERED)
    getOrderedSchedules(configuration.schedules)
      .forEach((a) => {
        a.layoutNode.startPlayback()
      })
  })
}

const insertMedia = (_G, mediaNode, swMedia, callback) => {
  // console.log('Insert media ' + swMedia.mediaEid + '(' + mediaNode.id + ').', swMedia.type)
  mediaNode.timers = []
  let mediaDomElement
  if (swMedia.type === _G.codes.MEDIA_TYPE_VIDEO) {
    mediaDomElement = document.createElement('VIDEO')
    let mimetype = 'video/' + swMedia.fileName.split('.')[swMedia.fileName.split('.').length - 1]
    mediaDomElement.type = mimetype
    // console.log(mimetype)
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaDomElement.overflow = 'hidden'
    mediaDomElement.autoplay = false
    mediaDomElement.controls = _G.DEV_MODE
    mediaDomElement.muted = swMedia.mute
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.video'
    mediaDomElement.addEventListener('durationchange', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' duration ' + mediaDomElement.duration + 'sec\n')
    })
    mediaDomElement.addEventListener('play', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' started\n')
    })
    mediaDomElement.addEventListener('ended', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' ended. Start delay ' + swMedia.delay * 1e3 + 'ms\n')
      // console.log('mediaNode.stopPlayback() from "video ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_AUDIO) {
    let mediaDomElement = document.createElement('AUDIO')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.audio'
    mediaDomElement.addEventListener('ended', () => {
      console.log('mediaNode.stopPlayback() from "audio ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_IMAGE) {
    let mediaDomElement = document.createElement('IMG')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.img'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {
      // If duration is not set, the image will stay on screen until playlist gets cleaned
      if (swMedia.duration) {
        mediaNode.timers.push(setTimeout(function () {
          console.log('mediaNode.stopPlayback() from "image ended" event.', swMedia)
          mediaNode.stopPlayback()
          mediaNode.timers.push(setTimeout(function () {
            mediaNode.nextMediaNode.startPlayback()
          }, swMedia.delay * 1e3))
        }, swMedia.duration * 1e3))
      }
    }
    mediaDomElement.pause = () => {}
    callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_URL) {
    let mediaDomElement = document.createElement('IFRAME')
    mediaDomElement.src = swMedia.url
    mediaDomElement.scrolling = 'yes'
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.url'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {
      mediaNode.timers.push(setTimeout(function () {
        console.log('mediaNode.stopPlayback() from "URL ended" event.')
        mediaNode.stopPlayback()
        mediaNode.timers.push(setTimeout(function () {
          mediaNode.nextMediaNode.startPlayback()
        }, swMedia.delay * 1e3))
      }, swMedia.duration * 1e3))
    }
    mediaDomElement.pause = () => {}
    callback()
  }
}
<commit_msg>fine timing<commit_after>const async = require('async')
const fs = require('fs')
const later = require('later')
const path = require('path')

const getOrderedSchedules = (schedules) => {
  return Object.keys(schedules)
    .sort((a, b) => {
      let sched_a = later.parse.cron(schedules[a].crontab)
      let sched_b = later.parse.cron(schedules[b].crontab)
      schedules[a].prev = new Date(later.schedule(sched_a).prev().getTime())
      schedules[b].prev = new Date(later.schedule(sched_b).prev().getTime())
      return schedules[a].prev > schedules[b].prev
    })
    .map((a) => {
      console.log(schedules[a].prev)
      return schedules[a]
    })
}

const getNextSchedule = (schedules) => {
  let nextSchedule = schedules[Object.keys(schedules)[0]]
  Object.keys(schedules).forEach((a) => {
    let crtab = schedules[a].crontab
    let sched = later.parse.cron(crtab)
    let now = new Date()
    now.setSeconds(now.getSeconds() + 1)
    schedules[a].next = new Date(later.schedule(sched).next(1, now).getTime())
    if (nextSchedule.next < schedules[a].next) {
      nextSchedule = schedules[a]
    }
  })
  return nextSchedule
}

module.exports.render = (_G, configuration, mainCallback) => {
  _G.playbackLog.write(new Date().toJSON() + '\n')
  document.body.style.cursor = 'none'
  if (_G.DEV_MODE) {
    document.body.style.cursor = 'crosshair'
  }
  while (document.getElementById('player').hasChildNodes()) {
    document.getElementById('player').removeChild(document.getElementById('player').lastChild)
  }
  let playerRootNode = document.createElement('div')
  playerRootNode.id = configuration.screenEid
  playerRootNode.className = 'screen'
  document.getElementById('player').appendChild(playerRootNode)

  playerRootNode.stopPlayback = function () {
    playerRootNode.playbackStatus = 'stopped'
    _G.playbackLog.write(new Date().toJSON() + ' Stop  all' + '\n')
    Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
  }

  let configurationNode = document.createElement('pre')
  configurationNode.className = 'configuration'
  configurationNode.innerHTML = JSON.stringify(configuration, null, 4)
  document.getElementById('player').appendChild(configurationNode)

  // Schedules->layouts
  async.forEachOf(configuration.schedules, (schedule, scheduleEid, callback) => {
    schedule.layoutNode = document.createElement('div')
    let layoutNode = schedule.layoutNode
    layoutNode.swConfiguration = configuration
    // layoutNode.swSchedule = schedule
    playerRootNode.appendChild(layoutNode)
    layoutNode.id = layoutNode.parentNode.id + '.' + schedule.layoutEid
    layoutNode.className = 'layout'
    layoutNode.getNextSchedule = getNextSchedule

    layoutNode.stopPlayback = function () {
      layoutNode.playbackStatus = 'stopped'
      _G.playbackLog.write(new Date().toJSON() + ' Stop  layout ' + layoutNode.id + '\n')
      Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
    }

    layoutNode.startPlayback = function () { // this === layoutNode
      layoutNode.playbackStatus = 'started'
      if (schedule.cleanup) {
        playerRootNode.stopPlayback()
      }
      let nextSchedule = this.getNextSchedule(this.swConfiguration.schedules)
      let self = this
      setTimeout(function () {
        _G.playbackLog.write(new Date().toJSON() + ' Start layout ' + layoutNode.id + '. Play for ' + (nextSchedule.next - new Date()) + ' ms.' + '\n')
        Array.from(self.childNodes).forEach((a) => {
          // console.log(a)
          a.startPlayback()
        })
      }, 10)
      setTimeout(() => {
        nextSchedule.layoutNode.startPlayback()
        self.stopPlayback()
      }, nextSchedule.next - new Date())
    }

    // Playlists
    async.forEachOf(schedule.layoutPlaylists, (playlist, layoutPlaylistEid, callback) => {
      playlist.playlistNode = document.createElement('div')
      let playlistNode = playlist.playlistNode
      // playlistNode.swPlaylist = playlist
      layoutNode.appendChild(playlistNode)
      playlistNode.id = playlistNode.parentNode.id + '.' + playlist.playlistEid
      playlistNode.className = 'playlist'
      if (playlist.inPixels) {
        playlistNode.style.top = (playlist.top / schedule.height * 100) + '%'
        playlistNode.style.left = (playlist.left / schedule.width * 100) + '%'
        playlistNode.style.width = (playlist.width / schedule.width * 100) + '%'
        playlistNode.style.height = (playlist.height / schedule.height * 100) + '%'
      }
      else {
        playlistNode.style.top = playlist.top + '%'
        playlistNode.style.left = playlist.left + '%'
        playlistNode.style.width = playlist.width + '%'
        playlistNode.style.height = playlist.height + '%'
      }

      playlistNode.stopPlayback = function () {
        playlistNode.playbackStatus = 'stopped'
        _G.playbackLog.write(new Date().toJSON() + ' Stop  playlist ' + playlistNode.id + '\n')
        Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
      }

      playlistNode.startPlayback = function () { // this === playlistNode
        playlistNode.playbackStatus = 'started'
        _G.playbackLog.write(new Date().toJSON() + ' Start playlist ' + playlistNode.id + '\n')
        this.firstChild.startPlayback()
      }

      // Medias
      let firstMediaNode
      let lastMediaNode
      async.forEachOf(playlist.playlistMedias, (swMedia, playlistMediaEid, callback) => {
        swMedia.mediaNode = document.createElement('div')
        let mediaNode = swMedia.mediaNode
        mediaNode.playlistNode = playlistNode
        mediaNode.swMedia = swMedia

        if (firstMediaNode === undefined) { firstMediaNode = mediaNode }
        if (lastMediaNode !== undefined) {
          lastMediaNode.nextMediaNode = mediaNode
        }
        lastMediaNode = mediaNode

        playlistNode.appendChild(mediaNode)
        mediaNode.id = mediaNode.parentNode.id + '.' + swMedia.mediaEid
        mediaNode.style.visibility = 'hidden'
        mediaNode.className = 'media'

        mediaNode.stopPlayback = function () {
          mediaNode.timers.forEach((timer) => {
            clearTimeout(timer)
          })
          mediaNode.playbackStatus = 'stopped'
          _G.playbackLog.write(new Date().toJSON() + ' Stop  media ' + mediaNode.id + '\n')
          mediaNode.style.visibility = 'hidden'
          this.firstChild.pause()
          this.firstChild.currentTime = 0
        }

        mediaNode.startPlayback = function () { // this === mediaNode
          if (mediaNode.playlistNode.playbackStatus === 'started') {
            mediaNode.playbackStatus = 'started'
            _G.playbackLog.write(new Date().toJSON() + ' Start media ' + mediaNode.id + '\n')
            mediaNode.style.visibility = 'visible'
            this.firstChild.currentTime = 0
            this.firstChild.play()
          }
        }
        insertMedia(_G, mediaNode, swMedia, callback)
      }, function (err) {
        lastMediaNode.nextMediaNode = firstMediaNode
        if (err) { console.error(err.message) }
        callback()
      })
    }, function (err) {
      if (err) { console.error(err.message) }
      callback()
    })
  }, function (err) {
    if (err) { console.error(err.message) }
    mainCallback(null, _G.codes.DOM_RENDERED)
    console.log(_G.codes.DOM_RENDERED)
    getOrderedSchedules(configuration.schedules)
      .forEach((a) => {
        a.layoutNode.startPlayback()
      })
  })
}

const insertMedia = (_G, mediaNode, swMedia, callback) => {
  // console.log('Insert media ' + swMedia.mediaEid + '(' + mediaNode.id + ').', swMedia.type)
  mediaNode.timers = []
  let mediaDomElement
  if (swMedia.type === _G.codes.MEDIA_TYPE_VIDEO) {
    mediaDomElement = document.createElement('VIDEO')
    let mimetype = 'video/' + swMedia.fileName.split('.')[swMedia.fileName.split('.').length - 1]
    mediaDomElement.type = mimetype
    // console.log(mimetype)
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaDomElement.overflow = 'hidden'
    mediaDomElement.autoplay = false
    mediaDomElement.controls = _G.DEV_MODE
    mediaDomElement.muted = swMedia.mute
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.video'
    mediaDomElement.addEventListener('durationchange', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' duration ' + mediaDomElement.duration + 'sec\n')
    })
    mediaDomElement.addEventListener('play', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' started\n')
    })
    mediaDomElement.addEventListener('ended', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' ended. Start delay ' + swMedia.delay * 1e3 + 'ms\n')
      // console.log('mediaNode.stopPlayback() from "video ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_AUDIO) {
    let mediaDomElement = document.createElement('AUDIO')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.audio'
    mediaDomElement.addEventListener('ended', () => {
      console.log('mediaNode.stopPlayback() from "audio ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_IMAGE) {
    let mediaDomElement = document.createElement('IMG')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.img'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {
      // If duration is not set, the image will stay on screen until playlist gets cleaned
      if (swMedia.duration) {
        mediaNode.timers.push(setTimeout(function () {
          console.log('mediaNode.stopPlayback() from "image ended" event.', swMedia)
          mediaNode.stopPlayback()
          mediaNode.timers.push(setTimeout(function () {
            mediaNode.nextMediaNode.startPlayback()
          }, swMedia.delay * 1e3))
        }, swMedia.duration * 1e3))
      }
    }
    mediaDomElement.pause = () => {}
    callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_URL) {
    let mediaDomElement = document.createElement('IFRAME')
    mediaDomElement.src = swMedia.url
    mediaDomElement.scrolling = 'yes'
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.url'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {
      mediaNode.timers.push(setTimeout(function () {
        console.log('mediaNode.stopPlayback() from "URL ended" event.')
        mediaNode.stopPlayback()
        mediaNode.timers.push(setTimeout(function () {
          mediaNode.nextMediaNode.startPlayback()
        }, swMedia.delay * 1e3))
      }, swMedia.duration * 1e3))
    }
    mediaDomElement.pause = () => {}
    callback()
  }
}
<|endoftext|>


<commit_before>var downloads =
{
	// url - string
	// passFunction - function (string url, string text)
	// failFunction - function (string url, int status)
	add: function (url, passFunction, failFunction)
	{
		var download = {}
		download.url = url;
		download.passFunction = passFunction;
		download.failFunction = failFunction;
		this._queue.push(download);
		this._update();
	},

	// Internal

	_active: [],
	_queue: [],
	_maxActive: 10,
	_update: function()
	{
		if(this._active.length < this._maxActive && this._queue.length > 0)
		{
			var download = this._queue.shift();
			var request = new XMLHttpRequest();
			request.onreadystatechange = function ()
			{
				if(request.readyState == 4)
				{
					if(request.status == 200 || request.status == 0)
					{
						if(download.passFunction)
						{
							download.passFunction(download.url, request.responseText);
						}
					}
					else
					{
						if(download.failFunction)
						{
							download.failFunction(download.url, request.status);
						}
					}
					downloads._update();
				}
			}
			request.open("GET", download.url, true);
			request.send();
		}
	}
}
<commit_msg>Made downloads be able to dynamically load scripts<commit_after>var downloads =
{
	// url - string
	// pass - function (string url, string text)
	// fail - function (string url, int status)
	add: function(url, pass, fail)
	{
		var download = new this._Download(url, pass, fail, false);
		this._queue.push(download);
		this._update();
	},

	// url - string
	// pass - function (string url)
	// fail - function (string url)
	addScript: function(url, load, fail)
	{
		var download = new this._Download(url, load, fail, true);
		this._queue.push(download);
		this._update();
	},

	// Internal

	_Download: function(url, pass, fail, script)
	{
		this.url = url;
		this.pass = pass;
		this.fail = fail;
		this.script = script;
	},

	_active: [],
	_queue: [],
	_maxActive: 10,

	_update: function()
	{
		if(this._active.length < this._maxActive && this._queue.length > 0)
		{
			var download = this._queue.shift();
			if(download.script)
			{
				var script = document.createElement('script');
				script.src = download.url;
				if(download.pass)
				{
					script.onload = download.pass.bind(undefined, download.url);
				}
				if(download.fail)
				{
					script.onerror = download.fail.bind(undefined, download.url);
				}
				document.getElementsByTagName('head')[0].appendChild(script);
			}
			else
			{
				var request = new XMLHttpRequest();
				request.onreadystatechange = function()
				{
					if(request.readyState == 4)
					{
						if(request.status == 200 || request.status == 0)
						{
							if(download.pass)
							{
								download.pass(download.url, request.responseText);
							}
						}
						else
						{
							if(download.fail)
							{
								download.fail(download.url, request.request.status);
							}
						}
						downloads._update();
					}
				}
				request.open("GET", download.url, true);
				request.send();
			}
		}
	}
}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var fs = require('fs');
var path = require('path');

var files = [{
    url: '/dist/bundle.js',
    path: "bundle.js"
}, {
    url: '/dist/style.css',
    path: "style.css"
}, {
    url: '/home',
    path: "index.html"
}, {
    url: '/logo-mini.png',
    path: "logo-mini.png"
}, {
    url: '/logo-white.png',
    path: "logo-white.png"
}, {
    url: '/logo.png',
    path: "logo.png"
}]

module.exports = {
    name: "Seascape",
    extends: "frontend",
    defaults: {
        port: 2095
    },
    exec: function(home, callback) {
        var express = require('express');
        var app = express();

        files.forEach(function(file, index) {
            app.use(file.url, function(req, res) {
                res.sendFile(file.path, {
                    root: __dirname + "/dist/",
                    dotfiles: 'deny',
                    headers: {
                        'x-timestamp': Date.now(),
                        'x-sent': true
                    }
                }, function(error) {
                    if (error) {
                        console.log(error);
                        res.status(error.status).end();
                    } else {
                        console.log('SEASCAPE [SENT]:', file.path);
                    }
                });
            });
        })

        // 404 error
        app.use(function(req, res, next) {
            res.status(404).end('404 - Not Found!');
        })

        app.listen(this.config.port);
    }
}
<commit_msg>Interface is now available through root path<commit_after>var express = require('express');
var path = require('path');
var fs = require('fs');
var path = require('path');

var files = [{
    url: '/dist/bundle.js',
    path: "bundle.js"
}, {
    url: '/dist/style.css',
    path: "style.css"
}, {
    url: '/home',
    path: "index.html"
}, {
    url: '/',
    path: "index.html"
}, {
    url: '/logo-mini.png',
    path: "logo-mini.png"
}, {
    url: '/logo-white.png',
    path: "logo-white.png"
}, {
    url: '/logo.png',
    path: "logo.png"
}]

module.exports = {
    name: "Seascape",
    extends: "frontend",
    defaults: {
        port: 2095
    },
    exec: function(home, callback) {
        var express = require('express');
        var app = express();

        files.forEach(function(file, index) {
            app.use(file.url, function(req, res) {
                res.sendFile(file.path, {
                    root: __dirname + "/dist/",
                    dotfiles: 'deny',
                    headers: {
                        'x-timestamp': Date.now(),
                        'x-sent': true
                    }
                }, function(error) {
                    if (error) {
                        console.log(error);
                        res.status(error.status).end();
                    } else {
                        console.log('SEASCAPE [SENT]:', file.path);
                    }
                });
            });
        })

        // 404 error
        app.use(function(req, res, next) {
            res.status(404).end('404 - Not Found!');
        })

        app.listen(this.config.port);
    }
}
<|endoftext|>


<commit_before>$( document ).ready(function() {

    $("div.headertitle").addClass("page-header");
    $("div.title").addClass("h1");

    $('li > a[href="index.html"] > span').before(" ");
    $('li > a[href="modules.html"] > span').before(" ");
    $('li > a[href="namespaces.html"] > span').before(" ");
    $('li > a[href="annotated.html"] > span').before(" ");
    $('li > a[href="classes.html"] > span').before(" ");
    $('li > a[href="inherits.html"] > span').before(" ");
    $('li > a[href="functions.html"] > span').before(" ");
    $('li > a[href="functions_func.html"] > span').before(" ");
    $('li > a[href="functions_vars.html"] > span').before(" ");
    $('li > a[href="functions_enum.html"] > span').before(" ");
    $('li > a[href="functions_eval.html"] > span').before(" ");
    $('img[src="ftv2ns.png"]').replaceWith('N ');
    $('img[src="ftv2cl.png"]').replaceWith('C ');

    $("ul.tablist").addClass("nav nav-pills nav-justified");
    $("ul.tablist").css("margin-top", "0.5em");
    $("ul.tablist").css("margin-bottom", "0.5em");
    $("li.current").addClass("active");
    $("iframe").attr("scrolling", "yes");

    $("#nav-path > ul").addClass("breadcrumb");

    $("table.params").addClass("table");
    $("div.ingroups").wrapInner("");
    $("div.levels").css("margin", "0.5em");
    $("div.levels > span").addClass("btn btn-default btn-xs");
    $("div.levels > span").css("margin-right", "0.25em");

    $("table.directory").addClass("table table-striped");
    $("div.summary > a").addClass("btn btn-default btn-xs");
    $("table.fieldtable").addClass("table");
    $(".fragment").addClass("well");
    $(".memitem").addClass("panel panel-default");
    $(".memproto").addClass("panel-heading");
    $(".memdoc").addClass("panel-body");
    $("span.mlabel").addClass("label label-info");

    $("table.memberdecls").addClass("table");
    $("[class^=memitem]").addClass("active");

    $("div.ah").addClass("btn btn-default");
    $("span.mlabels").addClass("pull-right");
    $("table.mlabels").css("width", "100%")
    $("td.mlabels-right").addClass("pull-right");

    $("div.ttc").addClass("panel panel-primary");
    $("div.ttname").addClass("panel-heading");
    $("div.ttname a").css("color", 'white');
    $("div.ttdef,div.ttdoc,div.ttdeci").addClass("panel-body");

    $('div.fragment.well div.line:first').css('margin-top', '2px');
    $('div.fragment.well div.line:last').css('margin-bottom', '2px');

	$('table.doxtable').removeClass('doxtable').addClass('table table-striped table-bordered').each(function(){
		$(this).prepend('

');
		$(this).find('tbody > tr:first').prependTo($(this).find('thead'));

		$(this).find('td > span.success').parent().addClass('success');
		$(this).find('td > span.warning').parent().addClass('warning');
		$(this).find('td > span.danger').parent().addClass('danger');
	});

    if($('div.fragment.well div.ttc').length > 0)
    {
        $('div.fragment.well div.line:first').parent().removeClass('fragment well');
    }

    $('table.memberdecls').find('.memItemRight').each(function(){
        $(this).contents().appendTo($(this).siblings('.memItemLeft'));
        $(this).siblings('.memItemLeft').attr('align', 'left');
    });

    $('table.memberdecls').find('.memTemplItemRight').each(function(){
        $(this).contents().appendTo($(this).siblings('.memTemplItemLeft'));
        $(this).siblings('.memTemplItemLeft').attr('align', 'left');
    });

	function getOriginalWidthOfImg(img_element) {
		var t = new Image();
		t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
		return t.width;
	}

	$('div.dyncontent').find('img').each(function(){
		if(getOriginalWidthOfImg($(this)[0]) > $('#content>div.container').width())
			$(this).css('width', '100%');
	});

  /* responsive search box */
  $('#MSearchBox').parent().remove();

  var nav_container = $('

');
  $('#navrow1').parent().prepend(nav_container);

  var left_nav = $('

');
  for (i = 0; i < 6; i++) {
    var navrow = $('#navrow' + i + ' > ul.tablist').detach();
    left_nav.append(navrow);
    $('#navrow' + i).remove();
  }
  var right_nav = $('

').append('\

\

\
        <button aria-expanded="false" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">\
           \
        </button>\

\

\

\
      <button id="search-close" type="button" class="close" aria-label="Close">×</button>\
      <input id="search-field" class="form-control" accesskey="S" onkeydown="searchBox.OnSearchFieldChange(event);" placeholder="Search ..." type="text">\

');
  $(nav_container).append(left_nav);
  $(nav_container).append(right_nav);

  $('#MSearchSelectWindow .SelectionMark').remove();
  var search_selectors = $('#MSearchSelectWindow .SelectItem');
  for (var i = 0; i < search_selectors.length; i += 1) {
    var element_a = $('').text($(search_selectors[i]).text());

    element_a.click(function(){
      $('#search-box .dropdown-menu li').removeClass('active');
      $(this).parent().addClass('active');
      searchBox.OnSelectItem($('#search-box li a').index(this));
      searchBox.Search();
      return false;
    });

    var element = $('

').append(element_a);
    $('#search-box .dropdown-menu').append(element);
  }
  $('#MSearchSelectWindow').remove();

  $('#search-box .close').click(function (){
    searchBox.CloseResultsWindow();
  });

  $('body').append('

');
  $('body').append('

');
  $('body').append('

');

  searchBox.searchLabel = '';
  searchBox.DOMSearchField = function() {
    return document.getElementById("search-field");
  }
  searchBox.DOMSearchClose = function(){
    return document.getElementById("search-close");
  }

  /* search results */
  var results_iframe = $('#MSearchResults').detach();
  $('#MSearchResultsWindow')
    .attr('id', 'search-results-window')
    .addClass('panel panel-default')
    .append(
      '
\

Search Results
\

\

'
    );
  $('#search-results-window .panel-body').append(results_iframe);

  searchBox.DOMPopupSearchResultsWindow = function() {
    return document.getElementById("search-results-window");
  }

  function update_search_results_window() {
    $('#search-results-window').removeClass('panel-default panel-success panel-warning panel-danger')
    var status = $('#MSearchResults').contents().find('.SRStatus:visible');
    if (status.length > 0) {
      switch(status.attr('id')) {
        case 'Loading':
        case 'Searching':
          $('#search-results-window').addClass('panel-warning');
          break;
        case 'NoMatches':
          $('#search-results-window').addClass('panel-danger');
          break;
        default:
          $('#search-results-window').addClass('panel-default');
      }
    } else {
      $('#search-results-window').addClass('panel-success');
    }
  }
  $('#MSearchResults').load(function() {
    $('#MSearchResults').contents().find('link[href="search.css"]').attr('href','../doxygen.css');
    $('#MSearchResults').contents().find('head').append(
      '<link href="../customdoxygen.css" rel="stylesheet" type="text/css">');

    update_search_results_window();

    // detect status changes (only for search with external search backend)
    var observer = new MutationObserver(function(mutations) {
      update_search_results_window();
    });
    var config = { attributes: true};

    var targets = $('#MSearchResults').contents().find('.SRStatus');
    for (i = 0; i < targets.length; i++) {
      observer.observe(targets[i], config);
    }
  });

  /* enumerations */
  $('table.fieldtable').removeClass('fieldtable').addClass('table table-striped table-bordered').each(function(){
    $(this).prepend('

');
    $(this).find('tbody > tr:first').prependTo($(this).find('thead'));

    $(this).find('td > span.success').parent().addClass('success');
    $(this).find('td > span.warning').parent().addClass('warning');
    $(this).find('td > span.danger').parent().addClass('danger');
  });

  /* todo list */
  var todoelements = $('.contents > .textblock > dl.reflist > dt, .contents > .textblock > dl.reflist > dd');
  for (var i = 0; i < todoelements.length; i += 2) {
    $('.contents > .textblock').append(
      '
'
        + "
" + $(todoelements[i]).html() + "
"
        + "
" + $(todoelements[i+1]).html() + "
"
      + '
');
  }
  $('.contents > .textblock > dl').remove();

	$(".memitem").removeClass('memitem');
    $(".memproto").removeClass('memproto');
    $(".memdoc").removeClass('memdoc');
	$("span.mlabel").removeClass('mlabel');
	$("table.memberdecls").removeClass('memberdecls');
    $("[class^=memitem]").removeClass('memitem');
    $("span.mlabels").removeClass('mlabels');
    $("table.mlabels").removeClass('mlabels');
    $("td.mlabels-right").removeClass('mlabels-right');
	$(".navpath").removeClass('navpath');
	$("li.navelem").removeClass('navelem');
	$("a.el").removeClass('el');
	$("div.ah").removeClass('ah');
	$("div.header").removeClass("header");

	$('.mdescLeft').each(function(){
		if($(this).html()==" ") {
			$(this).siblings('.mdescRight').attr('colspan', 2);
			$(this).remove();
		}
	});
  $('td.memItemLeft').each(function(){
    if($(this).siblings('.memItemRight').html()=="") {
      $(this).attr('colspan', 2);
      $(this).siblings('.memItemRight').remove();
    }
  });
	$('td.memTemplItemLeft').each(function(){
		if($(this).siblings('.memTemplItemRight').html()=="") {
			$(this).attr('colspan', 2);
			$(this).siblings('.memTemplItemRight').remove();
		}
	});
});
<commit_msg>close search results by default when page is loaded<commit_after>$( document ).ready(function() {

    $("div.headertitle").addClass("page-header");
    $("div.title").addClass("h1");

    $('li > a[href="index.html"] > span').before(" ");
    $('li > a[href="modules.html"] > span').before(" ");
    $('li > a[href="namespaces.html"] > span').before(" ");
    $('li > a[href="annotated.html"] > span').before(" ");
    $('li > a[href="classes.html"] > span').before(" ");
    $('li > a[href="inherits.html"] > span').before(" ");
    $('li > a[href="functions.html"] > span').before(" ");
    $('li > a[href="functions_func.html"] > span').before(" ");
    $('li > a[href="functions_vars.html"] > span').before(" ");
    $('li > a[href="functions_enum.html"] > span').before(" ");
    $('li > a[href="functions_eval.html"] > span').before(" ");
    $('img[src="ftv2ns.png"]').replaceWith('N ');
    $('img[src="ftv2cl.png"]').replaceWith('C ');

    $("ul.tablist").addClass("nav nav-pills nav-justified");
    $("ul.tablist").css("margin-top", "0.5em");
    $("ul.tablist").css("margin-bottom", "0.5em");
    $("li.current").addClass("active");
    $("iframe").attr("scrolling", "yes");

    $("#nav-path > ul").addClass("breadcrumb");

    $("table.params").addClass("table");
    $("div.ingroups").wrapInner("");
    $("div.levels").css("margin", "0.5em");
    $("div.levels > span").addClass("btn btn-default btn-xs");
    $("div.levels > span").css("margin-right", "0.25em");

    $("table.directory").addClass("table table-striped");
    $("div.summary > a").addClass("btn btn-default btn-xs");
    $("table.fieldtable").addClass("table");
    $(".fragment").addClass("well");
    $(".memitem").addClass("panel panel-default");
    $(".memproto").addClass("panel-heading");
    $(".memdoc").addClass("panel-body");
    $("span.mlabel").addClass("label label-info");

    $("table.memberdecls").addClass("table");
    $("[class^=memitem]").addClass("active");

    $("div.ah").addClass("btn btn-default");
    $("span.mlabels").addClass("pull-right");
    $("table.mlabels").css("width", "100%")
    $("td.mlabels-right").addClass("pull-right");

    $("div.ttc").addClass("panel panel-primary");
    $("div.ttname").addClass("panel-heading");
    $("div.ttname a").css("color", 'white');
    $("div.ttdef,div.ttdoc,div.ttdeci").addClass("panel-body");

    $('div.fragment.well div.line:first').css('margin-top', '2px');
    $('div.fragment.well div.line:last').css('margin-bottom', '2px');

	$('table.doxtable').removeClass('doxtable').addClass('table table-striped table-bordered').each(function(){
		$(this).prepend('

');
		$(this).find('tbody > tr:first').prependTo($(this).find('thead'));

		$(this).find('td > span.success').parent().addClass('success');
		$(this).find('td > span.warning').parent().addClass('warning');
		$(this).find('td > span.danger').parent().addClass('danger');
	});

    if($('div.fragment.well div.ttc').length > 0)
    {
        $('div.fragment.well div.line:first').parent().removeClass('fragment well');
    }

    $('table.memberdecls').find('.memItemRight').each(function(){
        $(this).contents().appendTo($(this).siblings('.memItemLeft'));
        $(this).siblings('.memItemLeft').attr('align', 'left');
    });

    $('table.memberdecls').find('.memTemplItemRight').each(function(){
        $(this).contents().appendTo($(this).siblings('.memTemplItemLeft'));
        $(this).siblings('.memTemplItemLeft').attr('align', 'left');
    });

	function getOriginalWidthOfImg(img_element) {
		var t = new Image();
		t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
		return t.width;
	}

	$('div.dyncontent').find('img').each(function(){
		if(getOriginalWidthOfImg($(this)[0]) > $('#content>div.container').width())
			$(this).css('width', '100%');
	});

  /* responsive search box */
  $('#MSearchBox').parent().remove();

  var nav_container = $('

');
  $('#navrow1').parent().prepend(nav_container);

  var left_nav = $('

');
  for (i = 0; i < 6; i++) {
    var navrow = $('#navrow' + i + ' > ul.tablist').detach();
    left_nav.append(navrow);
    $('#navrow' + i).remove();
  }
  var right_nav = $('

').append('\

\

\
        <button aria-expanded="false" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">\
           \
        </button>\

\

\

\
      <button id="search-close" type="button" class="close" aria-label="Close">×</button>\
      <input id="search-field" class="form-control" accesskey="S" onkeydown="searchBox.OnSearchFieldChange(event);" placeholder="Search ..." type="text">\

');
  $(nav_container).append(left_nav);
  $(nav_container).append(right_nav);

  $('#MSearchSelectWindow .SelectionMark').remove();
  var search_selectors = $('#MSearchSelectWindow .SelectItem');
  for (var i = 0; i < search_selectors.length; i += 1) {
    var element_a = $('').text($(search_selectors[i]).text());

    element_a.click(function(){
      $('#search-box .dropdown-menu li').removeClass('active');
      $(this).parent().addClass('active');
      searchBox.OnSelectItem($('#search-box li a').index(this));
      searchBox.Search();
      return false;
    });

    var element = $('

').append(element_a);
    $('#search-box .dropdown-menu').append(element);
  }
  $('#MSearchSelectWindow').remove();

  $('#search-box .close').click(function (){
    searchBox.CloseResultsWindow();
  });

  $('body').append('

');
  $('body').append('

');
  $('body').append('

');

  searchBox.searchLabel = '';
  searchBox.DOMSearchField = function() {
    return document.getElementById("search-field");
  }
  searchBox.DOMSearchClose = function(){
    return document.getElementById("search-close");
  }

  /* search results */
  var results_iframe = $('#MSearchResults').detach();
  $('#MSearchResultsWindow')
    .attr('id', 'search-results-window')
    .addClass('panel panel-default')
    .append(
      '
\

Search Results
\

\

'
    );
  $('#search-results-window .panel-body').append(results_iframe);

  searchBox.DOMPopupSearchResultsWindow = function() {
    return document.getElementById("search-results-window");
  }

  function update_search_results_window() {
    $('#search-results-window').removeClass('panel-default panel-success panel-warning panel-danger')
    var status = $('#MSearchResults').contents().find('.SRStatus:visible');
    if (status.length > 0) {
      switch(status.attr('id')) {
        case 'Loading':
        case 'Searching':
          $('#search-results-window').addClass('panel-warning');
          break;
        case 'NoMatches':
          $('#search-results-window').addClass('panel-danger');
          break;
        default:
          $('#search-results-window').addClass('panel-default');
      }
    } else {
      $('#search-results-window').addClass('panel-success');
    }
  }
  $('#MSearchResults').load(function() {
    $('#MSearchResults').contents().find('link[href="search.css"]').attr('href','../doxygen.css');
    $('#MSearchResults').contents().find('head').append(
      '<link href="../customdoxygen.css" rel="stylesheet" type="text/css">');

    update_search_results_window();

    // detect status changes (only for search with external search backend)
    var observer = new MutationObserver(function(mutations) {
      update_search_results_window();
    });
    var config = { attributes: true};

    var targets = $('#MSearchResults').contents().find('.SRStatus');
    for (i = 0; i < targets.length; i++) {
      observer.observe(targets[i], config);
    }
  });

  /* enumerations */
  $('table.fieldtable').removeClass('fieldtable').addClass('table table-striped table-bordered').each(function(){
    $(this).prepend('

');
    $(this).find('tbody > tr:first').prependTo($(this).find('thead'));

    $(this).find('td > span.success').parent().addClass('success');
    $(this).find('td > span.warning').parent().addClass('warning');
    $(this).find('td > span.danger').parent().addClass('danger');
  });

  /* todo list */
  var todoelements = $('.contents > .textblock > dl.reflist > dt, .contents > .textblock > dl.reflist > dd');
  for (var i = 0; i < todoelements.length; i += 2) {
    $('.contents > .textblock').append(
      '
'
        + "
" + $(todoelements[i]).html() + "
"
        + "
" + $(todoelements[i+1]).html() + "
"
      + '
');
  }
  $('.contents > .textblock > dl').remove();

	$(".memitem").removeClass('memitem');
    $(".memproto").removeClass('memproto');
    $(".memdoc").removeClass('memdoc');
	$("span.mlabel").removeClass('mlabel');
	$("table.memberdecls").removeClass('memberdecls');
    $("[class^=memitem]").removeClass('memitem');
    $("span.mlabels").removeClass('mlabels');
    $("table.mlabels").removeClass('mlabels');
    $("td.mlabels-right").removeClass('mlabels-right');
	$(".navpath").removeClass('navpath');
	$("li.navelem").removeClass('navelem');
	$("a.el").removeClass('el');
	$("div.ah").removeClass('ah');
	$("div.header").removeClass("header");

	$('.mdescLeft').each(function(){
		if($(this).html()==" ") {
			$(this).siblings('.mdescRight').attr('colspan', 2);
			$(this).remove();
		}
	});
  $('td.memItemLeft').each(function(){
    if($(this).siblings('.memItemRight').html()=="") {
      $(this).attr('colspan', 2);
      $(this).siblings('.memItemRight').remove();
    }
  });
	$('td.memTemplItemLeft').each(function(){
		if($(this).siblings('.memTemplItemRight').html()=="") {
			$(this).attr('colspan', 2);
			$(this).siblings('.memTemplItemRight').remove();
		}
	});
  searchBox.CloseResultsWindow();
});
<|endoftext|>