<commit_before>/*global $, document, window, console*/

/**
 * WebSocket options object specification
 */
srvModule.webSocketOptions = function() {

  // Check against no use of new()
  if (!(this instanceof srvModule.webSocketOptions)) {
    return new srvModule.webSocketOptions();
  }

  this.url = 'ws://' + window.location.host + '/ws';
  this.nodes = [];

  return this;
};

/**
 * WebSocket wrapper to more easily communicate with geoweb server
 */
srvModule.webSocket = function(options) {

  this.events = {
    "message_recieved" : "message_recieved",
    "opened" : "opened",
    "closed" : "closed",
    "ready" : "ready"
  };

  if (!(this instanceof srvModule.webSocket)) {
    return new srvModule.webSocket(options);
  }

  ogs.vgl.object.call(this);

  /** @private */
  var m_that = this;

  /** @private */
  var m_url = options.url || 'ws://' + window.location.host + '/ws';

  /** @private */
  var m_nodes = options.nodes || [];

  /** @private */
  var m_readynodes = {};

  /** @private */
  var m_binders = {};

  /** @private */
  var m_open = false;

  /** @private */
  var m_ws;

  if (window.WebSocket) {
    m_ws = new window.WebSocket(m_url);
  } else if (window.MozWebSocket) {
    m_ws = window.MozWebSocket(m_url);
  } else {
    console.log("[WARNING] WebSocket Not Supported");
    return;
  }

  // Close the websocket when the window closes
  window.onbeforeunload = function (event) {
    m_ws.close(1000, 'Window closed');
    m_that.m_open = false;

    if (!event) {
      event = window.event;
    }
    event.stopPropagation();
    event.preventDefault();
  };

  // websocket connection established
  m_ws.onopen = function() {
    m_that.m_open = true;
    $(m_that).trigger({
      type: m_that.events.opened
    });

    //initiate nodes if needed
    if(m_that.nodes.length == 0) {
      $(m_that).trigger({
	type: m_that.events.ready
      });
    } else {

      m_that.bind('nodemanager', function(node) {
	m_readynodes[node] = true;
	var allReady = true;
	for(var i = 0; i < m_nodes.length; i++) {
	  if(!m_readynodes[m_nodes[i]]) {
	    allReady = false;
	  }
	}
	if(allReady) {
	  $(m_that).trigger({
	    type: m_that.events.ready
	  });
	}
      });

      for(var i = 0; i < m_nodes.length; i++) {
	m_that.message('nodemanager',m_nodes[i]);
      }
    }
  }

  // websocket connection lost
  m_ws.onclosed = function() {
    m_that.m_open = false;
    $(m_that).trigger({
      type: m_that.events.closed
    });
  }

  // Recieved a message from the server
  // trigger event, and call all callbacks registered for this target
  m_ws.onmessage = function (event) {
    $(m_that).trigger({
      type : m_that.events.message_recieved,
      message : event.data
    });

    data = JSON.parse(event.data);
    if(m_binders.hasOwnProperty(data.target)) {
      for(var i in m_binders[data.target]) {
	m_binders[data.target][i].call(m_that, data.message);
      }
    }
  }

  /**
   * Send a signal to a server node
   *
   * @param {String} target
   * @param {String} slot
   * @param {array} args [optional]
   * @param {object} kwargs [optional]
   */
  this.signal = function(node, slot, args, kwargs) {
    args = typeof args !== 'undefined' ? args : [];
    kwargs = typeof kwargs !== 'undefined' ? kwargs : {};
    var json = {
      target:node,
      message: {
	slot: slot,
	args: args,
	kwargs: kwargs
      }
    };

    m_ws.send(JSON.stringify(json));
  };

  /**
   * Send a message to a server node or handler
   *
   * @param {String} target
   * @param {Mixed} message
   */
  this.message = function(node, message) {
    var json = {
      target: node,
      message: message
    };

    m_ws.send(JSON.stringify(json));
  };

  /**
   * Get the url used by this websocket
   *
   * @returns {String}
   */
  this.url = function() {
    return m_url;
  };

  /**
   * Get the open status of this websocket
   *
   * @returns {Boolean}
   */
  this.open = function() {
    return m_open;
  };

  /**
   * Get the underlying websocket
   *
   * @returns {WebSocket}
   */
  this.name = function() {
    return m_ws;
  };

  /**
   * Bind to named websocket messages from the server
   * 'this' for the callback will be this websocket object
   *
   * @param {String} name
   * @param {function} callback
   */
  this.bind = function(name, callback) {
    if( !m_binders.hasOwnProperty(name)) {
      m_binders[name] = [];
    }
    m_binders[name].push(callback);
  }

  /**
   * Unbind from named websocket messages from the server
   *
   * @param {String} name
   * @param {function} callback
   */
  this.unbind = function(name, callback) {
    if( m_binders.hasOwnProperty(name)) {
      index = m_binders[name].indexof(callback);
      if(index != -1) {
	m_binders.splice(index,1);
      }
    }
  }

  /**
   * Unbind all callbacks from named websocket messages from the server
   * If name is blank, all binded functions for all names are removed
   * Otherwise only callbacks binded to that name
   *
   * @param {String} name [optional]
   */
  this.unbindAll = function(name) {
    if(typeof name !== 'undefined') {
      if( m_binders.hasOwnProperty(name)) {
	m_binders[name] = [];
      }
    } else {
      m_binders = {}
    }
  }

  return this;
};

inherit(srvModule.webSocket, ogs.vgl.object);
<commit_msg>Reworked server structure working<commit_after>/*global $, document, window, console*/

/**
 * WebSocket options object specification
 */
srvModule.webSocketOptions = function() {

  // Check against no use of new()
  if (!(this instanceof srvModule.webSocketOptions)) {
    return new srvModule.webSocketOptions();
  }

  this.url = 'ws://' + window.location.host + '/ws';
  this.nodes = [];

  return this;
};

/**
 * WebSocket wrapper to more easily communicate with geoweb server
 */
