<commit_before>/*
 * Geddy JavaScript Web development framework
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

var md = require('marked');
var hljs = require('highlight.js');
md.setOptions({
  gfm: true
, pedantic: false
, highlight: function (code, lang) {
    return hljs.highlightAuto(code).value;
  }
});

var Main = function () {

  this.error = function (req, resp, params) {
    console.log(params.error);
    this.respond(params, {
      format: 'html'
    , template: 'app/views/main/error'
    });
  };

  this.index = function (req, resp, params) {
    this.respond(params, {
      format: 'html'
    , template: 'app/views/main/index'
    });
  };

  this.documentation = function (req, resp, params) {
    var self = this
    , docs = []
    , count = 0

    // once we've got a list of commits, get the tree
    // for the latest commit
    , gotCommits = function (err, commits) {
      if (err) {
        params.error = err;
        return self.error(req, resp, params);
      }
      var commit = commits[0] && commits[0].commit
        , url = commit.tree && commit.tree.url;
      return getTree(url, gotTree);
    }

    // once we've got the first tree, get 'docs' tree
    // once we've got the 'docs' tree, call gotTree
    , getTree = function (url, callback) {
        var tree;
        opts.url = url;
        geddy.request(opts, function (err, trees) {
          if (err || !trees) {
            params.error = err;
            return self.error(req, resp, params);
          }
          for (var i in trees.tree) {
            tree = trees.tree[i];
            if (tree.path == 'docs') {
              return getTree(tree.url, gotTree);
            }
          }
          return callback(err, trees.tree);
        });
    }
    , getBlob = function (paths, i, callback) {
      var options = {
        url: paths[i].url
      , dataType: 'json'
      }
      geddy.request(options, function (err, resp) {

        if (err) {
          params.error = err;
          return self.error(req, resp, params)
        }

        var content = (resp.content) ? new Buffer(resp.content, 'base64').toString('utf8') : ''
          , name = paths[i].path.replace('.md','').split('-')
          , subs = []
          , lines = content.split('\n');
        for (var l in lines) {
          if (lines[l].indexOf('#### ') == 0) {
            subs.push(geddy.string.trim(lines[l].replace('#### ', '')));
          }
        }
        docs[parseInt(name[0]) - 1] = {
          name: name[1]
        , content: md(content)
        , subs: subs
        };
        return respond(paths.length);
      });
    }

    // once we've got the 'docs' tree,
    // parse it and call getBlob for each file
    , gotTree = function (err, tree) {
      if (err) {
        params.error = err;
        return self.error(req, resp, params);
      }

      for (var i in tree) {
        getBlob(tree, i, respond);
      }
    }

    // once we've got everything done, respond with data
    , respond = function (total) {
      count++;
      if (count == total) {
        self.respond({docs: docs}, {
          format: 'html'
        , template: 'app/views/main/documentation'
        });
      }
    }

    // inital call to get the commits
    , opts = {
        url: 'https://api.github.com/repos/mde/geddy/commits'
      , dataType: 'json'
    }
    geddy.request(opts, gotCommits);
  };

  this.tutorial = function (req, resp, params) {
    var self = this;

    // respond to the request
    var respond = function (sections, content) {
      self.respond({sections: sections, content: content}, {
        format: 'html'
      , template: 'app/views/main/tutorial'
      });
    }

    // find the sections
    var gotTutorial = function (err, tutorial) {
      var content = md(tutorial);
      var lines = tutorial.split('\n');
      var sections = [];
      for (var i in lines) {
        if (lines[i].indexOf('### ') == 0) {
          sections.push(geddy.string.trim(lines[i].replace("###", '')));
        }
      }
      respond(sections, content);
    }

    // get the tutorial markdown file
    geddy.request({url: 'https://raw.github.com/mde/geddy/master/tutorial.md'}, gotTutorial);
  };

  this.changelog = function (req, resp, params) {
    var self = this;

    // respond to the request
    var respond = function (sections, content) {
      self.respond({sections: sections, content: content}, {
        format: 'html'
      , template: 'app/views/main/changelog'
      });
    }

    // find the sections
    var gotTutorial = function (err, tutorial) {
      var content = md(tutorial);
      var lines = tutorial.split('\n');
      var sections = [];
      for (var i in lines) {
        if (lines[i].indexOf('### ') == 0) {
          sections.push(geddy.string.trim(lines[i].replace("###", '')));
        }
      }
      respond(sections, content);
    }

    // get the tutorial markdown file
    geddy.request({url: 'https://raw.github.com/mde/geddy/master/changelog.md'}, gotTutorial);
  };

  this.community = function (req, resp, params) {
    var self = this;
    var gotStars = function (err, stars) {
      self.respond({stars: stars}, {
        format: 'html'
      , template: 'app/views/main/community'
      });
    };

    // get stargazers
    var opts = {
      url: 'https://api.github.com/repos/mde/geddy/stargazers?page='+(Math.floor(Math.random()*10)+1)
    , dataType: 'json'
    };
    geddy.request(opts, gotStars);
  };

  this.faq = function (req, resp, params) {
    this.respond(params, {
      format: 'html'
    , template: 'app/views/main/faq'
    });
  };

};

exports.Main = Main;

<commit_msg>Fucking GitHub wants a User-Agent string<commit_after>/*
 * Geddy JavaScript Web development framework
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

var md = require('marked');
var hljs = require('highlight.js');
md.setOptions({
  gfm: true
, pedantic: false
, highlight: function (code, lang) {
    return hljs.highlightAuto(code).value;
  }
});

var Main = function () {

  this.error = function (req, resp, params) {
    console.log(params.error);
    this.respond(params, {
      format: 'html'
    , template: 'app/views/main/error'
    });
  };

  this.index = function (req, resp, params) {
    this.respond(params, {
      format: 'html'
    , template: 'app/views/main/index'
    });
  };

  this.documentation = function (req, resp, params) {
    var self = this
    , docs = []
    , count = 0

    // once we've got a list of commits, get the tree
    // for the latest commit
    , gotCommits = function (err, commits) {
      if (err) {
        params.error = err;
        return self.error(req, resp, params);
      }
      var commit = commits[0] && commits[0].commit
        , url = commit.tree && commit.tree.url;
      return getTree(url, gotTree);
    }

    // once we've got the first tree, get 'docs' tree
    // once we've got the 'docs' tree, call gotTree
    , getTree = function (url, callback) {
        var tree;
        opts.url = url;
        opts.headers = {'User-Agent': 'GeddyJS documentation site'}

        geddy.request(opts, function (err, trees) {
          if (err || !trees) {
            params.error = err;
            return self.error(req, resp, params);
          }
          for (var i in trees.tree) {
            tree = trees.tree[i];
            if (tree.path == 'docs') {
              return getTree(tree.url, gotTree);
            }
          }
          return callback(err, trees.tree);
        });
    }
    , getBlob = function (paths, i, callback) {
      var options = {
        url: paths[i].url
      , dataType: 'json'
      , headers: {'User-Agent': 'GeddyJS documentation site'}
      }
      geddy.request(options, function (err, resp) {

        if (err) {
          params.error = err;
          return self.error(req, resp, params)
        }

        var content = (resp.content) ? new Buffer(resp.content, 'base64').toString('utf8') : ''
          , name = paths[i].path.replace('.md','').split('-')
          , subs = []
          , lines = content.split('\n');
        for (var l in lines) {
          if (lines[l].indexOf('#### ') == 0) {
            subs.push(geddy.string.trim(lines[l].replace('#### ', '')));
          }
        }
        docs[parseInt(name[0]) - 1] = {
          name: name[1]
        , content: md(content)
        , subs: subs
        };
        return respond(paths.length);
      });
    }

    // once we've got the 'docs' tree,
    // parse it and call getBlob for each file
    , gotTree = function (err, tree) {
      if (err) {
        params.error = err;
        return self.error(req, resp, params);
      }

      for (var i in tree) {
        getBlob(tree, i, respond);
      }
    }

    // once we've got everything done, respond with data
    , respond = function (total) {
      count++;
      if (count == total) {
        self.respond({docs: docs}, {
          format: 'html'
        , template: 'app/views/main/documentation'
        });
      }
    }

    // inital call to get the commits
    , opts = {
        url: 'https://api.github.com/repos/mde/geddy/commits'
      , dataType: 'json'
      , headers: {'User-Agent': 'GeddyJS documentation site'}
    }
    geddy.request(opts, gotCommits);
  };

  this.tutorial = function (req, resp, params) {
    var self = this;

    // respond to the request
    var respond = function (sections, content) {
      self.respond({sections: sections, content: content}, {
        format: 'html'
      , template: 'app/views/main/tutorial'
      });
    }

    // find the sections
    var gotTutorial = function (err, tutorial) {
      var content = md(tutorial);
      var lines = tutorial.split('\n');
      var sections = [];
      for (var i in lines) {
        if (lines[i].indexOf('### ') == 0) {
          sections.push(geddy.string.trim(lines[i].replace("###", '')));
        }
      }
      respond(sections, content);
    }

    // get the tutorial markdown file
    geddy.request({
      url: 'https://raw.github.com/mde/geddy/master/tutorial.md'
      , headers: {'User-Agent': 'GeddyJS documentation site'}
      }, gotTutorial);
  };

  this.changelog = function (req, resp, params) {
    var self = this;

    // respond to the request
    var respond = function (sections, content) {
      self.respond({sections: sections, content: content}, {
        format: 'html'
      , template: 'app/views/main/changelog'
      });
    }

    // find the sections
    var gotTutorial = function (err, tutorial) {
      var content = md(tutorial);
      var lines = tutorial.split('\n');
      var sections = [];
      for (var i in lines) {
        if (lines[i].indexOf('### ') == 0) {
          sections.push(geddy.string.trim(lines[i].replace("###", '')));
        }
      }
      respond(sections, content);
    }

    // get the tutorial markdown file
    geddy.request({
      url: 'https://raw.github.com/mde/geddy/master/changelog.md'
      , headers: {'User-Agent': 'GeddyJS documentation site'}

      }, gotTutorial);
  };

  this.community = function (req, resp, params) {
    var self = this;
    var gotStars = function (err, stars) {
      self.respond({stars: stars}, {
        format: 'html'
      , template: 'app/views/main/community'
      });
    };

    // get stargazers
    var opts = {
      url: 'https://api.github.com/repos/mde/geddy/stargazers?page='+(Math.floor(Math.random()*10)+1)
    , dataType: 'json'
      , headers: {'User-Agent': 'GeddyJS documentation site'}
    };
    geddy.request(opts, gotStars);
  };

  this.faq = function (req, resp, params) {
    this.respond(params, {
      format: 'html'
    , template: 'app/views/main/faq'
    });
  };

};

exports.Main = Main;

<|endoftext|>


<commit_before>var DownloadButton = {
  /* the template for the image urls */
  imageUrlTemplate: Mirador.Handlebars.compile(
    '{{imageBaseUrl}}/full/{{size}}/0/default.jpg'
  ),

  /* the template for the link button */
  buttonTemplate: Mirador.Handlebars.compile([
    '',
    '',
    '',
    '
',
    '
',
    'IIIF-Manifest',
    '
',
    '{{#each imageUrls}}',
    '
',
    '',
    'JPG ({{this.title}})',
    '
',
    '{{/each}}',
    '
',
    ''
  ].join('')),

  sizes: ['full', '250,'],

  /* extracts image urls from the viewer window */
  extractImageUrls: function(viewerWindow){
    var currentImgIndex = viewerWindow.focusModules.ImageView.currentImgIndex;
    if(viewerWindow.manifest.jsonLd.viewingDirection == "right-to-left"){
        currentImgIndex = viewerWindow.manifest.jsonLd.sequences[0].canvases.length - currentImgIndex;
    }

    var currentImage = viewerWindow.imagesList[currentImgIndex];
    var imageBaseUrl = Mirador.Iiif.getImageUrl(currentImage);
    var ratio = currentImage.height / currentImage.width;

    var imageUrls = [];
    this.sizes.forEach(function(size){
      imageUrls.push({
        'href': viewerWindow.currentImageMode !== 'ImageView' ? '#' : this.imageUrlTemplate({
          'imageBaseUrl': imageBaseUrl, 'size': size
        }),
        'title': size === 'full' ? currentImage.width + 'x' + currentImage.height : parseInt(size) + 'x' + Math.ceil(parseInt(size) * ratio)
      });
    }.bind(this));
    return imageUrls;
  },

  /* initializes the plugin, i.e. adds an event handler */
  init: function(){
    Mirador.Handlebars.registerHelper('eq', function(first, second){
      return first === second;
    });
    this.injectWindowEventHandler();
    this.injectWorkspaceEventHandler();
  },

  /* injects the button to the window menu */
  injectButtonToMenu: function(windowButtons, manifestUrl, imageUrls){
    $(windowButtons).prepend(this.buttonTemplate({
      'imageUrls': imageUrls,
      'manifestUrl': manifestUrl,
    }));
  },

  /* injects the needed window event handler */
  injectWindowEventHandler: function(){
    var this_ = this;
    var origBindNavigation = Mirador.Window.prototype.bindNavigation;
    Mirador.Window.prototype.bindNavigation = function(){
      origBindNavigation.apply(this);
      this.element.find('.window-manifest-navigation').on(
        'mouseenter', '.mirador-icon-download', function(){
          this.element.find('.download-list').stop().slideFadeToggle(300);
        }.bind(this)
      ).on(
        'mouseleave', '.mirador-icon-download', function(){
          this.element.find('.download-list').stop().slideFadeToggle(300);
        }.bind(this)
      );
    };
    var origBindEvents = Mirador.Window.prototype.bindEvents;
    Mirador.Window.prototype.bindEvents = function(){
      origBindEvents.apply(this);
      this.eventEmitter.subscribe('windowUpdated', function(evt, data){
        if(this.id !== data.id || !data.viewType){
          return;
        }
        if(this.element.find('.mirador-icon-download').length === 0){
          var manifestUrl = this.manifest.jsonLd['@id'];
          var windowButtons = this.element.find('.window-manifest-navigation');
          this_.injectButtonToMenu(windowButtons, manifestUrl, this_.sizes.reduce(function(fakeImageUrls){
            fakeImageUrls.push({
              'href': '#',
              'title': 'n.a.'
            });
            return fakeImageUrls;
          }, []));
        }
        if(data.viewType === 'ImageView'){
          var imageUrls = this_.extractImageUrls(this);
          this.element.find('.image-link').removeClass('disabled').attr(
            'title', function(index){ return 'JPG (' + imageUrls[index].title + ')'; }
          ).find('a').attr(
            'href', function(index){ return imageUrls[index].href; }
          ).find('span.dimensions').text(
            function(index){ return imageUrls[index].title; }
          );
        }else{
          this.element.find('.image-link').addClass('disabled').find('span.dimensions').text('n.a.');
        }
      }.bind(this));
    };
  },

  /* injects the needed workspace event handler */
  injectWorkspaceEventHandler: function(){
    var this_ = this;
    var origFunc = Mirador.Workspace.prototype.bindEvents;
    Mirador.Workspace.prototype.bindEvents = function(){
      origFunc.apply(this);
      this.eventEmitter.subscribe('windowAdded', function(evt, data){
        var viewerWindow = this.windows.filter(function(currentWindow){
          return currentWindow.id === data.id;
        })[0];
        var manifestUrl = viewerWindow.manifest.jsonLd['@id'];
        var imageUrls = this_.extractImageUrls(viewerWindow);
        var windowButtons = viewerWindow.element.find('.window-manifest-navigation');
        this_.injectButtonToMenu(windowButtons, manifestUrl, imageUrls);
      }.bind(this));
    };
  }
};