srvModule.webSocket = function(options) {

  this.events = {
    "message_recieved" : "message_recieved",
    "opened" : "opened",
    "closed" : "closed",
    "ready" : "ready"
  };

  if (!(this instanceof srvModule.webSocket)) {
    return new srvModule.webSocket(options);
  }

  ogs.vgl.object.call(this);

  /** @private */
  var m_that = this;

  /** @private */
  var m_url = options.url || 'ws://' + window.location.host + '/ws';

  /** @private */
  var m_nodes = options.nodes || [];

  /** @private */
  var m_readynodes = {};

  /** @private */
  var m_binders = {};

  /** @private */
  var m_open = false;

  /** @private */
  var m_ws;

  if (window.WebSocket) {
    m_ws = new window.WebSocket(m_url);
  } else if (window.MozWebSocket) {
    m_ws = window.MozWebSocket(m_url);
  } else {
    console.log("[WARNING] WebSocket Not Supported");
    return;
  }

  // Close the websocket when the window closes
  window.onbeforeunload = function (event) {
    m_ws.close(1000, 'Window closed');
    m_open = false;

    if (!event) {
      event = window.event;
    }
    event.stopPropagation();
    event.preventDefault();
  };

  // websocket connection established
  m_ws.onopen = function() {
    m_open = true;
    $(m_that).trigger({
      type: m_that.events.opened
    });

    //initiate nodes if needed
    if(m_nodes.length == 0) {
      $(m_that).trigger({
	type: m_that.events.ready
      });
    } else {

      m_that.bind('nodemanager', function(node) {
	m_readynodes[node] = true;
	var allReady = true;
	for(var i = 0; i < m_nodes.length; i++) {
	  if(!m_readynodes[m_nodes[i]]) {
	    allReady = false;
	  }
	}
	if(allReady) {
	  $(m_that).trigger({
	    type: m_that.events.ready
	  });
	}
      });

      for(var i = 0; i < m_nodes.length; i++) {
	m_that.message('nodemanager',m_nodes[i]);
      }
    }
  }

  // websocket connection lost
  m_ws.onclosed = function() {
    m_open = false;
    $(m_that).trigger({
      type: m_that.events.closed
    });
  }

  // Recieved a message from the server
  // trigger event, and call all callbacks registered for this target
  m_ws.onmessage = function (event) {
    $(m_that).trigger({
      type : m_that.events.message_recieved,
      message : event.data
    });

    data = JSON.parse(event.data);
    if(m_binders.hasOwnProperty(data.target)) {
      for(var i in m_binders[data.target]) {
	m_binders[data.target][i].call(m_that, data.message);
      }
    }
  }

  /**
   * Send a signal to a server node
   *
   * @param {String} target
   * @param {String} slot
   * @param {array} args [optional]
   * @param {object} kwargs [optional]
   */
  this.signal = function(node, slot, args, kwargs) {
    args = typeof args !== 'undefined' ? args : [];
    kwargs = typeof kwargs !== 'undefined' ? kwargs : {};
    var json = {
      target:node,
      message: {
	slot: slot,
	args: args,
	kwargs: kwargs
      }
    };

    m_ws.send(JSON.stringify(json));
  };

  /**
   * Send a message to a server node or handler
   *
   * @param {String} target
   * @param {Mixed} message
   */
  this.message = function(node, message) {
    var json = {
      target: node,
      message: message
    };

    m_ws.send(JSON.stringify(json));
  };

  /**
   * Get the url used by this websocket
   *
   * @returns {String}
   */
  this.url = function() {
    return m_url;
  };

  /**
   * Get the open status of this websocket
   *
   * @returns {Boolean}
   */
  this.open = function() {
    return m_open;
  };

  /**
   * Get the underlying websocket
   *
   * @returns {WebSocket}
   */
  this.name = function() {
    return m_ws;
  };

  /**
   * Bind to named websocket messages from the server
   * 'this' for the callback will be this websocket object
   *
   * @param {String} name
   * @param {function} callback
   */
  this.bind = function(name, callback) {
    if( !m_binders.hasOwnProperty(name)) {
      m_binders[name] = [];
    }
    m_binders[name].push(callback);
  }

  /**
   * Unbind from named websocket messages from the server
   *
   * @param {String} name
   * @param {function} callback
   */
  this.unbind = function(name, callback) {
    if( m_binders.hasOwnProperty(name)) {
      index = m_binders[name].indexof(callback);
      if(index != -1) {
	m_binders.splice(index,1);
      }
    }
  }

  /**
   * Unbind all callbacks from named websocket messages from the server
   * If name is blank, all binded functions for all names are removed
   * Otherwise only callbacks binded to that name
   *
   * @param {String} name [optional]
   */
  this.unbindAll = function(name) {
    if(typeof name !== 'undefined') {
      if( m_binders.hasOwnProperty(name)) {
	m_binders[name] = [];
      }
    } else {
      m_binders = {}
    }
  }

  return this;
};

inherit(srvModule.webSocket, ogs.vgl.object);
<|endoftext|>


<commit_before>import navConfig from './nav.config.json';
import langs from './i18n/route.json';

const registerRoute = (navConfig) => {
  let route = [];
  Object.keys(navConfig).forEach((lang, index) => {
    let navs = navConfig[lang];
    route.push({
      path: `/${ lang }/component`,
      redirect: `/${ lang }/component/installation`,
      component: require(`./pages/${ lang }/component.vue`),
      children: []
    });
    navs.forEach(nav => {
      if (nav.groups) {
        nav.groups.forEach(group => {
          group.list.forEach(nav => {
            addRoute(nav, lang, index);
          });
        });
      } else if (nav.children) {
        nav.children.forEach(nav => {
          addRoute(nav, lang, index);
        });
      } else {
        addRoute(nav, lang, index);
      }
    });
  });
  function addRoute(page, lang, index) {
    const component = page.path === '/changelog'
      ? require(`./pages/${ lang }/changelog.vue`)
      : require(`./docs/${ lang }${page.path}.md`);
    let child = {
      path: page.path.slice(1),
      meta: {
        title: page.title || page.name,
        description: page.description,
        lang
      },
      component: component.default || component
    };

    route[index].children.push(child);
  }

  return route;
};

let route = registerRoute(navConfig);

const generateMiscRoutes = function(lang) {
  let guideRoute = {
    path: `/${ lang }/guide`, // 指南
    redirect: `/${ lang }/guide/design`,
    component: require(`./pages/${ lang }/guide.vue`),
    children: [{
      path: 'design', // 设计原则
      meta: { lang },
      component: require(`./pages/${ lang }/design.vue`)
    }, {
      path: 'nav', // 导航
      meta: { lang },
      component: require(`./pages/${ lang }/nav.vue`)
    }]
  };

  let resourceRoute = {
    path: `/${ lang }/resource`, // 资源
    meta: { lang },
    component: require(`./pages/${ lang }/resource.vue`)
  };

  let indexRoute = {
    path: `/${ lang }`, // 首页
    meta: { lang },
    name: 'home',
    component: require(`./pages/${ lang }/index.vue`)
  };

  return [guideRoute, resourceRoute, indexRoute];
};

langs.forEach(lang => {
  route = route.concat(generateMiscRoutes(lang.lang));
});

route.push({
  path: '/play',
  name: 'play',
  component: require('./play/index.vue')
});

let userLanguage = localStorage.getItem('ELEMENT_LANGUAGE') || window.navigator.language;
let defaultPath = '/en-US';
if (userLanguage.indexOf('zh-') !== -1) {
  defaultPath = '/zh-CN';
}

route = route.concat([{
  path: '/',
  redirect: defaultPath
}, {
  path: '*',
  redirect: defaultPath
}]);

export default route;
<commit_msg>Homepage: fix a navigator.language bug (#1040)<commit_after>import navConfig from './nav.config.json';
import langs from './i18n/route.json';

const registerRoute = (navConfig) => {
  let route = [];
  Object.keys(navConfig).forEach((lang, index) => {
    let navs = navConfig[lang];
    route.push({
      path: `/${ lang }/component`,
      redirect: `/${ lang }/component/installation`,
      component: require(`./pages/${ lang }/component.vue`),
      children: []
    });
    navs.forEach(nav => {
      if (nav.groups) {
        nav.groups.forEach(group => {
          group.list.forEach(nav => {
            addRoute(nav, lang, index);
          });
        });
      } else if (nav.children) {
        nav.children.forEach(nav => {
          addRoute(nav, lang, index);
        });
      } else {
        addRoute(nav, lang, index);
      }
    });
  });
  function addRoute(page, lang, index) {
    const component = page.path === '/changelog'
      ? require(`./pages/${ lang }/changelog.vue`)
      : require(`./docs/${ lang }${page.path}.md`);
    let child = {
      path: page.path.slice(1),
      meta: {
        title: page.title || page.name,
        description: page.description,
        lang
      },
      component: component.default || component
    };

    route[index].children.push(child);
  }

  return route;
};

let route = registerRoute(navConfig);

const generateMiscRoutes = function(lang) {
  let guideRoute = {
    path: `/${ lang }/guide`, // 指南
    redirect: `/${ lang }/guide/design`,
    component: require(`./pages/${ lang }/guide.vue`),
    children: [{
      path: 'design', // 设计原则
      meta: { lang },
      component: require(`./pages/${ lang }/design.vue`)
    }, {
      path: 'nav', // 导航
      meta: { lang },
      component: require(`./pages/${ lang }/nav.vue`)
    }]
  };

  let resourceRoute = {
    path: `/${ lang }/resource`, // 资源
    meta: { lang },
    component: require(`./pages/${ lang }/resource.vue`)
  };

  let indexRoute = {
    path: `/${ lang }`, // 首页
    meta: { lang },
    name: 'home',
    component: require(`./pages/${ lang }/index.vue`)
  };

  return [guideRoute, resourceRoute, indexRoute];
};

langs.forEach(lang => {
  route = route.concat(generateMiscRoutes(lang.lang));
});

route.push({
  path: '/play',
  name: 'play',
  component: require('./play/index.vue')
});

let userLanguage = localStorage.getItem('ELEMENT_LANGUAGE') || window.navigator.language || 'en-US';
let defaultPath = '/en-US';
if (userLanguage.indexOf('zh-') !== -1) {
  defaultPath = '/zh-CN';
}

route = route.concat([{
  path: '/',
  redirect: defaultPath
}, {
  path: '*',
  redirect: defaultPath
}]);

export default route;
<|endoftext|>


<commit_before>var utils = require('./utils');

// Duplex stream factory
module.exports = function factory (instance, context) {

    // create stream object
    var stream = utils.clone(Stream);
    stream._ = instance;
    stream._h = [];
    stream._o = [];
    stream._i = [];

    // merge context into steam
    if (context) {
        for (var prop in context) {
            stream[prop] = context[prop];
        }
    }

    return stream;
};

/**
 * Stream like events.
 *
 * @class Stream
 */
var Stream = {

    // handler for incoming data
    data: function (handler, options) {
        this._h.push([handler, options]);
        return this;
    },

    // send data
    write: function (err, data) {

        // call handlers on output streams
        for (var o = 0, ol = this._o.length, out; o < ol; ++o) {

            // get ouputs input handlers
            out = this._o[o]._h;

            // call data handlers with err and data as arguments
            for (var i = 0, l = out.length; i < l; ++i) {

                //call data handler with stream instance as function scope
                var newData = out[i][0].call(this._, err, data, out[i][1]);

                // overwrite data with transformed data
                if (newData !== undefined) {
                    data = newData;
                }
            }
        }

        // call custom write handler
        if (typeof this._write === 'function') {
            this._write(err, data);
        }

        return this;
    },

    end: function () {

        // remove from output streams
        for (var i = 0, l = this._i.length; i < l; ++i) {
            this._i[i][0]._o.splice(this._i[i][1], 1);
        }

        // remove refs
        this._ = this._i = this._o = undefined;

        // call custom end handler
        if (typeof this._end === 'function') {
            this._end.apply(this, arguments);
        }
    },

    // pipe data to an stream
    pipe: function (stream) {

        // save input stream and output index on output stream
        stream._i.push([this, this._o.length]);

        // push output stream
        this._o.push(stream);

        // return out stream for unix like piping (a.pipe(b).pipe(a))
        return stream;
    }
};
<commit_msg>use out stream as scope for handlers<commit_after>var utils = require('./utils');

// Event stream factory
module.exports = function factory (instance, context) {

    // create stream object
    var stream = utils.clone(Stream);
    stream._ = instance;
    stream._h = [];
    stream._o = [];
    stream._i = [];

    // merge context into steam
    if (context) {
        for (var prop in context) {
            stream[prop] = context[prop];
        }
    }

    return stream;
};

/**
 * Stream like events.
 *
 * @class Stream
 */
var Stream = {

    // handler for incoming data
    data: function (handler, options) {
        this._h.push([handler, options]);
        return this;
    },

    // send data
    write: function (err, data) {

        // call handlers on output streams
        for (var o = 0, ol = this._o.length, stream, handlers; o < ol; ++o) {

            // get ouputs input handlers
            stream = this._o[o];
            handlers = stream._h;

            // call data handlers with err and data as arguments
            for (var i = 0, l = handlers.length; i < l; ++i) {

                //call data handler with stream instance as function scope
                var newData = handlers[i][0].call(stream, err, data, handlers[i][1]);

                // overwrite data with transformed data
                if (newData !== undefined) {
                    data = newData;
                }
            }
        }

        // call custom write handler
        if (typeof this._write === 'function') {
            this._write(err, data);
        }

        return this;
    },

    end: function () {

        // remove from output streams
        for (var i = 0, l = this._i.length; i < l; ++i) {
            // ..call end on output streams??
            this._i[i][0]._o.splice(this._i[i][1], 1);
        }

        // remove refs
        this._ = this._i = this._o = undefined;

        // call custom end handler
        if (typeof this._end === 'function') {
            this._end.apply(this, arguments);
        }
    },

    // pipe data to an stream
    pipe: function (stream) {

        // save input stream and output index on output stream
        stream._i.push([this, this._o.length]);

        // push output stream
        this._o.push(stream);

        // return out stream for unix like piping (a.pipe(b).pipe(a))
        return stream;
    }
};
<|endoftext|>


<commit_before>var CloudCommander, CloudFunc, $;
/* object contains viewer FancyBox
 * https://github.com/fancyapps/fancyBox
 */
CloudCommander.Viewer                       = {
    get: (function(){
        return this.FancyBox;
    })
};

CloudCommander.Viewer.FancyBox              = new CloudCommander.Util();

CloudCommander.Viewer.dir                   = './lib/client/viewer/';
CloudCommander.Viewer.FancyBox.dir          = CloudCommander.Viewer.dir +
    'fancybox/';

/* function return configureation
 * for FancyBox open and
 * onclick (it shoud be
 * different objects)
 */
CloudCommander.Viewer.FancyBox.getConfig    = (function(){
    return{
        beforeShow : (function(){
            CloudCommander.keyBinded = false;
        }),
        beforeClose: (function(){
            CloudCommander.keyBinded = true;
        }),

        openEffect    : 'none',
        closeEffect	: 'none',

        helpers : {
            overlay : {
                opacity: 0.1,
                css : {
                    'background-color' : '#fff'
                }
            }
        },
        padding : 0
    };
});

/* function loads css and js of FancyBox
 * @pParent     - this
 * @pCallBack   -  executes, when everything loaded
 */
CloudCommander.Viewer.FancyBox.load         = (function(pThis, pCallBack){
    var ljsLoad_f = function(){
        var lSrc = pThis.dir + 'jquery.fancybox.pack.js';
        pThis.jsload(lSrc,{
                onload: pCallBack
        });
    };

    var lSrc = pThis.dir +'jquery.fancybox.pack.css';
    pThis.cssLoad({
        src  : lSrc,
        func : {
            onload: ljsLoad_f
        }
    });
});

CloudCommander.Viewer.FancyBox.loadData          = (function(pA){
    var lThis = this;
    var lConfig = this.getConfig();

    this.Images.showLoad();

    $.ajax({
        url     : pA.href,
         error  : (function(jqXHR, textStatus, errorThrown){
             lThis.loading             = false;
             return lThis.Images.showError(jqXHR, textStatus, errorThrown);
         }),

         success:function(data, textStatus, jqXHR){
            /* if we got json - show it */
            if(typeof data === 'object')
                data = JSON.stringify(data, null, 4);

            $.fancybox('
' + data + '
', lConfig);

            lThis.Images.hideLoad();
        }
    });
});

CloudCommander.Viewer.FancyBox.set          = (function(){
    if(this.getByClass('fancybox').length)
        return;
    try{
        /* get current panel (left or right) */
        var lPanel = this.getPanel();

        /* get all file links */
        var lA = this.getByTag('a', lPanel);

        var lThis = this;

        var lDblClick_f = function(pA){
            return function(){
                var lConfig  = lThis.getConfig();
                lConfig.href = pA.href;
                if(pA.rel)
                    $.fancybox(lConfig);
                else
                    lThis.loadData(pA);
            };
        };

        /* first two is not files nor folders*/
        for (var i=2; i < lA.length; i++) {
            var lName = lA[i].title || lA[i].textContent;

            lA[i].className    = 'fancybox';
            if(CloudFunc.checkExtension(lName, ['png','jpg', 'gif','ico'])){
                lA[i].rel          = 'gallery';
            }

            lA[i].ondblclick = lDblClick_f(lA[i]);
        }

    }catch(pError){
        console.log(pError);
    }
});

CloudCommander.Viewer.FancyBox.show         = (function(pParent){
    CloudCommander.Viewer.FancyBox.set();

    var lCurrent = this.getCurrentFile();
    var lA = this.getByClass('fancybox', lCurrent)[0];
    var lConfig = this.getConfig();

    if(lA){
        if(lA.rel)
            $.fancybox.open({ href : lA[0].href },
                lConfig);
        else this.loadData(lA);
    }
});

CloudCommander.Viewer.Keys                  = (function(){
    "use strict";

    var lCallBack_f = (function(){
        var key_event = (function(pEvent){
            /* если клавиши можно обрабатывать */
            if(CloudCommander.keyBinded)
                /* if f3 pressed */
                if(pEvent.keyCode === CloudCommander.KEY.F3){
                    CloudCommander.Viewer.FancyBox.show();

                    pEvent.preventDefault();
                }
        });

        /* добавляем обработчик клавишь */
        if (document.addEventListener)
            document.addEventListener('keydown', key_event, false);

        else{
            var lFunc;
            if(typeof document.onkeydown === 'function')
                lFunc = document.onkeydown;

            document.onkeydown = function(){
                if(lFunc)
                    lFunc();

                key_event();
            };
        }

        /* showing images  preview*/
        CloudCommander.Viewer.FancyBox.show();
    });

    CloudCommander.Viewer.FancyBox.load(this.FancyBox, lCallBack_f);
});<commit_msg>fixed size and selection of viewer<commit_after>var CloudCommander, CloudFunc, $;
/* object contains viewer FancyBox
 * https://github.com/fancyapps/fancyBox
 */
CloudCommander.Viewer                       = {
    get: (function(){
        return this.FancyBox;
    })
};

CloudCommander.Viewer.FancyBox              = new CloudCommander.Util();

CloudCommander.Viewer.dir                   = './lib/client/viewer/';
CloudCommander.Viewer.FancyBox.dir          = CloudCommander.Viewer.dir +
    'fancybox/';

/* function return configureation
 * for FancyBox open and
 * onclick (it shoud be
 * different objects)
 */
CloudCommander.Viewer.FancyBox.getConfig    = (function(){
    var lThis = this;
    return{
        /* function do her work
         * before FauncyBox shows
         */
        beforeShow  : function(){
            CloudCommander.keyBinded = false;
        },

        afterShow   : function(){
            var lEditor = lThis.getById('CloudViewer');
            if(lEditor)
                lEditor.focus();
        },

        beforeClose : function(){
            CloudCommander.keyBinded = true;
        },

        openEffect      : 'none',
        closeEffect     : 'none',
        autoSize        : false,
        height          : window.innerHeight,
        helpers : {
            overlay : {
                opacity: 0.1,
                css : {
                    'background-color'  : '#fff'
                }
            }
        },
        padding : 0
    };
});

/* function loads css and js of FancyBox
 * @pParent     - this
 * @pCallBack   -  executes, when everything loaded
 */
CloudCommander.Viewer.FancyBox.load         = (function(pThis, pCallBack){
    var ljsLoad_f = function(){
        var lSrc = pThis.dir + 'jquery.fancybox.pack.js';
        pThis.jsload(lSrc,{
                onload: pCallBack
        });
    };

    pThis.cssSet({id:'viewer',
            inner : '#CloudViewer{'                         +
                        'font-size: 16px;'                  +
                        'white-space :pre'                  +
                    '}'                                     +
                    '#CloudViewer::selection{'              +
                            'background: #fe57a1;'          +
                            'color: #fff;'                  +
                            'text-shadow: none;'            +
                    '}'
    });

    var lSrc = pThis.dir +'jquery.fancybox.pack.css';
    pThis.cssLoad({
        src  : lSrc,
        func : {
            onload: ljsLoad_f
        }
    });
});

CloudCommander.Viewer.FancyBox.loadData          = (function(pA){
    var lThis = this;
    var lConfig = this.getConfig();

    this.Images.showLoad();

    $.ajax({
        url     : pA.href,
         error  : (function(jqXHR, textStatus, errorThrown){
             lThis.loading             = false;
             return lThis.Images.showError(jqXHR, textStatus, errorThrown);
         }),

         success:function(data, textStatus, jqXHR){
            /* if we got json - show it */
            if(typeof data === 'object')
                data = JSON.stringify(data, null, 4);

            $.fancybox('
' + data + '
', lConfig);

            lThis.Images.hideLoad();
        }
    });
});

CloudCommander.Viewer.FancyBox.set          = (function(){
    if(this.getByClass('fancybox').length)
        return;
    try{
        /* get current panel (left or right) */
        var lPanel = this.getPanel();

        /* get all file links */
        var lA = this.getByTag('a', lPanel);

        var lThis = this;

        var lDblClick_f = function(pA){
            return function(){
                var lConfig  = lThis.getConfig();
                lConfig.href = pA.href;
                if(pA.rel)
                    $.fancybox(lConfig);
                else
                    lThis.loadData(pA);
            };
        };

        /* first two is not files nor folders*/
        for (var i=2; i < lA.length; i++) {
            var lName = lA[i].title || lA[i].textContent;

            lA[i].className    = 'fancybox';
            if(CloudFunc.checkExtension(lName, ['png','jpg', 'gif','ico'])){
                lA[i].rel          = 'gallery';
            }

            lA[i].ondblclick = lDblClick_f(lA[i]);
        }

    }catch(pError){
        console.log(pError);
    }
});

CloudCommander.Viewer.FancyBox.show         = (function(pParent){
    CloudCommander.Viewer.FancyBox.set();

    var lCurrent = this.getCurrentFile();
    var lA = this.getByClass('fancybox', lCurrent)[0];
    var lConfig = this.getConfig();

    if(lA){
        if(lA.rel)
            $.fancybox.open({ href : lA[0].href },
                lConfig);
        else this.loadData(lA);
    }
});

CloudCommander.Viewer.Keys                  = (function(){
    "use strict";

    var lCallBack_f = (function(){
        var key_event = (function(pEvent){
            /* если клавиши можно обрабатывать */
            if(CloudCommander.keyBinded)
                /* if f3 pressed */
                if(pEvent.keyCode === CloudCommander.KEY.F3){
                    CloudCommander.Viewer.FancyBox.show();

                    pEvent.preventDefault();
                }
        });

        /* добавляем обработчик клавишь */
        if (document.addEventListener)
            document.addEventListener('keydown', key_event, false);

        else{
            var lFunc;
            if(typeof document.onkeydown === 'function')
                lFunc = document.onkeydown;

            document.onkeydown = function(){
                if(lFunc)
                    lFunc();

                key_event();
            };
        }

        /* showing images  preview*/
        CloudCommander.Viewer.FancyBox.show();
    });

    CloudCommander.Viewer.FancyBox.load(this.FancyBox, lCallBack_f);
});<|endoftext|>


<commit_before>import { num, arr, installGlobals } from "lively.lang";
import { pt, Color, Point } from "lively.graphics";
import { EventDispatcher, Renderer, Morph, World } from "lively.morphic";
import { ObjectDrawer, Window, Button} from "lively.morphic/widgets.js";

installGlobals();

var {world, renderer, eventDispatcher} = setupWorld();
world.eventDispatcher = eventDispatcher;
window.$$world = world;

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function setupWorld() {
  var world = new World({name: "world", extent: pt(window.innerWidth, window.innerHeight)}),
      renderer = new Renderer(world, document.getElementById("lively-world")).startRenderWorldLoop(),
      eventDispatcher = new EventDispatcher(window, world).install();
  world.addMorph(new ObjectDrawer());
  world.addMorph(new Window({name: "Alice", extent: pt(300, 300), position: pt(200,200),
                             submorphs: [new Button({label: "Click me!", bottomLeft: pt(10,290)}), new Button({label: "Click me!", bottomRight: pt(220,290), active: false})]}));
  world.addMorph(new Window({name: "Bob", extent: pt(200, 300), position: pt(600,200),
                             submorphs: []}));
    world.addMorph(new Window({name: "Carlo", extent: pt(200, 300), position: pt(800,200)}));

  return {world, renderer, eventDispatcher}
}
<commit_msg>add polygon morph to examples<commit_after>import { num, arr, installGlobals } from "lively.lang";
import { pt, Color, Point } from "lively.graphics";
import { EventDispatcher, Renderer, Morph, World, Polygon } from "lively.morphic";
import { ObjectDrawer, Window, Button} from "lively.morphic/widgets.js";

installGlobals();

var {world, renderer, eventDispatcher} = setupWorld();
world.eventDispatcher = eventDispatcher;
window.$$world = world;

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

function setupWorld() {
  var world = new World({name: "world", extent: pt(window.innerWidth, window.innerHeight)}),
      renderer = new Renderer(world, document.getElementById("lively-world")).startRenderWorldLoop(),
      eventDispatcher = new EventDispatcher(window, world).install();
  world.addMorph(new ObjectDrawer());
  world.addMorph(new Window({name: "Alice", extent: pt(300, 300), position: pt(200,200),
                             submorphs: [
                            new Button({label: "Click me!", bottomLeft: pt(10,290)}),
                             new Button({label: "Click me!", bottomRight: pt(220,290), active: false}),
                             new Polygon({name: "poly", vertices: [pt(0,0), pt(100,50), pt(50, 100)],
                                          extent: pt(102,102), fill: Color.orange})]}));
  world.addMorph(new Window({name: "Bob", extent: pt(200, 300), position: pt(600,200),
                             submorphs: []}));
    world.addMorph(new Window({name: "Carlo", extent: pt(200, 300), position: pt(800,200)}));

  return {world, renderer, eventDispatcher}
}
<|endoftext|>


<commit_before>var isLoggedIn = false;

// This is called with the results from from FB.getLoginStatus().

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        loginUserIntoApplication();
        document.getElementById('login_btn').style = "display: none";
        document.getElementById('logout_btn').style = "display: block";
        if(somePlaceIsSelected){
            document.getElementById('actions').style = "visibility: visible";
        }
        isLoggedIn = true;

    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        document.getElementById('status').innerHTML = 'Přihlašte se pomocí Facebooku.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });

};

// Load the SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);
        var usersJSON = createCORSRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users");
        if(!usersJSON) {
            alert(users);
            var users = JSON.parse(usersJSON);
        }

        document.getElementById('status').innerHTML =
            'Přihlášen jako, ' + response.name + '!';
    });
}
function fblogin()
{

    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'email' });

}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    if(!xhr){
        throw new Error('CORS not supported');
    }else{
        xhr.onload = function() {
            console.log(responseText);
            return responseText = xhr.responseText;
        };

        xhr.onerror = function() {
            console.log('There was an error!');
        };
        xhr.send();
    }

}<commit_msg>Test fetchnuti useru z meho API #4<commit_after>var isLoggedIn = false;