$(document).ready(function(){
  DownloadButton.init();
});
<commit_msg>Fix variable name because it is not a single button anymore<commit_after>var DownloadButton = {
  /* the template for the image urls */
  imageUrlTemplate: Mirador.Handlebars.compile(
    '{{imageBaseUrl}}/full/{{size}}/0/default.jpg'
  ),

  /* the template for the link button */
  menuTemplate: Mirador.Handlebars.compile([
    '',
    '',
    '',
    '
',
    '
',
    'IIIF-Manifest',
    '
',
    '{{#each imageUrls}}',
    '
',
    '',
    'JPG ({{this.title}})',
    '
',
    '{{/each}}',
    '
',
    ''
  ].join('')),

  sizes: ['full', '250,'],

  /* extracts image urls from the viewer window */
  extractImageUrls: function(viewerWindow){
    var currentImgIndex = viewerWindow.focusModules.ImageView.currentImgIndex;
    if(viewerWindow.manifest.jsonLd.viewingDirection == "right-to-left"){
        currentImgIndex = viewerWindow.manifest.jsonLd.sequences[0].canvases.length - currentImgIndex;
    }

    var currentImage = viewerWindow.imagesList[currentImgIndex];
    var imageBaseUrl = Mirador.Iiif.getImageUrl(currentImage);
    var ratio = currentImage.height / currentImage.width;

    var imageUrls = [];
    this.sizes.forEach(function(size){
      imageUrls.push({
        'href': viewerWindow.currentImageMode !== 'ImageView' ? '#' : this.imageUrlTemplate({
          'imageBaseUrl': imageBaseUrl, 'size': size
        }),
        'title': size === 'full' ? currentImage.width + 'x' + currentImage.height : parseInt(size) + 'x' + Math.ceil(parseInt(size) * ratio)
      });
    }.bind(this));
    return imageUrls;
  },

  /* initializes the plugin, i.e. adds an event handler */
  init: function(){
    Mirador.Handlebars.registerHelper('eq', function(first, second){
      return first === second;
    });
    this.injectWindowEventHandler();
    this.injectWorkspaceEventHandler();
  },

  /* injects the button to the window menu */
  injectButtonToMenu: function(windowButtons, manifestUrl, imageUrls){
    $(windowButtons).prepend(this.menuTemplate({
      'imageUrls': imageUrls,
      'manifestUrl': manifestUrl,
    }));
  },

  /* injects the needed window event handler */
  injectWindowEventHandler: function(){
    var this_ = this;
    var origBindNavigation = Mirador.Window.prototype.bindNavigation;
    Mirador.Window.prototype.bindNavigation = function(){
      origBindNavigation.apply(this);
      this.element.find('.window-manifest-navigation').on(
        'mouseenter', '.mirador-icon-download', function(){
          this.element.find('.download-list').stop().slideFadeToggle(300);
        }.bind(this)
      ).on(
        'mouseleave', '.mirador-icon-download', function(){
          this.element.find('.download-list').stop().slideFadeToggle(300);
        }.bind(this)
      );
    };
    var origBindEvents = Mirador.Window.prototype.bindEvents;
    Mirador.Window.prototype.bindEvents = function(){
      origBindEvents.apply(this);
      this.eventEmitter.subscribe('windowUpdated', function(evt, data){
        if(this.id !== data.id || !data.viewType){
          return;
        }
        if(this.element.find('.mirador-icon-download').length === 0){
          var manifestUrl = this.manifest.jsonLd['@id'];
          var windowButtons = this.element.find('.window-manifest-navigation');
          this_.injectButtonToMenu(windowButtons, manifestUrl, this_.sizes.reduce(function(fakeImageUrls){
            fakeImageUrls.push({
              'href': '#',
              'title': 'n.a.'
            });
            return fakeImageUrls;
          }, []));
        }
        if(data.viewType === 'ImageView'){
          var imageUrls = this_.extractImageUrls(this);
          this.element.find('.image-link').removeClass('disabled').attr(
            'title', function(index){ return 'JPG (' + imageUrls[index].title + ')'; }
          ).find('a').attr(
            'href', function(index){ return imageUrls[index].href; }
          ).find('span.dimensions').text(
            function(index){ return imageUrls[index].title; }
          );
        }else{
          this.element.find('.image-link').addClass('disabled').find('span.dimensions').text('n.a.');
        }
      }.bind(this));
    };
  },

  /* injects the needed workspace event handler */
  injectWorkspaceEventHandler: function(){
    var this_ = this;
    var origFunc = Mirador.Workspace.prototype.bindEvents;
    Mirador.Workspace.prototype.bindEvents = function(){
      origFunc.apply(this);
      this.eventEmitter.subscribe('windowAdded', function(evt, data){
        var viewerWindow = this.windows.filter(function(currentWindow){
          return currentWindow.id === data.id;
        })[0];
        var manifestUrl = viewerWindow.manifest.jsonLd['@id'];
        var imageUrls = this_.extractImageUrls(viewerWindow);
        var windowButtons = viewerWindow.element.find('.window-manifest-navigation');
        this_.injectButtonToMenu(windowButtons, manifestUrl, imageUrls);
      }.bind(this));
    };
  }
};