// This is called with the results from from FB.getLoginStatus().

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        loginUserIntoApplication();
        document.getElementById('login_btn').style = "display: none";
        document.getElementById('logout_btn').style = "display: block";
        if(somePlaceIsSelected){
            document.getElementById('actions').style = "visibility: visible";
        }
        isLoggedIn = true;

    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        document.getElementById('status').innerHTML = 'Přihlašte se pomocí Facebooku.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });

};

// Load the SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function loginUserIntoApplication() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);
        var usersJSON = createCORSRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/users");
        if(!usersJSON) {
            alert(usersJSON);
            var users = JSON.parse(usersJSON);
        }

        document.getElementById('status').innerHTML =
            'Přihlášen jako, ' + response.name + '!';
    });
}
function fblogin()
{

    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'email' });

}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    if(!xhr){
        throw new Error('CORS not supported');
    }else{
        xhr.onload = function() {
            console.log(responseText);
            return responseText = xhr.responseText;
        };

        xhr.onerror = function() {
            console.log('There was an error!');
        };
        xhr.send();
    }

}<|endoftext|>


<commit_before>var isLoggedIn = false;

// This is called with the results from from FB.getLoginStatus().

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        testAPI();
        document.getElementById('login_btn').style = "display: none";
        document.getElementById('logout_btn').style = "display: block";
        if(somePlaceIsSelected){
            document.getElementById('actions').style = "visibility: visible";
        }
        isLoggedIn = true;

    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        document.getElementById('status').innerHTML = 'Přihlašte se pomocí Facebooku.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });

};

// Load the SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Here we run a very simple test of the Graph API after login is
// successful.  See statusChangeCallback() for when this call is made.
function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me?fields=name,email', function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);

        //httpRequest("GET", "http://localhost/api/)
        document.getElementById('status').innerHTML =
            'Přihlášen jako, ' + response.name + '!';
    });
}
function fblogin()
{

    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'email,name' });

}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}

var httpRequest = function(method, url){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            return xmlHttp.responseText;
    }
    xmlHttp.open(method, url, true); // true for asynchronous
    xmlHttp.send(null);
}<commit_msg>Test FB loginu #10<commit_after>var isLoggedIn = false;

// This is called with the results from from FB.getLoginStatus().

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        testAPI();
        document.getElementById('login_btn').style = "display: none";
        document.getElementById('logout_btn').style = "display: block";
        if(somePlaceIsSelected){
            document.getElementById('actions').style = "visibility: visible";
        }
        isLoggedIn = true;

    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('status').innerHTML = 'Přihlašte se do této aplikace.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        document.getElementById('status').innerHTML = 'Přihlašte se pomocí Facebooku.';
        document.getElementById('login_btn').style = "display: block";
        document.getElementById('logout_btn').style = "display: none";
        document.getElementById('actions').style = "visibility: hidden";
        isLoggedIn = false;

    }
}

function subscribeToEvents() {
    FB.Event.subscribe('auth.logout', logout_event);
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function() {
    FB.init({
        appId      : '177757152673157',
        cookie     : true,  // enable cookies to allow the server to access
                            // the session
        xfbml      : true,  // parse social plugins on this page
        version    : 'v2.5' // use graph api version 2.5
    });

    // Now that we've initialized the JavaScript SDK, we call
    // FB.getLoginStatus().  This function gets the state of the
    // person visiting this page and can return one of three states to
    // the callback you provide.  They can be:
    //
    // 1. Logged into your app ('connected')
    // 2. Logged into Facebook, but not your app ('not_authorized')
    // 3. Not logged into Facebook and can't tell if they are logged into
    //    your app or not.
    //
    // These three cases are handled in the callback function.

    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });

};