$(document).ready(function(){
  DownloadButton.init();
});
<|endoftext|>


<commit_before>'use strict';
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose'),
	jwt = require('jwt-simple');

// multithreading
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

 if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  // http.createServer(function(req, res) {
  //   res.writeHead(200);
  //   res.end("hello world\n");
  // }).listen(8000);

	// Bootstrap db connection
	var db = mongoose.connect(config.db, function(err) {
		if (err) {
			console.error('\x1b[31m', 'Could not connect to MongoDB!');
			console.log(err);
		}
	});

	// Init the express application
	var app = require('./config/express')(db);

	// Set the secret for encoding/decoding JWT tokens
	app.set('jwtTokenSecret', 'studiocenter-auditions-jwt');

	// Bootstrap passport config
	require('./config/passport')();

	// Start the app by listening on <port>
	var server = app.listen(config.port);

	var io = require('socket.io').listen(server);

	app.set('socketio', io);
	app.set('server', server);

	// Expose app
	exports = module.exports = app;

}

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);<commit_msg>enable redis socketio<commit_after>'use strict';
/**
 * Module dependencies.
 */
var init = require('./config/init')(),
	config = require('./config/config'),
	mongoose = require('mongoose'),
	jwt = require('jwt-simple');

// multithreading
var cluster = require('cluster'),
	sio = require('socket.io'),
	sio_redis = require('socket.io-redis'),
	numCPUs = require('os').cpus().length;

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

 if (cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
  // Workers can share any TCP connection
  // In this case its a HTTP server
  // http.createServer(function(req, res) {
  //   res.writeHead(200);
  //   res.end("hello world\n");
  // }).listen(8000);

	// Bootstrap db connection
	var db = mongoose.connect(config.db, function(err) {
		if (err) {
			console.error('\x1b[31m', 'Could not connect to MongoDB!');
			console.log(err);
		}
	});

	// Init the express application
	var app = require('./config/express')(db);

	// Set the secret for encoding/decoding JWT tokens
	app.set('jwtTokenSecret', 'studiocenter-auditions-jwt');

	// Bootstrap passport config
	require('./config/passport')();

	// Start the app by listening on <port>
	var server = app.listen(config.port);

	var io = sio(server);

	io.adapter(sio_redis({ host: 'localhost', port: 6379 }));

	app.set('socketio', io);
	app.set('server', server);

	// Expose app
	exports = module.exports = app;

}

// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);<|endoftext|>


<commit_before>const { description } = require('../../package');
const getConfig = require('vuepress-bar');