// Load the SDK asynchronously
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

// Here we run a very simple test of the Graph API after login is
// successful.  See statusChangeCallback() for when this call is made.
function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me',{ fields: 'name, email' }, function(response) {
        console.log('Successful login for: ' + response.name + " "+response.email);

        //httpRequest("GET", "http://localhost/api/)
        document.getElementById('status').innerHTML =
            'Přihlášen jako, ' + response.name + '!';
    });
}
function fblogin()
{

    FB.login(function (response) {
        if (response.authResponse) {
            checkLoginState();
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    }, { scope: 'email' });

}

var logout_event = function(response) {
    console.log("logout_event");
    console.log(response.status);
    console.log(response);
    checkLoginState();
}

var httpRequest = function(method, url){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            return xmlHttp.responseText;
    }
    xmlHttp.open(method, url, true); // true for asynchronous
    xmlHttp.send(null);
}<|endoftext|>


<commit_before>var util = require('util'),
    Marshal = require('./marshal'),
    Column = require('./column'),
    Row = require('./row'),
    ttype = require('./cassandra/1.0/cassandra_types');

/**
 * NO-Operation for deault callbacks
 * @private
 * @memberOf ColumnFamily
 */
var NOOP = function(){};

/**
 * Default read consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_READ_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Default write consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_WRITE_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Representation of a Column Family
 *
 * @param {Object} definition The Column Family definition
 * @constructor
 */
var ColumnFamily = function(keyspace, definition){
//  ttype.CfDef.call(this, definition);
  this.isSuper = this.column_type === 'Super';
  this.keyspace = keyspace;
  this.connection = keyspace.connection;
  this.definition = definition;
  this.name = definition.name;
  this.columnMarshaller = new Marshal(definition.comparator_type);
  this.valueMarshaller = new Marshal(definition.default_validation_class);
  this.keyMarshaller = new Marshal(definition.key_validation_class);
};
//util.inherits(ColumnFamily, ttype.CfDef);

/**
 * Performs a set command to the cluster
 *
 * @param {String} key The key for the row
 * @param {Object} value The value for the columns as represented by JSON
 * @param {Object} options The options for the insert
 * @param {Function} callback The callback to call once complete
 */
ColumnFamily.prototype.insert = function(key, values, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = {};
  }

  var mutations = [], batch = {}, i = 0, value, prop,
      keys = Object.keys(values), keylen = keys.length,
      ts = new Date(),
      consistency = options.consistencyLevel || DEFAULT_WRITE_CONSISTENCY;

  if (this.isSuper) {
    // TODO: Implement SuperColumns
    throw(new Error('SuperColumns Are Evil!!!'));
  } else {
    // standard
    for (; i < keylen; i += 1) {
      prop = keys[i];
      value = values[prop];

      if(value === null || value === undefined){
        value = '';
      }

      var col = new Column(prop, value, ts, options.ttl);

      mutations.push(new ttype.Mutation({
        column_or_supercolumn: new ttype.ColumnOrSuperColumn({
          column: col.toThrift(this.columnMarshaller, this.valueMarshaller)
        })
      }));
    }
  }

  batch[key] = {};
  batch[key][this.definition.name] = mutations;

  this.connection.execute('batch_mutate', batch, consistency, callback);
};

/**
 * Get a column in a row by its key
 * @param {String} key The key to get
 * @param {Object} options Options for the get, can have start, end, max, consistencyLevel
 *

 *
start: the from part of the column name

 *
end: the to part of the column name

 *
max: the max amount of columns to return

 *
consistencyLevel: the read consistency level

 *

 * @param {Function} callback The callback to invoke once the response has been received
 */
ColumnFamily.prototype.get = function(key, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = undefined;
  }

  callback = callback || NOOP;

  var consistency = options.consistencyLevel || DEFAULT_READ_CONSISTENCY,
      self = this, predicate, parent;

  parent = new ttype.ColumnParent({
    column_family: this.name
  });

  predicate = new ttype.SlicePredicate({
    slice_range: new ttype.SliceRange({
      start:options.start,
      finish:options.finish,
      reversed:options.reversed,
      count:options.max
    })
  });

  function onComplete(err, val){
    if(err){
      callback(err);
      return;
    }

    callback(null, Row.fromThrift(key, val, self));
  }
  this.connection.execute('get_slice', key, parent, predicate, consistency, onComplete);
};

module.exports = ColumnFamily;<commit_msg>fixed issue with getting range slices and getting a row without options<commit_after>var util = require('util'),
    Marshal = require('./marshal'),
    Column = require('./column'),
    Row = require('./row'),
    ttype = require('./cassandra/1.0/cassandra_types');

/**
 * NO-Operation for deault callbacks
 * @private
 * @memberOf ColumnFamily
 */
var NOOP = function(){};

/**
 * Default read consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_READ_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Default write consistency level
 * @private
 * @constant
 * @memberOf ColumnFamily
 */
var DEFAULT_WRITE_CONSISTENCY = ttype.ConsistencyLevel.QUORUM;

/**
 * Representation of a Column Family
 *
 * @param {Object} definition The Column Family definition
 * @constructor
 */
var ColumnFamily = function(keyspace, definition){
//  ttype.CfDef.call(this, definition);
  this.isSuper = this.column_type === 'Super';
  this.keyspace = keyspace;
  this.connection = keyspace.connection;
  this.definition = definition;
  this.name = definition.name;
  this.columnMarshaller = new Marshal(definition.comparator_type);
  this.valueMarshaller = new Marshal(definition.default_validation_class);
  this.keyMarshaller = new Marshal(definition.key_validation_class);
};
//util.inherits(ColumnFamily, ttype.CfDef);

/**
 * Performs a set command to the cluster
 *
 * @param {String} key The key for the row
 * @param {Object} value The value for the columns as represented by JSON
 * @param {Object} options The options for the insert
 * @param {Function} callback The callback to call once complete
 */
ColumnFamily.prototype.insert = function(key, values, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = {};
  }

  var mutations = [], batch = {}, i = 0, value, prop,
      keys = Object.keys(values), keylen = keys.length,
      ts = new Date(),
      consistency = options.consistencyLevel || DEFAULT_WRITE_CONSISTENCY;

  if (this.isSuper) {
    // TODO: Implement SuperColumns
    throw(new Error('SuperColumns Are Evil!!!'));
  } else {
    // standard
    for (; i < keylen; i += 1) {
      prop = keys[i];
      value = values[prop];

      if(value === null || value === undefined){
        value = '';
      }

      var col = new Column(prop, value, ts, options.ttl);

      mutations.push(new ttype.Mutation({
        column_or_supercolumn: new ttype.ColumnOrSuperColumn({
          column: col.toThrift(this.columnMarshaller, this.valueMarshaller)
        })
      }));
    }
  }

  batch[key] = {};
  batch[key][this.definition.name] = mutations;

  this.connection.execute('batch_mutate', batch, consistency, callback);
};

/**
 * Get a column in a row by its key
 * @param {String} key The key to get
 * @param {Object} options Options for the get, can have start, end, max, consistencyLevel
 *

 *
start: the from part of the column name

 *
end: the to part of the column name

 *
max: the max amount of columns to return

 *
consistencyLevel: the read consistency level

 *

 * @param {Function} callback The callback to invoke once the response has been received
 */
ColumnFamily.prototype.get = function(key, options, callback){
  if (typeof options === 'function'){
    callback = options;
    options = {};
  }

  callback = callback || NOOP;

  var consistency = options.consistencyLevel || DEFAULT_READ_CONSISTENCY,
      self = this, predicate, parent;

  parent = new ttype.ColumnParent({
    column_family: this.name
  });

  predicate = new ttype.SlicePredicate({
    slice_range: new ttype.SliceRange({
      start:options.start,
      finish:options.end,
      reversed:options.reversed,
      count:options.max
    })
  });

  function onComplete(err, val){
    if(err){
      callback(err);
      return;
    }

    callback(null, Row.fromThrift(key, val, self));
  }
  this.connection.execute('get_slice', key, parent, predicate, consistency, onComplete);
};

module.exports = ColumnFamily;<|endoftext|>


<commit_before>/* Common JS functions */

function getDefaultDataTableConfig() {
    return {
        "bPaginate": false,
        "bAutoWidth": false,
        "oLanguage": {
            "sSearch": "",
            "sInfo" : "Showing _TOTAL_ nodes",
            "sInfoEmpty": "No nodes found",
            "sInfoFiltered": " (filtering from _MAX_ total)",
            "sZeroRecords": "No nodes to display"
        },
        "oSearch": {
            "sSearch": getSearchText(),
        },
        "aoColumnDefs": [
            /* Expander */ { "bSortable": false, "aTargets": [0] },
            /* Fqdn */ { "bVisible": false, "aTargets": [1] },
            /* Links */ { "bSearchable": false, "aTargets": [-1] }
        ],
        "sDom": '<"top"if>rt<"bottom"lp><"clear">'
    }
}

function getSearchText() {
    /*
     * Gets the predefined search text from the &search page url parameter
     */
    var searchText = '';
    var qs = window.location.search.replace('?', '');
    var pairs = qs.split('&');
    $.each(pairs, function(i, v){
        var pair = v.split('=');
        if (pair[0] == 'search') {
            searchText = pair[1];
        }
    });
    return searchText;
}

function drawNodeListTable(searchText) {
    /*
     * Creates a list of nodes DataTable
     */
    oTable = $('#nodes').dataTable(getDefaultDataTableConfig());
    setSearchBox();
    setExtendedRows(oTable);
}

function buildProgressBar(nodeid, total) {
    var memory_usage = 0;
    NODES_EXTENDED.forEach(function(node) {
        if (nodeid == node['name']) {
            memory_usage = node['kitchen']['data']['memory_usage'];
            return;
        }
    });
    var status = "";
    var progress = 100 * memory_usage / total;
    if (progress > 80) { status = "progress-danger"; }
    else if (progress > 60) { status = "progress-warning"; }
    else { status = "progress-success"; }
    status = " " + status;
    var html = '

';
    html += '' +  memory_usage + ' / ' + total + '
';
    return html;
}

function drawNodeVirtTable(searchText) {
    /*
     * Creates the guests DataTable, grouped by hosts
     */
    // Extend the default DataTable config
    dataTableConfig = getDefaultDataTableConfig();
    dataTableConfig['aoColumnDefs'].push({ "bVisible": false, "aTargets": [2] });  // Grouper column
    dataTableConfig['aaSortingFixed'] = [[ 2, 'asc' ]];
    dataTableConfig['aaSorting'] = [[ 3, 'asc' ]];
    dataTableConfig['fnDrawCallback'] = function (oSettings) {
        if (oSettings.aiDisplay.length == 0) {
            return;
        }
        var nTrs = $('#nodes tbody tr');
        var iColspan = nTrs[0].getElementsByTagName('td').length;
        var sLastGroup = "";
        for (var i=0;i<nTrs.length;i++) {
            var iDisplayIndex = oSettings._iDisplayStart + i;
            var sGroup = '';
            sGroup += oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[2];
            sGroup += '';
            if (sGroup != sLastGroup) {
                var nGroup = document.createElement('tr');
                var nCell = document.createElement('td');
                nCell.colSpan = iColspan;
                nCell.className = "host-grouper";
                sLastGroup = sGroup;
                sGroup += buildProgressBar(
                    oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[1],
                    oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[5].split(" ")[0]
                );
                nCell.innerHTML = sGroup;
                nGroup.appendChild(nCell);
                nTrs[i].parentNode.insertBefore(nGroup, nTrs[i]);
            }
        }
    };
    oTable = $('#nodes').dataTable(dataTableConfig);
    setSearchBox();
    setExtendedRows(oTable);
}

function setSearchBox() {
    /*
    * Sets a predefined string inside the DataTables filter box
    */
    $('#nodes_filter input').attr("placeholder", "Search");
    $('#nodes_filter input:text').focus();
}

function setExtendedRows(oTable) {
    /*
     * Sets an event listener for opening and closing details
     */
    $('#nodes td.control').html('');
    $('#nodes td.control').live('click', function () {
        var nTr = $(this).parents('tr')[0];
        if (oTable.fnIsOpen(nTr)) {
            $(this).html('');
            oTable.fnClose(nTr);
        }
        else {
            $(this).html('');
            oTable.fnOpen(nTr, fnFormatNodeDetails(oTable, nTr), 'details');
        }
    } );
}

function fnFormatNodeDetails (oTable, nTr) {
    /*
     * Establishes the content of the extended row.
     * The node key in DataTables will always be placed in the index 1 column.
     */
    var aData = oTable.fnGetData(nTr);
    var node = undefined;
    for(var i=0;i<NODES.length;i++) {
        if (NODES[i].name.substring(0, aData[1].length) == aData[1]) {
            node = NODES[i];
            break;
        }
    }
    var sOut = '
';
    nodeJson = syntaxHighlight(JSON.stringify(node, undefined, 4));
    sOut += nodeJson;
    sOut += '
';
    return sOut;
}

function syntaxHighlight(json) {
    /*
    * Highlights JSON code
    */
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '' + match + '';
    });
}
<commit_msg>Don't divide by 0<commit_after>/* Common JS functions */

function getDefaultDataTableConfig() {
    return {
        "bPaginate": false,
        "bAutoWidth": false,
        "oLanguage": {
            "sSearch": "",
            "sInfo" : "Showing _TOTAL_ nodes",
            "sInfoEmpty": "No nodes found",
            "sInfoFiltered": " (filtering from _MAX_ total)",
            "sZeroRecords": "No nodes to display"
        },
        "oSearch": {
            "sSearch": getSearchText(),
        },
        "aoColumnDefs": [
            /* Expander */ { "bSortable": false, "aTargets": [0] },
            /* Fqdn */ { "bVisible": false, "aTargets": [1] },
            /* Links */ { "bSearchable": false, "aTargets": [-1] }
        ],
        "sDom": '<"top"if>rt<"bottom"lp><"clear">'
    }
}

function getSearchText() {
    /*
     * Gets the predefined search text from the &search page url parameter
     */
    var searchText = '';
    var qs = window.location.search.replace('?', '');
    var pairs = qs.split('&');
    $.each(pairs, function(i, v){
        var pair = v.split('=');
        if (pair[0] == 'search') {
            searchText = pair[1];
        }
    });
    return searchText;
}

function drawNodeListTable(searchText) {
    /*
     * Creates a list of nodes DataTable
     */
    oTable = $('#nodes').dataTable(getDefaultDataTableConfig());
    setSearchBox();
    setExtendedRows(oTable);
}

function buildProgressBar(nodeid, total) {
    var memory_usage = 0;
    NODES_EXTENDED.forEach(function(node) {
        if (nodeid == node['name']) {
            memory_usage = node['kitchen']['data']['memory_usage'];
            return;
        }
    });
    var status = "";
    var progress = 0;
    total = parseInt(total);
    if (!isNaN(total) && total > 0) {
        progress = 100 * memory_usage / total;
    }
    if (progress > 80) { status = "progress-danger"; }
    else if (progress > 60) { status = "progress-warning"; }
    else { status = "progress-success"; }
    status = " " + status;
    var html = '

';
    html += '' +  memory_usage + ' / ' + total + '
';
    return html;
}