const { sidebar: retrievedSidebar } = getConfig({ filter: (meta) => meta.sidebar !== false });
const seoTitle = 'Altair GraphQL Client';
const seoImage = '/assets/img/app-shot.png';
module.exports = {
  /**
   * Ref：https://v1.vuepress.vuejs.org/config/#title
   */
  title: 'Altair GraphQL Client',
  /**
   * Ref：https://v1.vuepress.vuejs.org/config/#description
   */
  description: description,

  /**
   * Extra tags to be injected to the page HTML `<head>`
   *
   * ref：https://v1.vuepress.vuejs.org/config/#head
   */
  head: [
    ['meta', { name: 'theme-color', content: '#3eaf7c' }],
    ['meta', { name: 'apple-mobile-web-app-capable', content: 'yes' }],
    ['meta', { name: 'apple-mobile-web-app-status-bar-style', content: 'black' }],
    ['link', { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=DM+Sans:400,500,700&display=swap' }],
    ['link', { rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.css' }],
    ['script', { src: 'https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js', 'data-cfasync': 'false' }],

    // SEO
    ['meta', { name: 'description', content: description }],
    ['meta', { itemprop: 'name', content: seoTitle }],
    ['meta', { itemprop: 'description', content: description }],
    ['meta', { itemprop: 'image', content: seoImage }],
    ['meta', { name: 'author', content: 'Samuel Imolorhe' }],
    ['meta', { property: 'og:type', content: 'website' }],
    ['meta', { property: 'og:title', content: seoTitle }],
    ['meta', { property: 'og:description', content: description }],
    ['meta', { property: 'og:image', content: seoImage }],
    ['meta', { property: 'twitter:card', content: 'summary_large_image' }],
    ['meta', { property: 'twitter:title', content: seoTitle }],
    ['meta', { property: 'twitter:description', content: description }],
    ['meta', { property: 'twitter:image', content: seoImage }],
  ],

  /**
   * Theme configuration, here is the default theme configuration for VuePress.
   *
   * ref：https://v1.vuepress.vuejs.org/theme/default-theme-config.html
   */
  themeConfig: {
    repo: 'imolorhe/altair',
    editLinks: false,
    docsDir: 'site',
    editLinkText: '',
    lastUpdated: true,
    smoothScroll: true,
    nav: [
      {
        text: 'Docs',
        link: '/docs/',
      },
      {
        text: 'Twitter',
        link: 'https://twitter.com/AltairGraphQL'
      },
      {
        text: 'Donate',
        link: 'https://opencollective.com/altair/donate'
      },
    ],
    sidebar: retrievedSidebar[0].children,
    // sidebar: {
    //   '/docs/': [
    //     {
    //       title: 'Guide',
    //       collapsable: false,
    //       children: [
    //         '',
    //         'using-vue',
    //       ]
    //     }
    //   ],
    // }
  },

  /**
   * Apply plugins，ref：https://v1.vuepress.vuejs.org/zh/plugin/
   */
  plugins: [
    '@vuepress/plugin-back-to-top',
    '@vuepress/plugin-medium-zoom',
    'seo',
    [
      '@vuepress/google-analytics',
      {
        'ga': 'UA-41432833-7',
      }
    ],
    [
      require('./plugins/github-metadata'),
      {
        owner: 'imolorhe',
        repo: 'altair',
      }
    ],
  ]
}
<commit_msg>Enabled edit link in docs<commit_after>const { description } = require('../../package');
const getConfig = require('vuepress-bar');

const { sidebar: retrievedSidebar } = getConfig({ filter: (meta) => meta.sidebar !== false });
const seoTitle = 'Altair GraphQL Client';
const seoImage = '/assets/img/app-shot.png';
module.exports = {
  /**
   * Ref：https://v1.vuepress.vuejs.org/config/#title
   */
  title: 'Altair GraphQL Client',
  /**
   * Ref：https://v1.vuepress.vuejs.org/config/#description
   */
  description: description,

  /**
   * Extra tags to be injected to the page HTML `<head>`
   *
   * ref：https://v1.vuepress.vuejs.org/config/#head
   */
  head: [
    ['meta', { name: 'theme-color', content: '#3eaf7c' }],
    ['meta', { name: 'apple-mobile-web-app-capable', content: 'yes' }],
    ['meta', { name: 'apple-mobile-web-app-status-bar-style', content: 'black' }],
    ['link', { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=DM+Sans:400,500,700&display=swap' }],
    ['link', { rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.css' }],
    ['script', { src: 'https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js', 'data-cfasync': 'false' }],

    // SEO
    ['meta', { name: 'description', content: description }],
    ['meta', { itemprop: 'name', content: seoTitle }],
    ['meta', { itemprop: 'description', content: description }],
    ['meta', { itemprop: 'image', content: seoImage }],
    ['meta', { name: 'author', content: 'Samuel Imolorhe' }],
    ['meta', { property: 'og:type', content: 'website' }],
    ['meta', { property: 'og:title', content: seoTitle }],
    ['meta', { property: 'og:description', content: description }],
    ['meta', { property: 'og:image', content: seoImage }],
    ['meta', { property: 'twitter:card', content: 'summary_large_image' }],
    ['meta', { property: 'twitter:title', content: seoTitle }],
    ['meta', { property: 'twitter:description', content: description }],
    ['meta', { property: 'twitter:image', content: seoImage }],
  ],

  /**
   * Theme configuration, here is the default theme configuration for VuePress.
   *
   * ref：https://v1.vuepress.vuejs.org/theme/default-theme-config.html
   */
  themeConfig: {
    repo: 'imolorhe/altair',
    editLinks: false,
    docsDir: 'site/src', // defaults to false, set to true to enable
    editLinks: true,
    // custom text for edit link. Defaults to "Edit this page"
    editLinkText: 'Help us improve this page!',
    docsBranch: 'staging',
    lastUpdated: true,
    smoothScroll: true,
    nav: [
      {
        text: 'Docs',
        link: '/docs/',
      },
      {
        text: 'Twitter',
        link: 'https://twitter.com/AltairGraphQL'
      },
      {
        text: 'Donate',
        link: 'https://opencollective.com/altair/donate'
      },
    ],
    sidebar: retrievedSidebar[0].children,
    // sidebar: {
    //   '/docs/': [
    //     {
    //       title: 'Guide',
    //       collapsable: false,
    //       children: [
    //         '',
    //         'using-vue',
    //       ]
    //     }
    //   ],
    // }
  },

  /**
   * Apply plugins，ref：https://v1.vuepress.vuejs.org/zh/plugin/
   */
  plugins: [
    '@vuepress/plugin-back-to-top',
    '@vuepress/plugin-medium-zoom',
    'seo',
    [
      '@vuepress/google-analytics',
      {
        'ga': 'UA-41432833-7',
      }
    ],
    [
      require('./plugins/github-metadata'),
      {
        owner: 'imolorhe',
        repo: 'altair',
      }
    ],
  ]
}
<|endoftext|>


<commit_before>(function(window)
{
    var Gitana = window.Gitana;

    Gitana.Branch = Gitana.AbstractPlatformObject.extend(
    /** @lends Gitana.Branch.prototype */
    {
        /**
         * @constructs
         * @augments Gitana.AbstractPlatformObject
         *
         * @class Branch
         *
         * @param {Gitana.Repository} repository
         * @param [Object] object json object (if no callback required for populating)
         */
        constructor: function(repository, object)
        {
            this.base(repository.getPlatform(), object);

            this.objectType = "Gitana.Branch";

            //////////////////////////////////////////////////////////////////////////////////////////////
            //
            // PRIVILEGED METHODS
            //
            //////////////////////////////////////////////////////////////////////////////////////////////

            /**
             * Gets the Gitana Repository object.
             *
             * @inner
             *
             * @returns {Gitana.Repository} The Gitana Repository object
             */
            this.getRepository = function() { return repository; };

            /**
             * Gets the Gitana Repository id.
             *
             * @inner
             *
             * @returns {String} The Gitana Repository id
             */
            this.getRepositoryId = function() { return repository.getId(); };
        },

        /**
         * @OVERRIDE
         */
        getType: function()
        {
            return Gitana.TypedIDConstants.TYPE_BRANCH;
        },

        /**
         * @OVERRIDE
         */
        getUri: function()
        {
            return "/repositories/" + this.getRepositoryId() + "/branches/" + this.getId();
        },

        /**
         * @override
         */
        clone: function()
        {
            return this.getFactory().branch(this.getRepository(), this.object);
        },

        /**
         * @override
         */
        del: function()
        {
            // TODO - not implemented for branches
            return this;
        },

        /**
         * @returns {Boolean} whether this is the master branch
         */
        isMaster: function()
        {
            return (this.getType().toLowerCase() == "master");
        },

        /**
         * @return {String} the type of branch ("master" or "custom")
         */
        getType: function()
        {
            return this.get("type");
        },

        /**
         * @return {String} the tip changeset of the branch
         */
        getTip: function()
        {
            return this.get("tip");
        },

        /**
         * Acquires a list of mount nodes under the root of the repository.
         *
         * @chained node map
         *
         * @public
         *
         * @param [Object] pagination
         */
        listMounts: function(pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainGet(chainable, uriFunction, params);
        },

        /**
         * Reads a node.
         *
         * @chained node
         *
         * @public
         *
         * @param {String} nodeId the node id
         */
        readNode: function(nodeId)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/" + nodeId;
            };

            var chainable = this.getFactory().node(this);
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Reads the root node.
         *
         * @chained node
         *
         * @public
         */
        rootNode: function()
        {
            return this.readNode("root");
        },

        /**
         * Create a node
         *
         * @chained node
         *
         * @public
         *
         * @param [Object] object JSON object
         */
        createNode: function(object)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/nodes";
            };

            var chainable = this.getFactory().node(this);
            return this.chainCreate(chainable, object, uriFunction);
        },

        /**
         * Searches the branch.
         *
         * @chained node map
         *
         * Config should be:
         *
         *    {
         *       "search": {
         *           ... Elastic Search Config Block
         *       }
         *    }
         *
         * For a full text term search, you can simply provide text in place of a config json object.
         *
         * See the Elastic Search documentation for more advanced examples
         *
         * @public
         *
         * @param search
         * @param [Object] pagination
         */
        searchNodes: function(search, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            if (Gitana.isString(search))
            {
                search = {
                    "search": search
                };
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/search";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, search);
        },

        /**
         * Queries for nodes on the branch.
         *
         * Config should be:
         *
         *    {
         *       Gitana query configs
         *    }
         *
         * @chained node map
         *
         * @public
         *
         * @param {Object} query
         * @param [Object] pagination
         */
        queryNodes: function(query, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/query";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, query);
        },

        /**
         * Performs a bulk check of permissions against permissioned objects of type node.
         *
         * Example of checks array:
         *
         * [{
         *    "permissionedId": "<permissionedId>",
         *    "principalId": "<principalId>",
         *    "permissionId": "<permissionId>"
         * }]
         *
         * The callback receives an array of results, example:
         *
         * [{
         *    "permissionedId": "<permissionedId>",
         *    "principalId": "<principalId>",
         *    "permissionId": "<permissionId>",
         *    "result": true
         * }]
         *
         * The order of elements in the array will be the same for checks and results.
         *
         * @param checks
         * @param callback
         */
        checkNodePermissions: function(checks, callback)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/permissions/check";
            };

            var object = {
                "checks": checks
            };

            return this.chainPostResponse(this, uriFunction, {}, object).then(function() {
                callback.call(this, this.response["results"]);
            });
        },

        /**
         * Reads the person object for a security user.
         *
         * @chained node
         *
         * @param {Object} user either the user id, user name or the user object
         * @param [Boolean] createIfNotFound whether to create the person object if it isn't found
         */
        readPersonNode: function(user, createIfNotFound)
        {
            var self = this;

            var principalDomainQualifiedId = this.extractPrincipalDomainQualifiedId(user);

            var uriFunction = function()
            {
                var uri = self.getUri() + "/person/acquire?id=" + principalDomainQualifiedId;
                if (createIfNotFound)
                {
                    uri += "&createIfNotFound=" + createIfNotFound;
                }

                return uri;
            };

            var chainable = this.getFactory().node(this, "n:person");
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Reads the group object for a security group.
         *
         * @chained node
         *
         * @param {Object} group eitehr the group id, group name or the group object
         * @param [Boolean] createIfNotFound whether to create the group object if it isn't found
         */
        readGroupNode: function(group, createIfNotFound)
        {
            var self = this;

            var principalDomainQualifiedId = this.extractPrincipalDomainQualifiedId(group);

            var uriFunction = function()
            {
                var uri = self.getUri() + "/group/acquire?id=" + principalDomainQualifiedId;
                if (createIfNotFound)
                {
                    uri += "&createIfNotFound=" + createIfNotFound;
                }

                return uri;
            };

            var chainable = this.getFactory().node(this, "n:group");
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Acquire a list of definitions.
         *
         * @chained node map
         *
         * @public
         *
         * @param [String] filter Optional filter of the kind of definition to fetch - "association", "type" or "feature"
         * @param [Object] pagination Optional pagination
         */
        listDefinitions: function(filter, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                // uri
                var uri = self.getUri() + "/definitions";
                if (filter)
                {
                    uri = uri + "?filter=" + filter;
                }

                return uri;
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainGet(chainable, uriFunction, params);
        },

        /**
         * Reads a definition by qname.
         *
         * @chained definition
         *
         * @public
         *
         * @param {String} qname the qname
         */
        readDefinition: function(qname)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/definitions/" + qname;
            };

            var chainable = this.getFactory().definition(this);
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Determines an available QName on this branch given some input.
         * This makes a call to the repository and asks it to provide a valid QName.
         *
         * The valid QName is passed as an argument to the next method in the chain.
         *
         * Note: This QName is a recommended QName that is valid at the time of the call.
         *
         * If another thread writes a node with the same QName after this call but ahead of this thread
         * attempting to commit, an invalid qname exception may still be thrown back.
         *
         * @chained this
         *
         * @public
         *
         * @param {Object} object an object with "title" or "description" fields to base generation upon
         */
        generateQName: function(object, callback)
        {
            var self = this;

            return this.then(function() {

                var chain = this;

                // call
                var uri = self.getUri() + "/qnames/generate";
                self.getDriver().gitanaPost(uri, null, object, function(response) {

                    var qname = response["_qname"];

                    callback.call(chain, qname);

                    chain.next();
                });

                // NOTE: we return false to tell the chain that we'll manually call next()
                return false;
            });
        },

        /**
         * Creates an association between the source node and the target node of the given type.
         *
         * @chained branch (this)
         *
         * @param sourceNode
         * @param targetNode
         * @param object (or string identifying type)
         */
        associate: function(sourceNode, targetNode, object)
        {
            // source
            var sourceNodeId = null;
            if (Gitana.isString(sourceNode))
            {
                sourceNodeId = sourceNode;
            }
            else
            {
                sourceNodeId = sourceNode.getId();
            }

            // target
            var targetNodeId = null;
            if (Gitana.isString(targetNode))
            {
                targetNodeId = targetNode;
            }
            else
            {
                targetNodeId = targetNode.getId();
            }

            // make sure we hand back the branch
            var result = this.subchain(this);

            // run a subchain to do the association
            result.subchain(this).then(function() {
                this.readNode(sourceNodeId).associate(targetNodeId, object);
            });

            return result;
        },

        /**
         * Traverses around the given node.
         *
         * Note: This is a helper function provided for convenience that delegates off to the node to do the work.
         *
         * @chained traversal results
         *
         * @param node or node id
         * @param config
         */
        traverse: function(node, config)
        {
            var nodeId = null;
            if (Gitana.isString(node))
            {
                nodeId = node;
            }
            else
            {
                nodeId = node.getId();
            }

            return this.readNode(nodeId).traverse(config);
        },

        //////////////////////////////////////////////////////////////////////////////////////////
        //
        // CONTAINER (a:child) CONVENIENCE FUNCTIONS
        //
        //////////////////////////////////////////////////////////////////////////////////////////

        /**
         * Creates a container node.
         *
         * This is a convenience function that simply applies the container feature to the object
         * ahead of calling createNode.
         *
         * @chained node
         *
         * @public
         *
         * @param [Object] object JSON object
         */
        createContainer: function(object)
        {
            if (!object)
            {
                object = {};
            }

            if (!object["_system"])
            {
                object["_system"] = {};
            }

            if (!object["_system"]["_features"])
            {
                object["_system"]["_features"] = {};
            }

            object["_system"]["_features"]["f:container"] = {
                "active": "true"
            };

            return this.createNode(object);
        },

        //////////////////////////////////////////////////////////////////////////////////////////
        //
        // FIND
        //
        //////////////////////////////////////////////////////////////////////////////////////////

        /**
         * Finds nodes within a branch
         *
         * @chained node map
         *
         * Config should be:
         *
         *    {
         *       "query": {
         *           ... Query Block
         *       },
         *       "search": {
         *           ... Elastic Search Config Block
         *       }
         *    }
         *
         * Alternatively, the value for "search" in the JSON block above can simply be text.
         *
         * @public
         *
         * @param {Object} config search configuration
         */
        find: function(config, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/find";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, config);
        },

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        // NODE LIST
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        /**
         * List the items in a node list.
         *
         * @chained node map
         *
         * @public
         *
         * @param {String} listKey
         * @param [Object] pagination
         */
        listItems: function(listKey, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/lists/" + listKey + "/items";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainGet(chainable, uriFunction, pagination);
        },

        /**
         * Queries for items in a node list.
         *
         * @chained node map
         *
         * @public
         *
         * @param {String} listKey
         * @param {Object} query
         * @param [Object] pagination
         */
        queryItems: function(listKey, query, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/lists/" + listKey + "/items/query";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, query);
        }

    });

})(window);
<commit_msg>Branch Type now retrieved with getBranchType() method (conflicted with getType())<commit_after>(function(window)
{
    var Gitana = window.Gitana;

    Gitana.Branch = Gitana.AbstractPlatformObject.extend(
    /** @lends Gitana.Branch.prototype */
    {
        /**
         * @constructs
         * @augments Gitana.AbstractPlatformObject
         *
         * @class Branch
         *
         * @param {Gitana.Repository} repository
         * @param [Object] object json object (if no callback required for populating)
         */
        constructor: function(repository, object)
        {
            this.base(repository.getPlatform(), object);

            this.objectType = "Gitana.Branch";

            //////////////////////////////////////////////////////////////////////////////////////////////
            //
            // PRIVILEGED METHODS
            //
            //////////////////////////////////////////////////////////////////////////////////////////////

            /**
             * Gets the Gitana Repository object.
             *
             * @inner
             *
             * @returns {Gitana.Repository} The Gitana Repository object
             */
            this.getRepository = function() { return repository; };

            /**
             * Gets the Gitana Repository id.
             *
             * @inner
             *
             * @returns {String} The Gitana Repository id
             */
            this.getRepositoryId = function() { return repository.getId(); };
        },

        /**
         * @OVERRIDE
         */
        getType: function()
        {
            return Gitana.TypedIDConstants.TYPE_BRANCH;
        },

        /**
         * @OVERRIDE
         */
        getUri: function()
        {
            return "/repositories/" + this.getRepositoryId() + "/branches/" + this.getId();
        },

        /**
         * @override
         */
        clone: function()
        {
            return this.getFactory().branch(this.getRepository(), this.object);
        },

        /**
         * @override
         */
        del: function()
        {
            // TODO - not implemented for branches
            return this;
        },

        /**
         * @returns {Boolean} whether this is the master branch
         */
        isMaster: function()
        {
            return (this.getBranchType().toLowerCase() == "master");
        },

        /**
         * @return {String} the type of branch ("master" or "custom")
         */
        getBranchType: function()
        {
            return this.get("type");
        },

        /**
         * @return {String} the tip changeset of the branch
         */
        getTip: function()
        {
            return this.get("tip");
        },

        /**
         * Acquires a list of mount nodes under the root of the repository.
         *
         * @chained node map
         *
         * @public
         *
         * @param [Object] pagination
         */
        listMounts: function(pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainGet(chainable, uriFunction, params);
        },

        /**
         * Reads a node.
         *
         * @chained node
         *
         * @public
         *
         * @param {String} nodeId the node id
         */
        readNode: function(nodeId)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/" + nodeId;
            };

            var chainable = this.getFactory().node(this);
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Reads the root node.
         *
         * @chained node
         *
         * @public
         */
        rootNode: function()
        {
            return this.readNode("root");
        },

        /**
         * Create a node
         *
         * @chained node
         *
         * @public
         *
         * @param [Object] object JSON object
         */
        createNode: function(object)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/nodes";
            };

            var chainable = this.getFactory().node(this);
            return this.chainCreate(chainable, object, uriFunction);
        },

        /**
         * Searches the branch.
         *
         * @chained node map
         *
         * Config should be:
         *
         *    {
         *       "search": {
         *           ... Elastic Search Config Block
         *       }
         *    }
         *
         * For a full text term search, you can simply provide text in place of a config json object.
         *
         * See the Elastic Search documentation for more advanced examples
         *
         * @public
         *
         * @param search
         * @param [Object] pagination
         */
        searchNodes: function(search, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            if (Gitana.isString(search))
            {
                search = {
                    "search": search
                };
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/search";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, search);
        },

        /**
         * Queries for nodes on the branch.
         *
         * Config should be:
         *
         *    {
         *       Gitana query configs
         *    }
         *
         * @chained node map
         *
         * @public
         *
         * @param {Object} query
         * @param [Object] pagination
         */
        queryNodes: function(query, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/query";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, query);
        },

        /**
         * Performs a bulk check of permissions against permissioned objects of type node.
         *
         * Example of checks array:
         *
         * [{
         *    "permissionedId": "<permissionedId>",
         *    "principalId": "<principalId>",
         *    "permissionId": "<permissionId>"
         * }]
         *
         * The callback receives an array of results, example:
         *
         * [{
         *    "permissionedId": "<permissionedId>",
         *    "principalId": "<principalId>",
         *    "permissionId": "<permissionId>",
         *    "result": true
         * }]
         *
         * The order of elements in the array will be the same for checks and results.
         *
         * @param checks
         * @param callback
         */
        checkNodePermissions: function(checks, callback)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/permissions/check";
            };

            var object = {
                "checks": checks
            };

            return this.chainPostResponse(this, uriFunction, {}, object).then(function() {
                callback.call(this, this.response["results"]);
            });
        },

        /**
         * Reads the person object for a security user.
         *
         * @chained node
         *
         * @param {Object} user either the user id, user name or the user object
         * @param [Boolean] createIfNotFound whether to create the person object if it isn't found
         */
        readPersonNode: function(user, createIfNotFound)
        {
            var self = this;

            var principalDomainQualifiedId = this.extractPrincipalDomainQualifiedId(user);

            var uriFunction = function()
            {
                var uri = self.getUri() + "/person/acquire?id=" + principalDomainQualifiedId;
                if (createIfNotFound)
                {
                    uri += "&createIfNotFound=" + createIfNotFound;
                }

                return uri;
            };

            var chainable = this.getFactory().node(this, "n:person");
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Reads the group object for a security group.
         *
         * @chained node
         *
         * @param {Object} group eitehr the group id, group name or the group object
         * @param [Boolean] createIfNotFound whether to create the group object if it isn't found
         */
        readGroupNode: function(group, createIfNotFound)
        {
            var self = this;

            var principalDomainQualifiedId = this.extractPrincipalDomainQualifiedId(group);

            var uriFunction = function()
            {
                var uri = self.getUri() + "/group/acquire?id=" + principalDomainQualifiedId;
                if (createIfNotFound)
                {
                    uri += "&createIfNotFound=" + createIfNotFound;
                }

                return uri;
            };

            var chainable = this.getFactory().node(this, "n:group");
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Acquire a list of definitions.
         *
         * @chained node map
         *
         * @public
         *
         * @param [String] filter Optional filter of the kind of definition to fetch - "association", "type" or "feature"
         * @param [Object] pagination Optional pagination
         */
        listDefinitions: function(filter, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                // uri
                var uri = self.getUri() + "/definitions";
                if (filter)
                {
                    uri = uri + "?filter=" + filter;
                }

                return uri;
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainGet(chainable, uriFunction, params);
        },

        /**
         * Reads a definition by qname.
         *
         * @chained definition
         *
         * @public
         *
         * @param {String} qname the qname
         */
        readDefinition: function(qname)
        {
            var self = this;

            var uriFunction = function()
            {
                return self.getUri() + "/definitions/" + qname;
            };

            var chainable = this.getFactory().definition(this);
            return this.chainGet(chainable, uriFunction);
        },

        /**
         * Determines an available QName on this branch given some input.
         * This makes a call to the repository and asks it to provide a valid QName.
         *
         * The valid QName is passed as an argument to the next method in the chain.
         *
         * Note: This QName is a recommended QName that is valid at the time of the call.
         *
         * If another thread writes a node with the same QName after this call but ahead of this thread
         * attempting to commit, an invalid qname exception may still be thrown back.
         *
         * @chained this
         *
         * @public
         *
         * @param {Object} object an object with "title" or "description" fields to base generation upon
         */
        generateQName: function(object, callback)
        {
            var self = this;

            return this.then(function() {

                var chain = this;

                // call
                var uri = self.getUri() + "/qnames/generate";
                self.getDriver().gitanaPost(uri, null, object, function(response) {

                    var qname = response["_qname"];

                    callback.call(chain, qname);

                    chain.next();
                });

                // NOTE: we return false to tell the chain that we'll manually call next()
                return false;
            });
        },

        /**
         * Creates an association between the source node and the target node of the given type.
         *
         * @chained branch (this)
         *
         * @param sourceNode
         * @param targetNode
         * @param object (or string identifying type)
         */
        associate: function(sourceNode, targetNode, object)
        {
            // source
            var sourceNodeId = null;
            if (Gitana.isString(sourceNode))
            {
                sourceNodeId = sourceNode;
            }
            else
            {
                sourceNodeId = sourceNode.getId();
            }

            // target
            var targetNodeId = null;
            if (Gitana.isString(targetNode))
            {
                targetNodeId = targetNode;
            }
            else
            {
                targetNodeId = targetNode.getId();
            }

            // make sure we hand back the branch
            var result = this.subchain(this);

            // run a subchain to do the association
            result.subchain(this).then(function() {
                this.readNode(sourceNodeId).associate(targetNodeId, object);
            });

            return result;
        },

        /**
         * Traverses around the given node.
         *
         * Note: This is a helper function provided for convenience that delegates off to the node to do the work.
         *
         * @chained traversal results
         *
         * @param node or node id
         * @param config
         */
        traverse: function(node, config)
        {
            var nodeId = null;
            if (Gitana.isString(node))
            {
                nodeId = node;
            }
            else
            {
                nodeId = node.getId();
            }

            return this.readNode(nodeId).traverse(config);
        },

        //////////////////////////////////////////////////////////////////////////////////////////
        //
        // CONTAINER (a:child) CONVENIENCE FUNCTIONS
        //
        //////////////////////////////////////////////////////////////////////////////////////////

        /**
         * Creates a container node.
         *
         * This is a convenience function that simply applies the container feature to the object
         * ahead of calling createNode.
         *
         * @chained node
         *
         * @public
         *
         * @param [Object] object JSON object
         */
        createContainer: function(object)
        {
            if (!object)
            {
                object = {};
            }

            if (!object["_system"])
            {
                object["_system"] = {};
            }

            if (!object["_system"]["_features"])
            {
                object["_system"]["_features"] = {};
            }

            object["_system"]["_features"]["f:container"] = {
                "active": "true"
            };

            return this.createNode(object);
        },

        //////////////////////////////////////////////////////////////////////////////////////////
        //
        // FIND
        //
        //////////////////////////////////////////////////////////////////////////////////////////

        /**
         * Finds nodes within a branch
         *
         * @chained node map
         *
         * Config should be:
         *
         *    {
         *       "query": {
         *           ... Query Block
         *       },
         *       "search": {
         *           ... Elastic Search Config Block
         *       }
         *    }
         *
         * Alternatively, the value for "search" in the JSON block above can simply be text.
         *
         * @public
         *
         * @param {Object} config search configuration
         */
        find: function(config, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/nodes/find";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, config);
        },

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //
        // NODE LIST
        //
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

        /**
         * List the items in a node list.
         *
         * @chained node map
         *
         * @public
         *
         * @param {String} listKey
         * @param [Object] pagination
         */
        listItems: function(listKey, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/lists/" + listKey + "/items";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainGet(chainable, uriFunction, pagination);
        },

        /**
         * Queries for items in a node list.
         *
         * @chained node map
         *
         * @public
         *
         * @param {String} listKey
         * @param {Object} query
         * @param [Object] pagination
         */
        queryItems: function(listKey, query, pagination)
        {
            var self = this;

            var params = {};
            if (pagination)
            {
                Gitana.copyInto(params, pagination);
            }

            var uriFunction = function()
            {
                return self.getUri() + "/lists/" + listKey + "/items/query";
            };

            var chainable = this.getFactory().nodeMap(this);
            return this.chainPost(chainable, uriFunction, params, query);
        }

    });

})(window);
<|endoftext|>


<commit_before>var express = require('express');
var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// configure a public directory to host static content
app.use(express.static(__dirname + '/public'));

require ("./test/app.js")(app);
require("./assignment/app.js")(app);

var port = process.env.PORT || 3000;
app.listen(port);<commit_msg>prevent Heroku from sleeping<commit_after>var express = require('express');
var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// configure a public directory to host static content
app.use(express.static(__dirname + '/public'));

require ("./test/app.js")(app);
require("./assignment/app.js")(app);

var port = process.env.PORT || 3000;
app.listen(port);

var http = require("http");
setInterval(function () {
    http.get("http://wang-xiao-webdev.herokuapp.com");
}, 300000);<|endoftext|>


<commit_before>var questao = document.getElementById('questao');
var button = document.getElementById('b1');
var parag = document.getElementsByClassName('parag');

var pergunta = ["Uma viagem entre duas cidades foi feita de carro em 4 dias, a uma velocidade média de 75 quilômetros por hora, viajando-se 9 horas por dia. Se aumentarmos a velocidade média em 20% e viajarmos 5 horas por dia, em quantos dias iríamos de uma cidade à outra? ","Osmar pediu R$ 500,00 a seu irmão Vilmar, para devolver só depois de um ano. Vilmar penalizou-se pela situação de seu irmão, mas sabia que Osmar não aceitaria o empréstimo se ele não cobrasse juros. Assim sendo, combinaram que Vilmar emprestaria o dinheiro a juros simples de forma que o acréscimo na quantia inicial não fosse menor que R$ 30,00, nem maior que R$ 60,00. Nessas condições, a variação possível para a taxa de juros mensal é: "," O produto das soluções da equação ( x + 3)2 + ( x − 3)2 − 116 = 0 é igual a: "];
var resposta = [["a) 2 dias ","b) 7 dias ","c) 6 dias ","d) 9 dias ","e) 3 dias "],["a) Maior ou igual a 0,5%. ","b) Menor ou igual a 12%. ","c) De 6% a 12%.","d) De 0,005% à 0,01%. ","e) De 0,5% a 1%. "],["a) 49","b) − 49 ","c) 0 ","d) − 7 ","e) 7 "]];
var gabarito = ["c) 6 dias ","e) De 0,5% a 1%. ","b) − 49 "];
/*
var aux = 0;
var ctd = 0;
var pontos = 0;
p = document.getElementById('parag').innerHTML = "PONTOS: "+pontos;
for (var i = 1; i <= 5; i++) {
    document.getElementById('questao').innerHTML = pergunta[aux];
    button = document.getElementById('b'+i);
    button.textContent = resposta[aux][i-1];
}
function clicou() {
    console.log(event.target.textContent);
    console.log(gabarito[ctd]);
    if (event.target.textContent == gabarito[ctd]) {
        pontos++;
        aux++;
        document.getElementById('parag').innerHTML = "PONTOS: "+pontos;
        if (aux == pergunta.length) {
            return fim();
        }
        for (var i = 1; i <= 5; i++) {
            var button = document.getElementById('b'+i);
            button.textContent = resposta[aux][i-1];
            document.getElementById('questao').innerHTML = pergunta[aux];
        }
        ctd++;
        console.log(aux);
        console.log(pergunta.length)
    }
    else{
        fim();
    }
}

function fim(){
    alert("FIM DE JOGO\n VOCE é BURROOO\nvoce fez "+pontos+" pontos");
}
*/<commit_msg>Update jogo.js<commit_after>var questao = document.getElementById('questao');
var button = document.getElementById('b1');
var parag = document.getElementsByClassName('parag');

var pergunta = [" Considere as afirmações abaixo: I. O cubo de 0,2 é 0,8.II. Um quadrado de área 0,36 cm2tem o perímetro igual a 2,4cm.III. O valor da expressão ,0125 3 5,0 3 + ⋅ é igual a 2.Então: "," Isadora tem um bambolê, brinquedo no formato de uma circunferência de 1,6 m de raio. Para Isadora, esse tamanho é inadequado: ela quer cortar o bambolê, para que ele fique com 75% do tamanho original. Nessas condições, quanto do comprimento inicial do bambolê deverá ser retirado?","Os alunos do 9 ano da escola “Perseverança” deveriam contribuir com quantias iguais a fim de arrecadar R$ 15.000,00 para as solenidades de formatura. Entretanto, dez deles deixaram de fazê-lo, ocasionando para cada um dos demais um acréscimo de R$ 50,00 nas respectivas contribuições. Contribuíram efetivamente: ",". De acordo com o paralelogramo ABCD,sendo E o ponto de intersecção das diagonais AC e BD, temos as seguintes medidas: AE = 4x, DE = 5x,BE  12 2y e CE  15 7y . Os valores de x e de y são,respectivamente:","Uma escada é feita pregando tábuas pequenas para os degraus e duas tábuas compridas para as laterais, como mostra a figura 2. Para pregar as tábuas, foram usados os pregos A, B, C, D, E, F, G e H. Sabendo que a distância entre os pregos B e D é de 25 cm, entre D e F é de 35 cm, entre F e H é de 20 cm, entre E e G é de 24 cm e que os dois degraus de cima são paralelos, determine a que distância, em cm, deve estar o prego G do prego A, para que os degraus fiquem paralelos entre si:",". Uma artesã dispõe de uma folha retangular de cartolina com dimensões 20 cm por 25 cm e precisa recortar retângulos com as dimensões 3 cm por 4 cm. O número máximo possível de retângulos com essas dimensões é",". Na primeira hora da tarde, uma pessoa conta um segredo para sua amiga. Na segunda hora da tarde, a amiga conta para mais três amigas.Cada uma dessas três amigas conta o segredo para outras três amigas diferentes, durante a terceira hora da tarde. E assim se sucede até o final da sétima hora da tarde. Quantas pessoas ficaram sabendo do segredo da pessoa inicial até o final da sétima hora da tarde?","Um parque tem 6 brinquedos individuais, mas somente 2/3 da sua capacidade total estão funcionando perfeitamente este mês (considerar o mês de 28 dias). Cada brinquedo individual funciona 5 horas por dia, durante 7 dias na semana, com 2 voltas por hora, e o ingresso é de R$ 3,25 por volta. As despesas com esses brinquedos são de R$ 1.745,00 por mês, contemplando salários dos funcionários, eletricidade, etc. Qual é o lucro exato do proprietário do parque com esses brinquedos neste mês?","Um retângulo que teve 40% de sua largura aumentada e 35% de seu comprimento reduzido apresenta, em relação à área do retângulo inicial,","Uma empresa A cobra R$ 80,00 por um determinado produto, mais uma taxa mensal de R$ 20,00 para manutenção. Uma empresa B cobra R$ 120,00 pelo mesmo produto, mais a taxa mensal de R$ 12,00 para manutenção. A empresa B será mais vantajosa que a A:"];

var resposta = [["a) Somente a afirmação II está correta.","b) Somente as afirmações I e II estão corretas.","c) Somente as afirmações I e III estão corretas.","d) Somente as afirmações II e III estão corretas.","e) Todas as afirmações estão corretas." ],["a) 2,4π m", "b) 1,2π m","c) 0,8 m","d) 1,2 m","e) 0,8π m "],["a) 60 pessoas","b) 55 pessoas","c) 50 pessoas","d) 10 pessoas","e) 65 pessoas "],["a) 8,5 e 10","b) 10 e 8,5","c)  1 e 2","d) 2 e1","e) 10,5 e 8"],["a) 80","b) 60","c) 96","d) 72","e) 84"],["(A) 36","(B) 40","(C) 41","(D) 42","(E) 45"],["(A) 234","(B) 729","(C) 730","(D) 1.093","(E) 2.187"],["(A) R$ 1.895,00","(B) R$ 2.085,00","(C) R$ 2.350,00","(D) R$ 3.640,00","(E) R$ 6.295,00"],["(A) aumento de 9%.","(B) redução de 5%.","(C) redução de 9%.","(D) aumento de 19%.","(E) igualdade de áreas."],["(A) a partir do 4° mês.","(B) a partir do 5° mês.","(C) a partir do 7° mês.","(D) a partir do 10° mês.","(E) sempre."]];

var gabarito = ["d) Somente as afirmações II e III estão corretas.","e) 0,8π m ","c) 50 pessoas","d) 2 e1","c) 96","(C) 41","(D) 1.093","(A) R$ 1.895,00","(C) redução de 9%.","(B) a partir do 5° mês."];

var aux = 0;
var ctd = 0;
var pontos = 0;
document.getElementById('parag').innerHTML = "PONTOS: "+pontos;
for (var i = 1; i <= 5; i++) {
    document.getElementById('questao').innerHTML = pergunta[aux];
    button = document.getElementById('b'+i);
    button.textContent = resposta[aux][i-1];
}
function clicou() {
    console.log(event.target.textContent);
    console.log(gabarito[ctd]);
    if (event.target.textContent == gabarito[ctd]) {
        pontos++;
        aux++;
        document.getElementById('parag').innerHTML = "PONTOS: "+pontos;
        if (aux == pergunta.length) {
            return fim();
        }
        for (var i = 1; i <= 5; i++) {
            var button = document.getElementById('b'+i);
            button.textContent = resposta[aux][i-1];
            document.getElementById('questao').innerHTML = pergunta[aux];
        }
        ctd++;
        console.log(aux);
        console.log(pergunta.length)
        }
        else{
            fim();
        }
}

function fim(){
    alert("FIM DE JOGO\n VOCE é BURROOO\nvoce fez "+pontos+" pontos");
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, View, TouchableHighlight, Text } from 'react-native';
import { Badge } from 'react-native-elements';
import Popover from 'react-native-popover-view';
import { SUSSOL_ORANGE } from '../globalStyles';

export class BadgeSet extends React.PureComponent {
  state = {
    isPopOverVisible: false,
    rect: {},
  };

  showPopover() {
    // Open popover and determine where to open it on canvas
    this.touchableContainer.measure((ox, oy, width, height, px, py) => {
      this.setState({
        isPopOverVisible: true,
        rect: { x: px, y: py, width, height },
      });
    });
  }

  closePopover() {
    this.setState({ isPopOverVisible: false });
  }

  renderInfo() {
    const { info } = this.props;

    // Create a list of text components' fragment with info array row data
    return info.map((item, key) => {
      if (item.count <= 0 || item.text === '') return null;

      return (
        <Text style={{ color: '#FFF', fontSize: 12 }}>
          {key === 0 ? '' : '\n'}
          {item.title} : {item.count || item.text}
        </Text>
      );
    });
  }

  render() {
    const { children, info, mainWrapperStyle, popoverPosition } = this.props;
    const { isPopOverVisible, rect } = this.state;

    // Get total of all the count variables in the info array. We want to show it on the badge
    const pendingCount = info.reduce((total, item) => total + (item.count || 0), 0);

    // Since having multiple digit text can break the badge, we are showing 99+
    // if the number is greater then 99.
    const unfinalisedCountText = pendingCount > 99 ? '99+' : pendingCount;

    return (
      <View style={{ position: 'relative' }}>
        {children}
        {pendingCount !== 0 && (
          <View style={[localStyles.mainWrapperStyle, mainWrapperStyle]}>
            <TouchableHighlight
              ref={ref => {
                this.touchableContainer = ref;
              }}
              style={localStyles.touchableContainerStyle}
              onPress={() => this.showPopover()}
            >
              <Badge
                value={unfinalisedCountText}
                badgeStyle={localStyles.badgeStyle}
                textStyle={localStyles.badgeFontStyle}
              />
            </TouchableHighlight>
            <Popover
              isVisible={isPopOverVisible}
              fromRect={rect}
              onRequestClose={() => this.closePopover()}
              popoverStyle={{ padding: 10, backgroundColor: SUSSOL_ORANGE }}
              arrowStyle={{ backgroundColor: SUSSOL_ORANGE }}
              backgroundStyle={{ backgroundColor: 'transparent' }}
              placement={popoverPosition}
            >
              <Text>{this.renderInfo()}</Text>
            </Popover>
          </View>
        )}
      </View>
    );
  }
}

export default BadgeSet;

BadgeSet.propTypes = {
  children: PropTypes.element.isRequired,
  info: PropTypes.shape.isRequired,
  mainWrapperStyle: PropTypes.element,
  popoverPosition: PropTypes.string,
};

BadgeSet.defaultProps = {
  mainWrapperStyle: {},
  popoverPosition: 'auto',
};

const localStyles = StyleSheet.create({
  mainWrapperStyle: {
    position: 'absolute',
    top: 0,
    right: 8,
  },
  touchableContainerStyle: {
    borderRadius: 10,
    backgroundColor: '#FFF',
    borderColor: '#FFF',
  },
  badgeStyle: {
    width: 45,
    backgroundColor: SUSSOL_ORANGE,
    alignItems: 'center',
    justifyContent: 'center',
  },
  badgeFontStyle: {
    fontSize: 10,
    color: '#FFF',
  },
});
<commit_msg>Replace badge component from react-native-elements to single badge<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, View, TouchableHighlight, Text } from 'react-native';
import Popover from 'react-native-popover-view';
import Badge from './Badge';
import { SUSSOL_ORANGE } from '../globalStyles';

export class BadgeSet extends React.PureComponent {
  state = {
    isPopOverVisible: false,
    rect: {},
  };

  showPopover() {
    // Open popover and determine where to open it on canvas
    this.touchableContainer.measure((ox, oy, width, height, px, py) => {
      this.setState({
        isPopOverVisible: true,
        rect: { x: px, y: py, width, height },
      });
    });
  }

  closePopover() {
    this.setState({ isPopOverVisible: false });
  }

  renderInfo() {
    const { info } = this.props;

    // Create a list of text components' fragment with info array row data
    return info.map((item, key) => {
      if (item.count <= 0 || item.text === '') return null;

      return (
        <Text style={{ color: '#FFF', fontSize: 12 }}>
          {key === 0 ? '' : '\n'}
          {item.title} : {item.count || item.text}
        </Text>
      );
    });
  }

  render() {
    const { children, info, mainWrapperStyle, popoverPosition } = this.props;
    const { isPopOverVisible, rect } = this.state;

    // Get total of all the count variables in the info array. We want to show it on the badge
    const pendingCount = info.reduce((total, item) => total + (item.count || 0), 0);

    // Since having multiple digit text can break the badge, we are showing 99+
    // if the number is greater then 99.
    const unfinalisedCountText = pendingCount > 99 ? '99+' : pendingCount;

    return (
      <View style={{ position: 'relative' }}>
        {children}
        {pendingCount !== 0 && (
          <View style={[localStyles.mainWrapperStyle, mainWrapperStyle]}>
            <TouchableHighlight
              ref={ref => {
                this.touchableContainer = ref;
              }}
              style={localStyles.touchableContainerStyle}
              onPress={() => this.showPopover()}
            >
              <Badge
                value={unfinalisedCountText}
                badgeStyle={localStyles.badgeStyle}
                textStyle={localStyles.badgeFontStyle}
              />
            </TouchableHighlight>
            <Popover
              isVisible={isPopOverVisible}
              fromRect={rect}
              onRequestClose={() => this.closePopover()}
              popoverStyle={{ padding: 10, backgroundColor: SUSSOL_ORANGE }}
              arrowStyle={{ backgroundColor: SUSSOL_ORANGE }}
              backgroundStyle={{ backgroundColor: 'transparent' }}
              placement={popoverPosition}
            >
              <Text>{this.renderInfo()}</Text>
            </Popover>
          </View>
        )}
      </View>
    );
  }
}

export default BadgeSet;

BadgeSet.propTypes = {
  children: PropTypes.element.isRequired,
  info: PropTypes.shape.isRequired,
  mainWrapperStyle: PropTypes.element,
  popoverPosition: PropTypes.string,
};

BadgeSet.defaultProps = {
  mainWrapperStyle: {},
  popoverPosition: 'auto',
};

const localStyles = StyleSheet.create({
  mainWrapperStyle: {
    position: 'absolute',
    top: 0,
    right: 8,
  },
  touchableContainerStyle: {
    borderRadius: 10,
    backgroundColor: '#FFF',
    borderColor: '#FFF',
  },
  badgeStyle: {
    width: 45,
    backgroundColor: SUSSOL_ORANGE,
    alignItems: 'center',
    justifyContent: 'center',
  },
  badgeFontStyle: {
    fontSize: 10,
    color: '#FFF',
  },
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('app')
        .controller('HomeCtrl', HomeCtrl);

        HomeCtrl.$inject = ['$scope', '$location', '$route', '$http', 'userService', 'imageService'];

        function HomeCtrl($scope, $location, $route, $http, userService, imageService) {
            let vm = this;

            vm.isAuthenticated = userService.isAuthenticated();

            vm.haveInfo = false;
            vm.noMoreInfo = false;
            vm.totalDisplay = 6;

            vm.loadMore = function () {
                if (vm.allImages.length < vm.totalDisplay + 6)
                    vm.noMoreInfo = true;
                vm.totalDisplay += 6;
                console.log(vm.totalDisplay);
            };

            if (vm.isAuthenticated){
                imageService.getAllImages().then(function (response){
                    vm.allImages = response;
                    vm.allImages.reverse();
                    vm.haveInfo = true;
                    vm.noMoreInfo = vm.allImages.length > vm.totalDisplay ? false : true;
                }, function (error){
                    console.log(error.data);
                })
            }

        }
})();<commit_msg>actually sort the images by latest id<commit_after>(function() {
    'use strict';

    angular
        .module('app')
        .controller('HomeCtrl', HomeCtrl);

        HomeCtrl.$inject = ['$scope', '$location', '$route', '$http', 'userService', 'imageService'];

        function HomeCtrl($scope, $location, $route, $http, userService, imageService) {
            let vm = this;

            vm.isAuthenticated = userService.isAuthenticated();

            vm.haveInfo = false;
            vm.noMoreInfo = false;
            vm.totalDisplay = 6;

            vm.loadMore = function () {
                if (vm.allImages.length < vm.totalDisplay + 6)
                    vm.noMoreInfo = true;
                vm.totalDisplay += 6;
                console.log(vm.totalDisplay);
            };

            if (vm.isAuthenticated){
                imageService.getAllImages().then(function (response){
                    vm.allImages = response;
                    vm.allImages.sort(function(a, b) {
                        return b.id - a.id;
                    });
                    vm.haveInfo = true;
                    vm.noMoreInfo = vm.allImages.length > vm.totalDisplay ? false : true;
                }, function (error){
                    console.log(error.data);
                })
            }

        }
})();<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/asciimo'] = function(req, res) {
            var link = "http://i.imgur.com/kmbjB.png";
            res.send("");
        };

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express.createServer();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>rm server.js<commit_after><|endoftext|>


<commit_before>
myApp.controller("MainCtrl", ['$scope', '$timeout', function($scope, $timeout){
  console.log("controller");

  $scope.watchID = null;
  $scope.innerWidth = window.innerWidth;
  $scope.innerHeight = window.innerHeight - 40;
  $scope.posX = (innerWidth - 50) / 2;
  $scope.posY = (innerHeight - 50) / 2;

  $scope.circle = {
    x : $scope.posX,
    y : $scope.posY,
    r : 40
  };

  $scope.startWatch = function() {
    console.log("startWatch");
    var options;
    options = { frequency: 100 };
    $scope.watchID = navigator.accelerometer.watchAcceleration($scope.onSuccess, $scope.onError, options);
  };

  $scope.stopWatch = function() {
    console.log("stopWatch");
    if ($scope.watchID) {
      navigator.accelerometer.clearWatch($scope.watchID);
      $scope.watchID = null;
    }
  };

  $scope.onSuccess = function(acceleration) {
  /*alert('Acceleration X: ' + acceleration.x + '\n' +
        'Acceleration Y: ' + acceleration.y + '\n' +
        'Acceleration Z: ' + acceleration.z + '\n' +
        'Timestamp: '      + acceleration.timestamp + '\n');*/
  /*var element = document.getElementById('accelerometer');
    element.innerHTML = 'Acceleration X: ' + acceleration.x + '
' +
                      'Acceleration Y: ' + acceleration.y + '
' +
                      'Acceleration Z: ' + acceleration.z + '
' +
                      'windowWidth: ' + window.innerWidth + '
' +
                      'windowHeight: ' + window.innerHeight + '
' +
                      'Timestamp: '      + acceleration.timestamp + '
';*/

    $scope.posX += -1 * (acceleration.x * 1.5);
    $scope.posY += (acceleration.y * 1.5);

    $timeout(function() {
      $scope.circle.x = $scope.posX;
      $scope.circle.y = $scope.posY;
    }, 0);
  }

  $scope.onError = function () {
    alert('onError!');
  }

}]);
<commit_msg>원이 화면에서 사라지지 않도록 수정<commit_after>
myApp.controller("MainCtrl", ['$scope', '$timeout', function($scope, $timeout){
  console.log("controller");

  $scope.watchID = null;
  $scope.innerWidth = window.innerWidth;
  $scope.innerHeight = window.innerHeight - 40;
  $scope.circle = {
    x : $scope.posX,
    y : $scope.posY,
    r : 40
  };
  $scope.posX = ($scope.innerWidth - $scope.circle.r) / 2;
  $scope.posY = ($scope.innerHeight - $scope.circle.r) / 2;

  $scope.startWatch = function() {
    console.log("startWatch");
    var options;
    options = { frequency: 100 };
    $scope.watchID = navigator.accelerometer.watchAcceleration($scope.onSuccess, $scope.onError, options);
  };

  $scope.stopWatch = function() {
    console.log("stopWatch");
    if ($scope.watchID) {
      navigator.accelerometer.clearWatch($scope.watchID);
      $scope.watchID = null;
    }
  };

  $scope.onSuccess = function(acceleration) {
  /*alert('Acceleration X: ' + acceleration.x + '\n' +
        'Acceleration Y: ' + acceleration.y + '\n' +
        'Acceleration Z: ' + acceleration.z + '\n' +
        'Timestamp: '      + acceleration.timestamp + '\n');*/
  /*var element = document.getElementById('accelerometer');
    element.innerHTML = 'Acceleration X: ' + acceleration.x + '
' +
                      'Acceleration Y: ' + acceleration.y + '
' +
                      'Acceleration Z: ' + acceleration.z + '
' +
                      'windowWidth: ' + window.innerWidth + '
' +
                      'windowHeight: ' + window.innerHeight + '
' +
                      'Timestamp: '      + acceleration.timestamp + '
';*/

    $scope.posX += -1 * (acceleration.x * 1.5);
    $scope.posY += (acceleration.y * 1.5);

    if($scope.posX < $scope.circle.r) {
      $scope.posX = $scope.circle.r;
    } else if($scope.posX > ($scope.innerWidth - $scope.circle.r)) {
      $scope.posX = ($scope.innerWidth - $scope.circle.r);
    }

    if($scope.posY < $scope.circle.r) {
      $scope.posY = $scope.circle.r;
    } else if($scope.posY > ($scope.innerHeight - $scope.circle.r)) {
      $scope.posY = ($scope.innerHeight - $scope.circle.r);
    }

    $timeout(function() {
      $scope.circle.x = $scope.posX;
      $scope.circle.y = $scope.posY;
    }, 0);
  }

  $scope.onError = function () {
    alert('onError!');
  }

}]);
<|endoftext|>