function drawNodeVirtTable(searchText) {
    /*
     * Creates the guests DataTable, grouped by hosts
     */
    // Extend the default DataTable config
    dataTableConfig = getDefaultDataTableConfig();
    dataTableConfig['aoColumnDefs'].push({ "bVisible": false, "aTargets": [2] });  // Grouper column
    dataTableConfig['aaSortingFixed'] = [[ 2, 'asc' ]];
    dataTableConfig['aaSorting'] = [[ 3, 'asc' ]];
    dataTableConfig['fnDrawCallback'] = function (oSettings) {
        if (oSettings.aiDisplay.length == 0) {
            return;
        }
        var nTrs = $('#nodes tbody tr');
        var iColspan = nTrs[0].getElementsByTagName('td').length;
        var sLastGroup = "";
        for (var i=0;i<nTrs.length;i++) {
            var iDisplayIndex = oSettings._iDisplayStart + i;
            var sGroup = '';
            sGroup += oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[2];
            sGroup += '';
            if (sGroup != sLastGroup) {
                var nGroup = document.createElement('tr');
                var nCell = document.createElement('td');
                nCell.colSpan = iColspan;
                nCell.className = "host-grouper";
                sLastGroup = sGroup;
                sGroup += buildProgressBar(
                    oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[1],
                    oSettings.aoData[oSettings.aiDisplay[iDisplayIndex]]._aData[5].split(" ")[0]
                );
                nCell.innerHTML = sGroup;
                nGroup.appendChild(nCell);
                nTrs[i].parentNode.insertBefore(nGroup, nTrs[i]);
            }
        }
    };
    oTable = $('#nodes').dataTable(dataTableConfig);
    setSearchBox();
    setExtendedRows(oTable);
}

function setSearchBox() {
    /*
    * Sets a predefined string inside the DataTables filter box
    */
    $('#nodes_filter input').attr("placeholder", "Search");
    $('#nodes_filter input:text').focus();
}

function setExtendedRows(oTable) {
    /*
     * Sets an event listener for opening and closing details
     */
    $('#nodes td.control').html('');
    $('#nodes td.control').live('click', function () {
        var nTr = $(this).parents('tr')[0];
        if (oTable.fnIsOpen(nTr)) {
            $(this).html('');
            oTable.fnClose(nTr);
        }
        else {
            $(this).html('');
            oTable.fnOpen(nTr, fnFormatNodeDetails(oTable, nTr), 'details');
        }
    } );
}

function fnFormatNodeDetails (oTable, nTr) {
    /*
     * Establishes the content of the extended row.
     * The node key in DataTables will always be placed in the index 1 column.
     */
    var aData = oTable.fnGetData(nTr);
    var node = undefined;
    for(var i=0;i<NODES.length;i++) {
        if (NODES[i].name.substring(0, aData[1].length) == aData[1]) {
            node = NODES[i];
            break;
        }
    }
    var sOut = '
';
    nodeJson = syntaxHighlight(JSON.stringify(node, undefined, 4));
    sOut += nodeJson;
    sOut += '
';
    return sOut;
}

function syntaxHighlight(json) {
    /*
    * Highlights JSON code
    */
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '' + match + '';
    });
}
<|endoftext|>


<commit_before>var controller = {
  dynamicProperties: {
    videoId: function(data) {
      return data.uri.substr(8);
    },
    nameTrunc: function(data) {
      return data.name.substr(0, 25) + "...";
    }
  },
  resources: {
    videos: {
      url:"resources/videos.json",
      dataKey: "data"
    }
  }
}

$(function() {
  new Reuq(controller);
})
<commit_msg>refactor: rename controller to app<commit_after>var app = {
  dynamicProperties: {
    videoId: function(data) {
      return data.uri.substr(8);
    },
    nameTrunc: function(data) {
      return data.name.substr(0, 25) + "...";
    }
  },
  resources: {
    videos: {
      url:"resources/videos.json",
      dataKey: "data"
    }
  }
}

$(function() {
  new Reuq(app);
})
<|endoftext|>


<commit_before>var _    = require('lodash');
var util = require('util');

module.exports = commandChart;

function commandChart (token, options) {
  this.token = token;
  this.options = options;
}

commandChart.prototype.handle = function (req, res, cb) {
  /*
  {
    "text": "<http://chart.finance.yahoo.com...>",
    "attachments": [
      { "image_url": "<http://chart.finance.yahoo.com...>" }
    ]
  }
  */
  res.setHeader('content-type', 'application/json');
  var chartUrl = "http://chart.finance.yahoo.com/t?lang=en-US&region=US&width=300&height=180&s=";
  var symbol = req.body.text;
  chartUrl += symbol;
  console.log(chartUrl);
  //var output = '<'+chartUrl+'>';
  //var output = '{"text":' + ' "<' + chartUrl + '>"' + ', "unfurl_link": true}';
  var output = '{';
  output += '"text":' + ' "<' + chartUrl + '>" ,';
  output += '"attachments":' + "[";
  output += "{" + '"image_url":' + ' "<' + chartUrl + '>"' + "}";
  output += '"]"';
  output += '}';
  cb(null, output);
};
<commit_msg>Changing to use attachments and image_url<commit_after>var _    = require('lodash');
var util = require('util');

module.exports = commandChart;

function commandChart (token, options) {
  this.token = token;
  this.options = options;
}

commandChart.prototype.handle = function (req, res, cb) {
  /*
  {
    "text": "<http://chart.finance.yahoo.com...>",
    "attachments": [
      { "image_url": "<http://chart.finance.yahoo.com...>" }
    ]
  }
  */
  res.setHeader('content-type', 'application/json');
  var chartUrl = "http://chart.finance.yahoo.com/t?lang=en-US&region=US&width=300&height=180&s=";
  var symbol = req.body.text;
  chartUrl += symbol;
  console.log(chartUrl);
  //var output = '<'+chartUrl+'>';
  //var output = '{"text":' + ' "<' + chartUrl + '>"' + ', "unfurl_link": true}';
  var output = '{';
  output += '"text":' + ' "<' + chartUrl + '>" ,';
  output += '"attachments":' + '[';
  output += '{' + '"image_url":' + ' "<' + chartUrl + '>"' + '}';
  output += ']';
  output += '}';
  cb(null, output);
};
<|endoftext|>


<commit_before>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(FILL_ME_IN);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */

      expect(productsICanEat.length).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(FILL_ME_IN);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = FILL_ME_IN;    /* try chaining range() and reduce() */

    expect(233168).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */
  /*
  it("should find the largest prime factor of a composite number", function () {

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });
  */
});
<commit_msg>partially complete AboutApplyingWhatWeHaveLearnt.js<commit_after>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

  /*********************************************************************************/

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */
      productsIcanEat = _(products).filter(function(item){
        if(!products[item].containsNuts){
          if(!products[item][ingredients]).any("mushrooms"){
            return products[item][name];
          }
        }
      });

      expect(productsICanEat.length).toBe(1);
  });

  /*********************************************************************************/

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(FILL_ME_IN);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = FILL_ME_IN;    /* try chaining range() and reduce() */

    expect(233168).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */
  /*
  it("should find the largest prime factor of a composite number", function () {

  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {

  });

  it("should find the 10001st prime", function () {

  });
  */
});
<|endoftext|>