<commit_before>define(['jquery', './base/gumhelper', './base/videoShooter'],
  function($, gumHelper, VideoShooter) {
  'use strict';

  var html = $('html');
  var body = $('body');
  var addChat = $('#add-chat-form');
  var chatList = $('.chats ul');
  var footer = $('#footer');
  var posting = false;
  var videoShooter;
  var socket = io.connect(location.protocol + '//' + location.hostname +
    (location.port ? ':' + location.port : ''));

  var CHAT_LIMIT = 35;

  var escapeHtml = function (text) {
    text = text
      .replace(/&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>');

    var txtArray = text.split(/\s/);
    var newTxt = [];

    for (var i = 0; i < txtArray.length; i ++) {
      if (txtArray[i].match(/^(http|www)+/) && txtArray[i].indexOf('gravatar') === -1) {
        newTxt.push('' + txtArray[i] + '');
      } else {
        newTxt.push(txtArray[i]);
      }
    }

    return newTxt.join(' ');
  };

  var renderChat = function (c) {
    if (body.find('li[data-key="' + c.chat.key + '"]').length === 0) {
      var li = $('

' +
        escapeHtml(c.chat.value.message) + '

');
      chatList.append(li);
      var scrollHeight = body[0].scrollHeight;
      body[0].scrollTop = scrollHeight;
      html[0].scrollTop = scrollHeight;

      if (body.find('.chats.list > ul > li').length > CHAT_LIMIT) {
        body.find('.chats.list > ul > li')[0].remove();
      }
    }
  };

  socket.on('connect', function () {
    socket.on('message', function (data) {
      renderChat(data);
    });
  });

  $.get('/get/chats', function (data) {
    for (var i = 0; i < data.chats.chats.length; i ++) {
      var chat = {
        chat: data.chats.chats[i]
      };
      renderChat(chat);
    }
  });

  var getScreenshot = function (callback, numFrames, interval) {
    if (videoShooter) {
      videoShooter.getShot(callback, numFrames, interval);
    } else {
      callback('');
    }
  };

  if (navigator.getMedia) {
    gumHelper.startVideoStreaming(function errorCb() {
    }, function successCallback(stream, videoElement, width, height) {
      videoElement.width = width / 5;
      videoElement.height = height / 5;
      footer.append(videoElement);
      videoElement.play();
      videoShooter = new VideoShooter(videoElement);
      addChat.click();
    });
  } else {
    addChat.click();
  }

  addChat.on('submit', function (ev) {
    ev.preventDefault();

    var self = $(ev.target);
    var blocker = self.find('#add-chat-blocker');
    var addChat = self.find('#add-chat');

    if (!posting) {
      blocker.removeClass('hidden');
      posting = true;

      getScreenshot(function (pictureData) {
        var picField = self.find('#picture').val(pictureData);

        $.post('/add/chat', self.serialize(), function () {
          picField.val('');
          addChat.val('');
          blocker.addClass('hidden');
          posting = false;
        });
      }, 10, 0.2);
    }
  });
});
<commit_msg>add in support for @twitter linking of names and fixed up the www regex so it added the http prefix<commit_after>define(['jquery', './base/gumhelper', './base/videoShooter'],
  function($, gumHelper, VideoShooter) {
  'use strict';

  var html = $('html');
  var body = $('body');
  var addChat = $('#add-chat-form');
  var chatList = $('.chats ul');
  var footer = $('#footer');
  var posting = false;
  var videoShooter;
  var socket = io.connect(location.protocol + '//' + location.hostname +
    (location.port ? ':' + location.port : ''));

  var CHAT_LIMIT = 35;

  var escapeHtml = function (text) {
    text = text
      .replace(/&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>');

    var txtArray = text.split(/\s/);
    var newTxt = [];

    for (var i = 0; i < txtArray.length; i ++) {
      if (txtArray[i].indexOf('gravatar') === -1) {
        if (txtArray[i].match(/^(http)+/)) {
          newTxt.push('' + txtArray[i] + '');
        } else if (txtArray[i].match(/^(www)+/)) {
          newTxt.push('' + txtArray[i] + '');
        } else if (txtArray[i].match(/(^|[^@\w])@(\w{1,15})\b/)) {
          newTxt.push('' + txtArray[i] + '');
        } else {
          newTxt.push(txtArray[i]);
        }
      } else {
        newTxt.push(txtArray[i]);
      }
    }

    return newTxt.join(' ');
  };

  var renderChat = function (c) {
    if (body.find('li[data-key="' + c.chat.key + '"]').length === 0) {
      var li = $('

' +
        escapeHtml(c.chat.value.message) + '

');
      chatList.append(li);
      var scrollHeight = body[0].scrollHeight;
      body[0].scrollTop = scrollHeight;
      html[0].scrollTop = scrollHeight;

      if (body.find('.chats.list > ul > li').length > CHAT_LIMIT) {
        body.find('.chats.list > ul > li')[0].remove();
      }
    }
  };

  socket.on('connect', function () {
    socket.on('message', function (data) {
      renderChat(data);
    });
  });

  $.get('/get/chats', function (data) {
    for (var i = 0; i < data.chats.chats.length; i ++) {
      var chat = {
        chat: data.chats.chats[i]
      };
      renderChat(chat);
    }
  });

  var getScreenshot = function (callback, numFrames, interval) {
    if (videoShooter) {
      videoShooter.getShot(callback, numFrames, interval);
    } else {
      callback('');
    }
  };

  if (navigator.getMedia) {
    gumHelper.startVideoStreaming(function errorCb() {
    }, function successCallback(stream, videoElement, width, height) {
      videoElement.width = width / 5;
      videoElement.height = height / 5;
      footer.append(videoElement);
      videoElement.play();
      videoShooter = new VideoShooter(videoElement);
      addChat.click();
    });
  } else {
    addChat.click();
  }

  addChat.on('submit', function (ev) {
    ev.preventDefault();

    var self = $(ev.target);
    var blocker = self.find('#add-chat-blocker');
    var addChat = self.find('#add-chat');

    if (!posting) {
      blocker.removeClass('hidden');
      posting = true;

      getScreenshot(function (pictureData) {
        var picField = self.find('#picture').val(pictureData);

        $.post('/add/chat', self.serialize(), function () {
          picField.val('');
          addChat.val('');
          blocker.addClass('hidden');
          posting = false;
        });
      }, 10, 0.2);
    }
  });
});
<|endoftext|>


<commit_before>/**
 * Created by brennon on 8/6/14.
 */

'use strict';

var request = require('supertest');
var config = require('../../../config/config');
var should = require('chai').should();

/* jshint ignore:start */
var sinon = require('sinon');
/* jshint ignore:end */

describe('Core Controller Tests', function() {

  describe('sessions', function() {

    var agent = request.agent('localhost:' + config.port);
    var cookieA, cookieB;

    it('should be in use', function(done) {
      agent.get('/').expect('set-cookie', /connect\.sid.*/).end(function(err, res) {
        if (err) return done(err);
        cookieA = res.header['set-cookie'];
        done();
      });
    });

    it('should be reset on any visit to the index', function(done) {
      agent.get('/').expect('set-cookie', /connect\.sid.*/).end(function(err, res) {
        if (err) return done(err);
        cookieB = res.header['set-cookie'];
        cookieA.should.not.equal(cookieB);
        done();
      });
    });
  });
});
<commit_msg>Reformat core.server.controller.test.js<commit_after>/**
 * Created by Brennon Bortz on 8/6/14.
 */

'use strict';

// Config module
var config = require('../../../config/config');

// Testing tools
var request = require('supertest');
var should = require('chai').should();
var sinon = require('sinon');

describe('Core Controller Tests', function() {

  describe('sessions', function() {

    var agent = request.agent('localhost:' + config.port);
    var cookieA, cookieB;

    it('should be in use', function(done) {
      agent.get('/').expect('set-cookie', /connect\.sid.*/).end(function(err, res) {
        if (err) {
            return done(err);
        }
        cookieA = res.header['set-cookie'];
        done();
      });
    });

    it('should be reset on any visit to the index', function(done) {
      agent.get('/').expect('set-cookie', /connect\.sid.*/).end(function(err, res) {
        if (err) {
            return done(err);
        }
        cookieB = res.header['set-cookie'];
        cookieA.should.not.equal(cookieB);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var app = angular.module('myApp.shuffler', ['ngRoute']);

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/shuffler', {
        templateUrl: 'shuffler/shuffler.html',
        controller: 'ShufflerCtrl'
    });
}]);

app.factory('cardSrvc', [function () {
    var createSuit = function (suit) {
        return [
            {
                face: 'A',
                suit: suit,
                order: '1'
            },
            {
                face: '2',
                suit: suit,
                order: '2'
            },
            {
                face: '3',
                suit: suit,
                order: '3'
            },
            {
                face: '4',
                suit: suit,
                order: '4'
            },
            {
                face: '5',
                suit: suit,
                order: '5'
            },
            {
                face: '6',
                suit: suit,
                order: '6'
            },
            {
                face: '7',
                suit: suit,
                order: '7'
            },
            {
                face: '8',
                suit: suit,
                order: '8'
            },
            {
                face: '9',
                suit: suit,
                order: '9'
            },
            {
                face: '10',
                suit: suit,
                order: 'a'
            },
            {
                face: 'J',
                suit: suit,
                order: 'b'
            },
            {
                face: 'Q',
                suit: suit,
                order: 'd'
            },
            {
                face: 'K',
                suit: suit,
                order: 'e'
            }
        ];
    };

    var suits = ['spades', 'hearts', 'clubs', 'diamonds'];

    var createDeck = function () {
        var deck = [];

        angular.forEach(suits, function (suit, i) {
            deck = deck.concat(createSuit(suit));
        });

        return deck;
    };

    var shuffle = function (deck) {
        return _.shuffle(deck);
    };

    var sort = function () {

    };

    return {
        createSuit: createSuit,
        createDeck: createDeck,
        shuffle: shuffle,
        sort: sort
    };
}]);

app.directive('shufflerSuit', [function () {
    return {
        restrict: 'E',
        scope: {
            suit: '@'
        },
        replace: true,
        template: '
{{face}}
',
        link: function (scope, element, attrs) {
            var suits = {
                'clubs': {
                    char: '\u2663',// '♣',
                    color: 'red'
                },
                'spades': {
                    char: '\u2660',
                    color: 'black'
                },
                'hearts': {
                    char: '\u2665',
                    color: 'red'
                },
                'diamonds': {
                    char: '\u2666',
                    color: 'red'
                }
            };

            scope.face = suits[attrs.suit].char;
            scope.color = suits[attrs.suit].color;
        }
    };
}]);

app.controller('ShufflerCtrl', ['$scope', 'cardSrvc', function($scope, cardSrvc) {
    $scope.deck = cardSrvc.createDeck();

    // $scope.shuffle = cardSrvc.shuffle();
    // $scope.sort = cardSrvc.sort();
}]);
<commit_msg>added ngLodash dependency<commit_after>'use strict';

var app = angular.module('myApp.shuffler', ['ngRoute', 'ngLodash']);

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/shuffler', {
        templateUrl: 'shuffler/shuffler.html',
        controller: 'ShufflerCtrl'
    });
}]);

app.factory('cardSrvc', ['lodash', function (lodash) {
    var createSuit = function (suit) {
        return [
            {
                face: 'A',
                suit: suit,
                order: '1'
            },
            {
                face: '2',
                suit: suit,
                order: '2'
            },
            {
                face: '3',
                suit: suit,
                order: '3'
            },
            {
                face: '4',
                suit: suit,
                order: '4'
            },
            {
                face: '5',
                suit: suit,
                order: '5'
            },
            {
                face: '6',
                suit: suit,
                order: '6'
            },
            {
                face: '7',
                suit: suit,
                order: '7'
            },
            {
                face: '8',
                suit: suit,
                order: '8'
            },
            {
                face: '9',
                suit: suit,
                order: '9'
            },
            {
                face: '10',
                suit: suit,
                order: 'a'
            },
            {
                face: 'J',
                suit: suit,
                order: 'b'
            },
            {
                face: 'Q',
                suit: suit,
                order: 'd'
            },
            {
                face: 'K',
                suit: suit,
                order: 'e'
            }
        ];
    };

    var suits = ['spades', 'hearts', 'clubs', 'diamonds'];

    var createDeck = function () {
        var deck = [];

        angular.forEach(suits, function (suit, i) {
            deck = deck.concat(createSuit(suit));
        });

        return deck;
    };

    var shuffle = function (deck) {
        return lodash.shuffle(deck);
    };

    var sort = function () {

    };

    return {
        createSuit: createSuit,
        createDeck: createDeck,
        shuffle: shuffle,
        sort: sort
    };
}]);

app.directive('shufflerSuit', [function () {
    return {
        restrict: 'E',
        scope: {
            suit: '@'
        },
        replace: true,
        template: '
{{face}}
',
        link: function (scope, element, attrs) {
            var suits = {
                'clubs': {
                    char: '\u2663',// '♣',
                    color: 'red'
                },
                'spades': {
                    char: '\u2660',
                    color: 'black'
                },
                'hearts': {
                    char: '\u2665',
                    color: 'red'
                },
                'diamonds': {
                    char: '\u2666',
                    color: 'red'
                }
            };

            scope.face = suits[attrs.suit].char;
            scope.color = suits[attrs.suit].color;
        }
    };
}]);

app.controller('ShufflerCtrl', ['$scope', 'cardSrvc', function($scope, cardSrvc) {
    $scope.deck = cardSrvc.createDeck();
    // $scope.shuffle = cardSrvc.shuffle();
    // $scope.sort = cardSrvc.sort();
}]);
<|endoftext|>


<commit_before>//= require_tree  ./lib/
//= require_tree  ./components/
//= require_tree  ./pages/
//= require_directory ./
<commit_msg>Fix Sprockets::CircularDependencyError looks like gems/active_admin-1bff73d87a26/app/assets/javascripts/active_admin/application.js has already been required<commit_after>//= require_tree  ./lib/
//= require_tree  ./components/
//= require_tree  ./pages/
<|endoftext|>


<commit_before>//using axios as an api utility
import axios from 'axios';
// import apiKey from './apiKey';
//setting API key to variables
var _APIURL = "http://api.openweathermap.org/data/2.5/";
var _APIKEY = //PLACE API KEY HERE;

//This utility will provide access to the open weather API.
// From openweather documents: 'To make the result more accurate just put the city name and country divided by comma.'
// Example
// http://api.openweathermap.org/data/2.5/weather?q=tarrytown&type=accurate&unit=celcius&appid=b714ec74bbab5650795063cb0fdf5fbe
//Unit is metric because... when I go to Norway I need to use metric! (celcius is used in global aviation also. Yes even the US)
//function to provide endpoint parameters
var getQueryStringData = function(city){
	return {
		q : city,
		type: 'accurate',
    units: 'metric',
		APPID: _APIKEY,
	}
};

// prepRouteParams is invoked in makeWeatherURL function
// Object.keys returns an array
// .map goes through Object.keys array and applies a callback to each key
// return a string of the key and value
// .join will join each string returned from every iteration of .map
var prepRouteParams = function(queryStringData){
	return Object.keys(queryStringData)
		.map(function(key){
			return key + '=' + encodeURIComponent(queryStringData[key]);
		}).join('&')
};

//concats different string components to create a URL
var makeWeatherURL = function(type, queryStringData){
	return _APIURL + type + '?' + prepRouteParams(queryStringData);
};

//Run API get request with axios
var getCurrentWeather = function(city){
	var queriedString = getQueryStringData(city); //JS object from above
	var url = makeWeatherURL("weather", queriedString);
	//axios performs get request to endpoint
	return axios.get(url)
		//Promise to provide success or fail results
		//success provides data as a JSON object
		.then(function(data){
				//Send data back to where it was called
				return data
			})
		//.catch provides error description
		.catch(function(error){
			console.warn("Error with weatherApi" + error)
			return error
		})
};

//export json data as getCurrentWeather
module.exports = {
	getCurrentWeather: getCurrentWeather
};
<commit_msg>d3 implementation<commit_after>//using axios as an api utility
import axios from 'axios';
import apiKey from './apiKey';
//setting API key to variables
var _APIURL = "http://api.openweathermap.org/data/2.5/";
var _APIKEY = apiKey;

//This utility will provide access to the open weather API.
// From openweather documents: 'To make the result more accurate just put the city name and country divided by comma.'
// Example
// http://api.openweathermap.org/data/2.5/weather?q=tarrytown&type=accurate&unit=celcius&appid=b714ec74bbab5650795063cb0fdf5fbe
//Unit is metric because... when I go to Norway I need to use metric! (celcius is used in global aviation also. Yes even the US)
//function to provide endpoint parameters
var getQueryStringData = function(city){
	return {
		q : city,
		type: 'accurate',
    units: 'metric',
		APPID: _APIKEY,
	}
};

// prepRouteParams is invoked in makeWeatherURL function
// Object.keys returns an array
// .map goes through Object.keys array and applies a callback to each key
// return a string of the key and value
// .join will join each string returned from every iteration of .map
var prepRouteParams = function(queryStringData){
	return Object.keys(queryStringData)
		.map(function(key){
			return key + '=' + encodeURIComponent(queryStringData[key]);
		}).join('&')
};

//concats different string components to create a URL
var makeWeatherURL = function(type, queryStringData){
	return _APIURL + type + '?' + prepRouteParams(queryStringData);
};

//Run API get request with axios
var getCurrentWeather = function(city){
	var queriedString = getQueryStringData(city); //JS object from above
	var url = makeWeatherURL("weather", queriedString);
	//axios performs get request to endpoint
	return axios.get(url)
		//Promise to provide success or fail results
		//success provides data as a JSON object
		.then(function(data){
				//Send data back to where it was called
				return data
			})
		//.catch provides error description
		.catch(function(error){
			console.warn("Error with weatherApi" + error)
			return error
		})
};

//export json data as getCurrentWeather
module.exports = {
	getCurrentWeather: getCurrentWeather
};
<|endoftext|>


<commit_before>module.exports.prompt = { // use nested prompt
  "development": [{
    name: "PUBLIC_URL",
    message: "Public URL (*.local)".magenta,
    required: true
  }],
  "production": [{
    name: "PUBLIC_URL",
    message: "Public URL (*.local)".magenta,
    required: true
  }]
}

module.exports.map = {
  //HOSTNAME: ["HOSTNAME", "HTTP_HOST"],
  PUBLIC_URL: "PUBLIC_URL"
}

module.exports.path = "images/php/php"

module.exports.defaults = {
  dev: {
    TZ: "Europe/Rome",          // Defaults
    DOCKER: "1",                // Defaults
    ENV: "local",               // Defaults
    WP_POST_REVISIONS: "false", // Defaults
    WP_USE_THEMES: "false",     // Defaults
    WP_LANG: "it_IT",           // Defaults
    WORKDIR: "/www",

    DB_HOST: "mysql",
    DB_NAME: "",          // Match with MySQL
    DB_USER: "",          // Match with MySQL
    DB_PASS: "",          // Match with MySQL

    PROJECT_NAME: "",     // Match with main
    APP_ID: "",           // Match with main
    PORT: "",             // Match with main
  },
  prod: {
    TZ: "Europe/Rome",          // Defaults
    DOCKER: "1",                // Defaults
    ENV: "local",               // Defaults
    WP_POST_REVISIONS: "false", // Defaults
    WP_USE_THEMES: "false",     // Defaults
    WP_LANG: "it_IT",           // Defaults
    WORKDIR: "/www",

    DB_HOST: "mysql",
    DB_NAME: "",          // Match with MySQL
    DB_USER: "",          // Match with MySQL
    DB_PASS: "",          // Match with MySQL

    PROJECT_NAME: "",     // Match with main
    APP_ID: "",           // Match with main
    PORT: "80",           // Match with main

    /*HTTP_HOST: "localhost",
    HOSTNAME: "localhost",
    PUBLIC_URL: "http://aeriawork.vanadio.dev"*/
  }
}

module.exports.dependencies = [
  { PROJECT_NAME: {main: "PROJECT_NAME"} },
  { APP_ID:       {main: "PROJECT_NAME"} },
  { PORT:         {main: "PROXY_HTTP"} },

  { DB_NAME:      {mysql: "MYSQL_DATABASE"} },
  { DB_USER:      {mysql: "MYSQL_USER"} },
  { DB_PASS:      {mysql: "MYSQL_PASSWORD"} },

  { HOSTNAME:     {nginx: "DOMAIN"} }
]<commit_msg>Updated PHP env variable HOSTNAME to DOMAIN<commit_after>module.exports.prompt = { // use nested prompt
  "development": [{
    name: "PUBLIC_URL",
    message: "Public URL (*.local)".magenta,
    required: true
  }],
  "production": [{
    name: "PUBLIC_URL",
    message: "Public URL (*.local)".magenta,
    required: true
  }]
}

module.exports.map = {
  //DOMAIN: ["DOMAIN", "HTTP_HOST"],
  PUBLIC_URL: "PUBLIC_URL"
}

module.exports.path = "images/php/php"

module.exports.defaults = {
  dev: {
    TZ: "Europe/Rome",          // Defaults
    DOCKER: "1",                // Defaults
    ENV: "local",               // Defaults
    WP_POST_REVISIONS: "false", // Defaults
    WP_USE_THEMES: "false",     // Defaults
    WP_LANG: "it_IT",           // Defaults
    WORKDIR: "/www",

    DB_HOST: "mysql",
    DB_NAME: "",          // Match with MySQL
    DB_USER: "",          // Match with MySQL
    DB_PASS: "",          // Match with MySQL

    PROJECT_NAME: "",     // Match with main
    APP_ID: "",           // Match with main
    PORT: "",             // Match with main
  },
  prod: {
    TZ: "Europe/Rome",          // Defaults
    DOCKER: "1",                // Defaults
    ENV: "local",               // Defaults
    WP_POST_REVISIONS: "false", // Defaults
    WP_USE_THEMES: "false",     // Defaults
    WP_LANG: "it_IT",           // Defaults
    WORKDIR: "/www",

    DB_HOST: "mysql",
    DB_NAME: "",          // Match with MySQL
    DB_USER: "",          // Match with MySQL
    DB_PASS: "",          // Match with MySQL

    PROJECT_NAME: "",     // Match with main
    APP_ID: "",           // Match with main
    PORT: "80",           // Match with main

    /*HTTP_HOST: "localhost",
    DOMAIN: "localhost",
    PUBLIC_URL: "http://aeriawork.vanadio.dev"*/
  }
}

module.exports.dependencies = [
  { PROJECT_NAME: {main: "PROJECT_NAME"} },
  { APP_ID:       {main: "PROJECT_NAME"} },
  { PORT:         {main: "PROXY_HTTP"} },

  { DB_NAME:      {mysql: "MYSQL_DATABASE"} },
  { DB_USER:      {mysql: "MYSQL_USER"} },
  { DB_PASS:      {mysql: "MYSQL_PASSWORD"} },

  { DOMAIN:     {nginx: "DOMAIN"} }
]<|endoftext|>


<commit_before>window.uniengine = window.uniengine || {};
window.uniengine.phpInjectionData = window.uniengine.phpInjectionData || {};
window.uniengine.phpInjectionData.lang = window.uniengine.phpInjectionData.lang || {};

function getLangStorage () {
    return window.uniengine.phpInjectionData.lang;
}

function strPadLeft (value, desiredLenght, padString) {
    const lengthLeft = desiredLenght - (value.length);

    if (lengthLeft <= 0) {
        return value;
    }

    const padding = (new Array(lengthLeft)).fill(padString, 0, lengthLeft).join("");

    return `${padding}${value}`;
}

function prettyTime ({ seconds }) {
    const lang = getLangStorage().common;

    seconds = Math.floor(seconds);

    const SECONDS_IN_MINUTE = 60;
    const SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
    const SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;

    const days = Math.floor(seconds / SECONDS_IN_DAY);

    seconds -= (days * SECONDS_IN_DAY);

    const hours = Math.floor(seconds / SECONDS_IN_HOUR);

    seconds -= (hours * SECONDS_IN_HOUR);

    const minutes = Math.floor(seconds / SECONDS_IN_MINUTE);

    seconds -= (minutes * SECONDS_IN_MINUTE);

    const hoursString = strPadLeft(String(hours), 2, "0");
    const minutesString = strPadLeft(String(minutes), 2, "0");
    const secondsString = strPadLeft(String(seconds), 2, "0");

    const timePieces = [];

    if (days > 0) {
        timePieces.push(lang.prettyTime.formatters.daysFullJSFunction(days));
    }

    timePieces.push(`${hoursString}:${minutesString}:${secondsString}`);

    return timePieces.join(" ");
}

window.uniengine.common = {
    getLangStorage,
    strPadLeft,
    prettyTime
};
<commit_msg>GH-139 Allow to turn off hours overflow conversion<commit_after>window.uniengine = window.uniengine || {};
window.uniengine.phpInjectionData = window.uniengine.phpInjectionData || {};
window.uniengine.phpInjectionData.lang = window.uniengine.phpInjectionData.lang || {};

function getLangStorage () {
    return window.uniengine.phpInjectionData.lang;
}

function strPadLeft (value, desiredLenght, padString) {
    const lengthLeft = desiredLenght - (value.length);

    if (lengthLeft <= 0) {
        return value;
    }

    const padding = (new Array(lengthLeft)).fill(padString, 0, lengthLeft).join("");

    return `${padding}${value}`;
}

function prettyTime ({ seconds, isDayConversionDisabled = false }) {
    const lang = getLangStorage().common;

    seconds = Math.floor(seconds);

    const SECONDS_IN_MINUTE = 60;
    const SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
    const SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;

    const days = Math.floor(seconds / SECONDS_IN_DAY);

    seconds -= (days * SECONDS_IN_DAY);

    const hours = Math.floor(seconds / SECONDS_IN_HOUR);

    seconds -= (hours * SECONDS_IN_HOUR);

    const minutes = Math.floor(seconds / SECONDS_IN_MINUTE);

    seconds -= (minutes * SECONDS_IN_MINUTE);

    const hoursString = strPadLeft(String(hours), 2, "0");
    const minutesString = strPadLeft(String(minutes), 2, "0");
    const secondsString = strPadLeft(String(seconds), 2, "0");

    const timePieces = [];

    if (days > 0 && !isDayConversionDisabled) {
        timePieces.push(lang.prettyTime.formatters.daysFullJSFunction(days));
    }

    timePieces.push(`${hoursString}:${minutesString}:${secondsString}`);

    return timePieces.join(" ");
}

window.uniengine.common = {
    getLangStorage,
    strPadLeft,
    prettyTime
};
<|endoftext|>


<commit_before>/**
 * If shouldHide is true, returns a CSS class that hides the element.
 */
export function hideElement(shouldHide) {
  if (shouldHide) {
    return 'hidden';
  } else {
    return '';
  }
}
<commit_msg>add getExtension for file<commit_after>/**
 * If shouldHide is true, returns a CSS class that hides the element.
 */
export function hideElement(shouldHide) {
  if (shouldHide) {
    return 'hidden';
  } else {
    return '';
  }
}

export function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}
<|endoftext|>


<commit_before>import { cloneDeep } from 'lodash';

import buildApp from './build.js';
import debug from 'debug';
import fs from 'fs';
import nodemiral from 'nodemiral';
import os from 'os';
import random from 'random-seed';
import uuid from 'uuid';

const log = debug('mup:module:meteor');

function tmpBuildPath(appPath, api) {
  let rand = random.create(appPath);
  let uuidNumbers = [];
  for (let i = 0; i < 16; i++) {
    uuidNumbers.push(rand(255));
  }
  return api.resolvePath(
    os.tmpdir(),
    `mup-meteor-${uuid.v4({ random: uuidNumbers })}`
  );
}

export function logs(api) {
  log('exec => mup meteor logs');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const args = api.getArgs();
  if (args[0] === 'meteor') {
    args.shift();
  }

  const sessions = api.getSessions(['app']);
  return api.getDockerLogs(config.name, sessions, args);
}

export function setup(api) {
  log('exec => mup meteor setup');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const list = nodemiral.taskList('Setup Meteor');

  list.executeScript('Setup Environment', {
    script: api.resolvePath(__dirname, 'assets/meteor-setup.sh'),
    vars: {
      name: config.name
    }
  });

  if (config.ssl && typeof config.ssl.autogenerate !== 'object') {
    const basePath = api.getBasePath();

    if (config.ssl.upload !== false) {
      list.executeScript('Cleaning up SSL Certificates', {
        script: api.resolvePath(__dirname, 'assets/ssl-cleanup.sh'),
        vars: {
          name: config.name
        }
      });
      list.copy('Copying SSL Certificate Bundle', {
        src: api.resolvePath(basePath, config.ssl.crt),
        dest: '/opt/' + config.name + '/config/bundle.crt'
      });

      list.copy('Copying SSL Private Key', {
        src: api.resolvePath(basePath, config.ssl.key),
        dest: '/opt/' + config.name + '/config/private.key'
      });
    }

    list.executeScript('Verifying SSL Configurations', {
      script: api.resolvePath(__dirname, 'assets/verify-ssl-config.sh'),
      vars: {
        name: config.name
      }
    });
  }

  const sessions = api.getSessions(['app']);

  return api.runTaskList(list, sessions, { verbose: api.verbose });
}

export async function push(api) {
  log('exec => mup meteor push');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const appPath = api.resolvePath(api.getBasePath(), config.path);

  let buildOptions = config.buildOptions || {};
  buildOptions.buildLocation =
    buildOptions.buildLocation || tmpBuildPath(appPath, api);

  var bundlePath = api.resolvePath(buildOptions.buildLocation, 'bundle.tar.gz');
  var rebuild = true;

  if (api.getOptions()['cached-build']) {
    const buildCached = fs.existsSync(bundlePath);
    if (!buildCached) {
      console.log('Unable to use previous build. It doesn\'t exist.');
    } else {
      rebuild = false;
      console.log('Not rebuilding app. Using build from previous deploy at');
      console.log(`${buildOptions.buildLocation}`);
    }
  }

  if (rebuild) {
    console.log('Building App Bundle Locally');
    await buildApp(appPath, buildOptions, api.getVerbose(), api);
  }

  const list = nodemiral.taskList('Pushing Meteor App');

  list.copy('Pushing Meteor App Bundle to The Server', {
    src: bundlePath,
    dest: '/opt/' + config.name + '/tmp/bundle.tar.gz',
    progressBar: config.enableUploadProgressBar
  });

  if (!config.docker) {
    if (config.dockerImage) {
      config.docker = {
        image: config.dockerImage
      };
      delete config.dockerImage;
    } else {
      config.docker = {
        image: 'kadirahq/meteord'
      };
    }
  }

  const prepareSupported = config.docker.image === 'abernix/meteord';
  const supportedScript = api.resolvePath(
    __dirname,
    'assets/prepare-bundle.sh'
  );
  const unsupportedScript = api.resolvePath(
    __dirname,
    'assets/prepare-bundle-unsupported.sh'
  );

  list.executeScript('Prepare Bundle', {
    script: prepareSupported ? supportedScript : unsupportedScript,
    vars: {
      appName: config.name,
      dockerImage: config.docker.image
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}

export function envconfig(api) {
  log('exec => mup meteor envconfig');

  const config = api.getConfig().app;
  const servers = api.getConfig().servers;
  let bindAddress = '0.0.0.0';

  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  config.log = config.log || {
    opts: {
      'max-size': '100m',
      'max-file': 10
    }
  };

  config.nginx = config.nginx || {};

  if (config.docker && config.docker.bind) {
    bindAddress = config.docker.bind;
  }

  if (!config.docker) {
    if (config.dockerImage) {
      config.docker = {
        image: config.dockerImage
      };
      delete config.dockerImage;
    } else {
      config.docker = {
        image: 'kadirahq/meteord'
      };
    }
  }
  if (config.dockerImageFrontendServer) {
    config.docker.imageFrontendServer = config.dockerImageFrontendServer;
  }
  if (!config.docker.imageFrontendServer) {
    config.docker.imageFrontendServer = 'meteorhacks/mup-frontend-server';
  }

  // If imagePort is not set, go with port 80 which was the traditional
  // port used by kadirahq/meteord and meteorhacks/meteord
  config.docker.imagePort = config.docker.imagePort || 80;

  if (config.ssl) {
    config.ssl.port = config.ssl.port || 443;
  }

  const list = nodemiral.taskList('Configuring App');
  list.copy('Pushing the Startup Script', {
    src: api.resolvePath(__dirname, 'assets/templates/start.sh'),
    dest: '/opt/' + config.name + '/config/start.sh',
    vars: {
      appName: config.name,
      useLocalMongo: api.getConfig().mongo ? 1 : 0,
      port: config.env.PORT || 80,
      bind: bindAddress,
      sslConfig: config.ssl,
      logConfig: config.log,
      volumes: config.volumes,
      docker: config.docker,
      proxyConfig: api.getConfig().proxy,
      nginxClientUploadLimit: config.nginx.clientUploadLimit || '10M'
    }
  });

  var env = cloneDeep(config.env);
  env.METEOR_SETTINGS = JSON.stringify(api.getSettings());
  // sending PORT to the docker container is useless.

  // setting PORT in the config is used for the publicly accessible
  // port.

  // docker.imagePort is used for the port exposed from the container.
  // In case the docker.imagePort is different than the container's
  // default port, we set the env PORT to docker.imagePort.
  env.PORT = config.docker.imagePort;

  const hostVars = {};
  Object.keys(config.servers).forEach(key => {
    if (config.servers[key].env) {
      hostVars[servers[key].host] = {env: config.servers[key].env};
    }
  });

  list.copy('Sending Environment Variables', {
    src: api.resolvePath(__dirname, 'assets/templates/env.list'),
    dest: '/opt/' + config.name + '/config/env.list',
    hostVars,
    vars: {
      env: env || {},
      appName: config.name
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}

export function start(api) {
  log('exec => mup meteor start');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const list = nodemiral.taskList('Start Meteor');

  list.executeScript('Start Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-start.sh'),
    vars: {
      appName: config.name
    }
  });

  list.executeScript('Verifying Deployment', {
    script: api.resolvePath(__dirname, 'assets/meteor-deploy-check.sh'),
    vars: {
      deployCheckWaitTime: config.deployCheckWaitTime || 60,
      appName: config.name,
      deployCheckPort: config.deployCheckPort || config.env.PORT || 80,
      deployCheckPath: '',
      host: api.getConfig().proxy ?
        api.getConfig().proxy.domains.split(',')[0] :
        null
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}

export function deploy(api) {
  log('exec => mup meteor deploy');

  // validate settings and config before starting
  api.getSettings();
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  return api
    .runCommand('meteor.push')
    .then(() => api.runCommand('meteor.envconfig'))
    .then(() => api.runCommand('meteor.start'));
}

export function stop(api) {
  log('exec => mup meteor stop');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const list = nodemiral.taskList('Stop Meteor');

  list.executeScript('Stop Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-stop.sh'),
    vars: {
      appName: config.name
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, { verbose: api.verbose });
}

export function restart(api) {
  const list = nodemiral.taskList('Restart Meteor');
  const sessions = api.getSessions(['meteor']);
  const config = api.getConfig().app;

  list.executeScript('Stop Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-stop.sh'),
    vars: {
      appName: config.name
    }
  });

  list.executeScript('Start Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-start.sh'),
    vars: {
      appName: config.name
    }
  });

  list.executeScript('Verifying Deployment', {
    script: api.resolvePath(__dirname, 'assets/meteor-deploy-check.sh'),
    vars: {
      deployCheckWaitTime: config.deployCheckWaitTime || 60,
      appName: config.name,
      deployCheckPort: config.deployCheckPort || config.env.PORT || 80,
      deployCheckPath: '',
      host: api.getConfig().proxy ?
        api.getConfig().proxy.domains.split(',')[0] : null
    }
  });

  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}
<commit_msg>Improve checking docker image<commit_after>import { cloneDeep } from 'lodash';

import buildApp from './build.js';
import debug from 'debug';
import fs from 'fs';
import nodemiral from 'nodemiral';
import os from 'os';
import random from 'random-seed';
import uuid from 'uuid';

const log = debug('mup:module:meteor');

function tmpBuildPath(appPath, api) {
  let rand = random.create(appPath);
  let uuidNumbers = [];
  for (let i = 0; i < 16; i++) {
    uuidNumbers.push(rand(255));
  }
  return api.resolvePath(
    os.tmpdir(),
    `mup-meteor-${uuid.v4({ random: uuidNumbers })}`
  );
}

export function logs(api) {
  log('exec => mup meteor logs');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const args = api.getArgs();
  if (args[0] === 'meteor') {
    args.shift();
  }

  const sessions = api.getSessions(['app']);
  return api.getDockerLogs(config.name, sessions, args);
}

export function setup(api) {
  log('exec => mup meteor setup');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const list = nodemiral.taskList('Setup Meteor');

  list.executeScript('Setup Environment', {
    script: api.resolvePath(__dirname, 'assets/meteor-setup.sh'),
    vars: {
      name: config.name
    }
  });

  if (config.ssl && typeof config.ssl.autogenerate !== 'object') {
    const basePath = api.getBasePath();

    if (config.ssl.upload !== false) {
      list.executeScript('Cleaning up SSL Certificates', {
        script: api.resolvePath(__dirname, 'assets/ssl-cleanup.sh'),
        vars: {
          name: config.name
        }
      });
      list.copy('Copying SSL Certificate Bundle', {
        src: api.resolvePath(basePath, config.ssl.crt),
        dest: '/opt/' + config.name + '/config/bundle.crt'
      });

      list.copy('Copying SSL Private Key', {
        src: api.resolvePath(basePath, config.ssl.key),
        dest: '/opt/' + config.name + '/config/private.key'
      });
    }

    list.executeScript('Verifying SSL Configurations', {
      script: api.resolvePath(__dirname, 'assets/verify-ssl-config.sh'),
      vars: {
        name: config.name
      }
    });
  }

  const sessions = api.getSessions(['app']);

  return api.runTaskList(list, sessions, { verbose: api.verbose });
}

export async function push(api) {
  log('exec => mup meteor push');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const appPath = api.resolvePath(api.getBasePath(), config.path);

  let buildOptions = config.buildOptions || {};
  buildOptions.buildLocation =
    buildOptions.buildLocation || tmpBuildPath(appPath, api);

  var bundlePath = api.resolvePath(buildOptions.buildLocation, 'bundle.tar.gz');
  var rebuild = true;

  if (api.getOptions()['cached-build']) {
    const buildCached = fs.existsSync(bundlePath);
    if (!buildCached) {
      console.log('Unable to use previous build. It doesn\'t exist.');
    } else {
      rebuild = false;
      console.log('Not rebuilding app. Using build from previous deploy at');
      console.log(`${buildOptions.buildLocation}`);
    }
  }

  if (rebuild) {
    console.log('Building App Bundle Locally');
    await buildApp(appPath, buildOptions, api.getVerbose(), api);
  }

  const list = nodemiral.taskList('Pushing Meteor App');

  list.copy('Pushing Meteor App Bundle to The Server', {
    src: bundlePath,
    dest: '/opt/' + config.name + '/tmp/bundle.tar.gz',
    progressBar: config.enableUploadProgressBar
  });

  if (!config.docker) {
    if (config.dockerImage) {
      config.docker = {
        image: config.dockerImage
      };
      delete config.dockerImage;
    } else {
      config.docker = {
        image: 'kadirahq/meteord'
      };
    }
  }

  const prepareSupported = config.docker.image.indexOf('abernix/meteord') === 0;
  const supportedScript = api.resolvePath(
    __dirname,
    'assets/prepare-bundle.sh'
  );
  const unsupportedScript = api.resolvePath(
    __dirname,
    'assets/prepare-bundle-unsupported.sh'
  );

  list.executeScript('Prepare Bundle', {
    script: prepareSupported ? supportedScript : unsupportedScript,
    vars: {
      appName: config.name,
      dockerImage: config.docker.image
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}

export function envconfig(api) {
  log('exec => mup meteor envconfig');

  const config = api.getConfig().app;
  const servers = api.getConfig().servers;
  let bindAddress = '0.0.0.0';

  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  config.log = config.log || {
    opts: {
      'max-size': '100m',
      'max-file': 10
    }
  };

  config.nginx = config.nginx || {};

  if (config.docker && config.docker.bind) {
    bindAddress = config.docker.bind;
  }

  if (!config.docker) {
    if (config.dockerImage) {
      config.docker = {
        image: config.dockerImage
      };
      delete config.dockerImage;
    } else {
      config.docker = {
        image: 'kadirahq/meteord'
      };
    }
  }
  if (config.dockerImageFrontendServer) {
    config.docker.imageFrontendServer = config.dockerImageFrontendServer;
  }
  if (!config.docker.imageFrontendServer) {
    config.docker.imageFrontendServer = 'meteorhacks/mup-frontend-server';
  }

  // If imagePort is not set, go with port 80 which was the traditional
  // port used by kadirahq/meteord and meteorhacks/meteord
  config.docker.imagePort = config.docker.imagePort || 80;

  if (config.ssl) {
    config.ssl.port = config.ssl.port || 443;
  }

  const list = nodemiral.taskList('Configuring App');
  list.copy('Pushing the Startup Script', {
    src: api.resolvePath(__dirname, 'assets/templates/start.sh'),
    dest: '/opt/' + config.name + '/config/start.sh',
    vars: {
      appName: config.name,
      useLocalMongo: api.getConfig().mongo ? 1 : 0,
      port: config.env.PORT || 80,
      bind: bindAddress,
      sslConfig: config.ssl,
      logConfig: config.log,
      volumes: config.volumes,
      docker: config.docker,
      proxyConfig: api.getConfig().proxy,
      nginxClientUploadLimit: config.nginx.clientUploadLimit || '10M'
    }
  });

  var env = cloneDeep(config.env);
  env.METEOR_SETTINGS = JSON.stringify(api.getSettings());
  // sending PORT to the docker container is useless.

  // setting PORT in the config is used for the publicly accessible
  // port.

  // docker.imagePort is used for the port exposed from the container.
  // In case the docker.imagePort is different than the container's
  // default port, we set the env PORT to docker.imagePort.
  env.PORT = config.docker.imagePort;

  const hostVars = {};
  Object.keys(config.servers).forEach(key => {
    if (config.servers[key].env) {
      hostVars[servers[key].host] = {env: config.servers[key].env};
    }
  });

  list.copy('Sending Environment Variables', {
    src: api.resolvePath(__dirname, 'assets/templates/env.list'),
    dest: '/opt/' + config.name + '/config/env.list',
    hostVars,
    vars: {
      env: env || {},
      appName: config.name
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}

export function start(api) {
  log('exec => mup meteor start');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const list = nodemiral.taskList('Start Meteor');

  list.executeScript('Start Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-start.sh'),
    vars: {
      appName: config.name
    }
  });

  list.executeScript('Verifying Deployment', {
    script: api.resolvePath(__dirname, 'assets/meteor-deploy-check.sh'),
    vars: {
      deployCheckWaitTime: config.deployCheckWaitTime || 60,
      appName: config.name,
      deployCheckPort: config.deployCheckPort || config.env.PORT || 80,
      deployCheckPath: '',
      host: api.getConfig().proxy ?
        api.getConfig().proxy.domains.split(',')[0] :
        null
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}

export function deploy(api) {
  log('exec => mup meteor deploy');

  // validate settings and config before starting
  api.getSettings();
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  return api
    .runCommand('meteor.push')
    .then(() => api.runCommand('meteor.envconfig'))
    .then(() => api.runCommand('meteor.start'));
}

export function stop(api) {
  log('exec => mup meteor stop');
  const config = api.getConfig().app;
  if (!config) {
    console.error('error: no configs found for meteor');
    process.exit(1);
  }

  const list = nodemiral.taskList('Stop Meteor');

  list.executeScript('Stop Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-stop.sh'),
    vars: {
      appName: config.name
    }
  });

  const sessions = api.getSessions(['app']);
  return api.runTaskList(list, sessions, { verbose: api.verbose });
}

export function restart(api) {
  const list = nodemiral.taskList('Restart Meteor');
  const sessions = api.getSessions(['meteor']);
  const config = api.getConfig().app;

  list.executeScript('Stop Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-stop.sh'),
    vars: {
      appName: config.name
    }
  });

  list.executeScript('Start Meteor', {
    script: api.resolvePath(__dirname, 'assets/meteor-start.sh'),
    vars: {
      appName: config.name
    }
  });

  list.executeScript('Verifying Deployment', {
    script: api.resolvePath(__dirname, 'assets/meteor-deploy-check.sh'),
    vars: {
      deployCheckWaitTime: config.deployCheckWaitTime || 60,
      appName: config.name,
      deployCheckPort: config.deployCheckPort || config.env.PORT || 80,
      deployCheckPath: '',
      host: api.getConfig().proxy ?
        api.getConfig().proxy.domains.split(',')[0] : null
    }
  });

  return api.runTaskList(list, sessions, {
    series: true,
    verbose: api.verbose
  });
}
<|endoftext|>


<commit_before>'use strict';

const methods = {
  accountInformation: require('./methods/account-information'),
  createEvent: require('./methods/create-event'),
  createNotificationChannel: require('./methods/create-notification-channel'),
  deleteEvent: require('./methods/delete-event'),
  deleteNotificationChannel: require('./methods/delete-notification-channel'),
  freeBusy: require('./methods/free-busy'),
  listCalendars: require('./methods/list-calendars'),
  listNotificationChannels: require('./methods/list-notification-channels'),
  profileInformation: require('./methods/profile-information'),
  readEvents: require('./methods/read-events'),
  refreshAccessToken: require('./methods/refresh-access-token'),
  requestAccessToken: require('./methods/request-access-token'),
  revokeAuthorization: require('./methods/revoke-authorization')
};

module.exports = methods;

<commit_msg>improves style consistency in index.js<commit_after>'use strict';

import accountInformation from './methods/account-information';
import createEvent from './methods/create-event';
import createNotificationChannel from './methods/create-notification-channel';
import accountInformation from './methods/account-information';
import createEvent from './methods/create-event';
import createNotificationChannel from './methods/create-notification-channel';
import deleteEvent from './methods/delete-event';
import deleteNotificationChannel from './methods/delete-notification-channel';
import freeBusy from './methods/free-busy';
import listCalendars from './methods/list-calendars';
import listNotificationChannels from './methods/list-notification-channels';
import profileInformation from './methods/profile-information';
import readEvents from './methods/read-events';
import refreshAccessToken from './methods/refresh-access-token';
import requestAccessToken from './methods/request-access-token';
import revokeAuthorization from './methods/revoke-authorization';

const methods = {
  accountInformation,
  createEvent,
  createNotificationChannel,
  deleteEvent,
  deleteNotificationChannel,
  freeBusy,
  listCalendars,
  listNotificationChannels,
  profileInformation,
  readEvents,
  refreshAccessToken,
  requestAccessToken,
  revokeAuthorization
};

export default methods;
<|endoftext|>


<commit_before>/**
 * This is our closure - all of our code goes inside it
 *
 * This style of closure is provided by jquery and automatically
 * waits for document.ready. It also provides us with a local
 * alias of jQuery as $.
 *
 * ES5 specifies that the first line inside our closure
 * should be 'use strict';
 */

cj(function ($, ts) {
	'use strict';

	// log
	console.log("translation js loaded 2015" + ts('Translation from javascript single quote'));

	// CRM alert
	window.alert(ts('Translation from javascript single quote'));
	window.alert(ts("Translation from javascript double quote"));

	// fill div
	var div = document.getElementById('divjs');
	div.innerHTML = div.innerHTML + ts("Translation from javascript double quote");

}(CRM.$, CRM.ts('be.ctrl.translation')));

<commit_msg>Updates for script.js<commit_after>/**
 * This is our closure - all of our code goes inside it
 *
 * This style of closure is provided by jquery and automatically
 * waits for document.ready. It also provides us with a local
 * alias of jQuery as $.
 *
 * ES5 specifies that the first line inside our closure
 * should be 'use strict';
 */

(function($, ts) {
	'use strict';

	// log
	console.log("be.ctrl.translation/js/script.js");

	// fill div
	$('div#divjs').append(ts("Translation from javascript double quote"));
  $('div#divjs').on('click', function() {
    // CRM alert
		alert(ts('Translation from javascript single quote'));
		alert(ts("Translation from javascript double quote"));
  });
})(CRM.$, CRM.ts('be.ctrl.translation'));
<|endoftext|>


<commit_before>function compileCode (input, usage, mode) {
    $.ajax({
       type: "POST",
       contentType: "application/json",
       url: '/compiler/' + mode,
       data: JSON.stringify(input),
       dataType: "json",
       success: usage,
       error: function(j, t, e) {}
    });
};

var heightUpdateFunction = function(editor, id) {
    // http://stackoverflow.com/questions/11584061/
    //console.log(id);
    //console.log(editor);
    var newHeight =
              editor.getSession().getScreenLength()
              * editor.renderer.lineHeight
              + editor.renderer.scrollBar.getWidth();

    $(id).height(newHeight.toString() + "px");
    // This call is required for the editor to fix all of
    // its inner structure for adapting to a change in size
    editor.resize();
};

function outputResult(doc, id, result, compilers) {
      switch(result.format) {
        case "html": doc.cells[id].renderDisplay.html(result.result); break;
        case "string": doc.cells[id].renderDisplay.html("
" + result.result + "
"); break;
      }
      if(compilers[doc.cells[id].mode].hideAfterCompile) $('#toggleEditor'+id).click();
      MathJax.Hub.Queue(["Typeset",MathJax.Hub,"renderDisplay"+id]);
      $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
      });
      /*
      // post compiling work
      switch(doc.cells[id].mode) {
        case "scala": break;
        case "markdown":
            $('#toggleEditor'+id).click();
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,"renderDisplay"+id]);
            break;
        case "latex":
            $('#toggleEditor'+id).click();
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,"renderDisplay"+id]);
            break;
        case "heading1":
            $('#toggleEditor'+id).click();
            break;
        case "heading2":
            $('#toggleEditor'+id).click();
            break;
        case "heading3":
            $('#toggleEditor'+id).click();
            break;
        case "heading4":
            $('#toggleEditor'+id).click();
            break;
        case "heading5":
            $('#toggleEditor'+id).click();
            break;
      }*/
}

function runCode(doc, id, compilers) {
  outputResult(doc, id, { format: "html", result: '
' +
                                                  '   ' +
                                                  '
' }, compilers)
  var mode = doc.cells[id].mode;
  var compiler = compilers[mode];
  var input = compiler.editorToInput(doc, id);
  input.extraFields = doc.cells[id].config;
  var aggregateCell = true;
  if(input.extraFields.hasOwnProperty('aggregate'))
    aggregateCell = input.extraFields.aggregate === 'true';
  var aggregateScope = "_default";
  if(input.extraFields.hasOwnProperty('scope'))
    aggregateScope = input.extraFields.scope;
  if(compiler.aggregate && aggregateCell) {
    var prefixConfig = {};
    var prefixInput = "";
    for(var midx in doc.ids) {
      var mid = doc.ids[midx];
      var scope = "_default"
      if(doc.cells[mid].config.hasOwnProperty('scope'))
        scope = doc.cells[mid].config.scope;
      if(doc.cells[mid].mode === mode && aggregateScope === scope) {
        if(id == mid) break;
        // config
        for(var ck in doc.cells[mid].config) {
          console.log(mid + " : " + ck);
          if(prefixConfig.hasOwnProperty(ck) && prefixConfig[ck] != doc.cells[mid].config[ck]) {
            console.log("Replacing config " + ck + " = " + prefixConfig[ck] + " with " + doc.cells[mid].config[ck])
          }
          prefixConfig[ck] = doc.cells[mid].config[ck];
        }
        // code
        prefixInput = prefixInput + compiler.editorToInput(doc, doc.cells[mid].id).code + "\n";
      }
    }
    for(var ck in prefixConfig) {
      console.log("prefix : " + ck);
      if(input.extraFields.hasOwnProperty(ck) && prefixConfig[ck] != input.extraFields[ck]) {
        console.log("Replacing config " + ck + " = " + input.extraFields[ck] + " with " + prefixConfig[ck])
      }
      input.extraFields[ck] = prefixConfig[ck];
    }
    input.code = prefixInput + input.code;
  }
  compileCode(input,
      function(x) {
        outputResult(doc, id, x, compilers);
      }, doc.cells[id].mode);
}

function changeMode(id, newMode) {
   var currentCode = compilers[doc.cells[id].mode].editorToInput(doc, id).code;
   compilers[doc.cells[id].mode].removeEditor(id);
   doc.cells[id].mode = newMode;
   //text = doc.cells[id].editor.getSession().getValue();
   doc.cells[id].editor = compilers[newMode].editor(id, currentCode);
   doc.cells[id].editor.focus();
}

function newCellDiv(id) {
   return '
' +
   '
' +
   '
' +
   '
' +
   '      ' +
   '      <button id="addAbove' + id + '" type="button" class="btn btn-default" onclick="addCellAbove(doc,' + id + ',compilers)"></button>' +
   '      <button id="toggleCellConfig' + id + '" type="button" class="btn btn-default edit-btn" onclick="cellConfigClicked(' + id + ', doc, compilers)"></button>' +
   '      <button id="toggleEditor' + id + '" type="button" class="btn btn-default edit-btn" onclick="toggleEditor(doc,' + id + ')"></button>' +
   '      <button id="remove' + id + '" type="button" class="btn btn-default" onclick="removeCell(doc,' + id + ')"></button>' +
   '      <button id="addBelow' + id + '" type="button" class="btn btn-default" onclick="addCellBelow(doc,' + id + ',compilers)"></button>' +
   '      ' +
   '
' +
   '
' +
   //'  cell ' + id + ' contents' +
   '
' +
   '
' + editorToolbar() +
   '
' +
   '

' +
   '      <button id="runCode' + id + '" type="button" class="btn btn-default btn-xs" onclick="runCode(doc, ' + id + ',compilers)"></button>' +
   '
' +
   '

' +
   '
' +
   '
'
}

function makeCellFunctional(doc,id,compiler,compilers,initialContent,config) {
    doc.cells[id] = new Object();
    doc.cells[id].id = id;
    doc.cells[id].mode = compiler;
    doc.cells[id].renderDisplay = $('#renderDisplay' + id);
    doc.cells[id].config = config;

    doc.cells[id].editor = compilers[compiler].editor(id,initialContent);
    doc.cells[id].showEditor = true;

    $('.btn').button();

    var sz = $('#modeForm'+id+' label');
    for (var i=0, len=sz.length; i<len; i++) {
        sz[i].onclick = function() {
            newMode = this.querySelector('input').value;
            //console.log(doc.cells[id].mode, newMode);
            if(doc.cells[id].mode != newMode) {
              changeMode(id, newMode);
            }
        };
    }
}

function addCellFromJson(doc,format,content,compilers,config) {
  $( "#cells" ).append(newCellDiv(doc.numCells));
  doc.ids.push(doc.numCells);
  makeCellFunctional(doc,doc.numCells,format,compilers,content, config);
  //doc.cells[doc.numCells].editor.getSession().setValue(content);
  $('#modeForm'+ doc.numCells +' label input[value='+ format +']').parent().click()
  //runCode(doc, doc.numCells, compilers);
  doc.numCells += 1;
}

function addCell(doc,compilers) {
  $( "#cells" ).append(newCellDiv(doc.numCells));
  doc.ids.push(doc.numCells);
  makeCellFunctional(doc,doc.numCells, "scala",compilers,"",{});
  doc.numCells += 1;
}

function addCellAbove(doc,id,compilers) {
  console.log("TODO: adding above " + id);
  $( "#cell"+id ).before(newCellDiv(doc.numCells));
  doc.ids.splice(doc.ids.indexOf(id),0,doc.numCells);
  makeCellFunctional(doc,doc.numCells, "scala",compilers,"",{});
  doc.numCells += 1;
}

function addCellBelow(doc,id,compilers) {
  console.log("TODO: adding below " + id);
  $( "#cell"+id ).after(newCellDiv(doc.numCells));
  doc.ids.splice(doc.ids.indexOf(id)+1,0,doc.numCells);
  makeCellFunctional(doc,doc.numCells, "scala",compilers,"",{});
  doc.numCells += 1;
}

function moveCellAbove(doc,id,compilers) {
  console.log("TODO: move cell up " + id);
  //$( "#cell"+id ).before(newCellDiv(doc.numCells));
  //doc.ids.splice(doc.ids.indexOf(id),0,doc.numCells);
  //makeCellFunctional(doc,doc.numCells, "scala",compilers,{});
  //doc.numCells += 1;
}

function moveCellBelow(doc,id,compilers) {
  console.log("TODO: move cell down " + id);
  //$( "#cell"+id ).after(newCellDiv(doc.numCells));
  //doc.ids.splice(doc.ids.indexOf(id)+1,0,doc.numCells);
  //makeCellFunctional(doc,doc.numCells, "scala",compilers,{});
  //doc.numCells += 1;
}

function toggleEditor(doc,id) {
  doc.cells[id].showEditor = !doc.cells[id].showEditor;
  if(doc.cells[id].showEditor) {
    // console.log("showing editor" + id);
    $('#editCell' + id + ' .input').show();
  } else {
    // console.log("hiding editor" + id);
    $('#editCell' + id + ' .input').hide();
  }
}

function removeCell(doc,id) {
  console.log("removing " + id);
  $('#cell' + id).remove();
  delete doc.cells[id];
}

function saveDoc(doc, compilers) {
  console.log("saving doc to " + $('#saveAsInput')[0].value);
  var d = docToJson(doc,compilers);
  console.log(d);
  $.ajax({
       type: "POST",
       contentType: "application/json",
       url: '/doc/save/' + $('#saveAsInput')[0].value,
       data: JSON.stringify(d),
       success: function(d) {
         bootstrap_alert("success", "Success", "Saved to " + $('#saveAsInput')[0].value, 2000);
         console.log(d);
       },
       error: function(j,t,e) {
         bootstrap_alert("danger", "Failed", JSON.stringify(e), 5000);
         console.log(d);
       }
    });
}

function runAll(doc, compilers) {
  for (var idx in doc.ids){
    var id = doc.ids[idx];
    if (doc.cells.hasOwnProperty(id)) {
      runCode(doc, id, compilers);
    }
  }
}
<commit_msg>minor bugfix<commit_after>function compileCode (input, usage, mode) {
    $.ajax({
       type: "POST",
       contentType: "application/json",
       url: '/compiler/' + mode,
       data: JSON.stringify(input),
       dataType: "json",
       success: usage,
       error: function(j, t, e) {}
    });
};

var heightUpdateFunction = function(editor, id) {
    // http://stackoverflow.com/questions/11584061/
    //console.log(id);
    //console.log(editor);
    var newHeight =
              editor.getSession().getScreenLength()
              * editor.renderer.lineHeight
              + editor.renderer.scrollBar.getWidth();

    $(id).height(newHeight.toString() + "px");
    // This call is required for the editor to fix all of
    // its inner structure for adapting to a change in size
    editor.resize();
};

function outputResult(doc, id, result, compilers) {
      switch(result.format) {
        case "html": doc.cells[id].renderDisplay.html(result.result); break;
        case "string": doc.cells[id].renderDisplay.html("
" + result.result + "
"); break;
      }
      if(compilers[doc.cells[id].mode].hideAfterCompile) $('#toggleEditor'+id).click();
      MathJax.Hub.Queue(["Typeset",MathJax.Hub,"renderDisplay"+id]);
      $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
      });
      /*
      // post compiling work
      switch(doc.cells[id].mode) {
        case "scala": break;
        case "markdown":
            $('#toggleEditor'+id).click();
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,"renderDisplay"+id]);
            break;
        case "latex":
            $('#toggleEditor'+id).click();
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,"renderDisplay"+id]);
            break;
        case "heading1":
            $('#toggleEditor'+id).click();
            break;
        case "heading2":
            $('#toggleEditor'+id).click();
            break;
        case "heading3":
            $('#toggleEditor'+id).click();
            break;
        case "heading4":
            $('#toggleEditor'+id).click();
            break;
        case "heading5":
            $('#toggleEditor'+id).click();
            break;
      }*/
}

function runCode(doc, id, compilers) {
  outputResult(doc, id, { format: "html", result: '
' +
                                                  '   ' +
                                                  '
' }, compilers)
  var mode = doc.cells[id].mode;
  var compiler = compilers[mode];
  var input = compiler.editorToInput(doc, id);
  input.extraFields = doc.cells[id].config;
  var aggregateCell = true;
  if(input.extraFields != null && input.extraFields.hasOwnProperty('aggregate'))
    aggregateCell = input.extraFields.aggregate === 'true';
  var aggregateScope = "_default";
  if(input.extraFields != null && input.extraFields.hasOwnProperty('scope'))
    aggregateScope = input.extraFields.scope;
  if(compiler.aggregate && aggregateCell) {
    var prefixConfig = {};
    var prefixInput = "";
    for(var midx in doc.ids) {
      var mid = doc.ids[midx];
      var scope = "_default"
      if(doc.cells[mid].config.hasOwnProperty('scope'))
        scope = doc.cells[mid].config.scope;
      if(doc.cells[mid].mode === mode && aggregateScope === scope) {
        if(id == mid) break;
        // config
        for(var ck in doc.cells[mid].config) {
          if(prefixConfig.hasOwnProperty(ck) && prefixConfig[ck] != doc.cells[mid].config[ck]) {
            console.log("Replacing config " + ck + " = " + prefixConfig[ck] + " with " + doc.cells[mid].config[ck])
          }
          prefixConfig[ck] = doc.cells[mid].config[ck];
        }
        // code
        prefixInput = prefixInput + compiler.editorToInput(doc, doc.cells[mid].id).code + "\n";
      }
    }
    for(var ck in prefixConfig) {
      if(input.extraFields.hasOwnProperty(ck) && prefixConfig[ck] != input.extraFields[ck]) {
        console.log("Replacing config " + ck + " = " + input.extraFields[ck] + " with " + prefixConfig[ck])
      }
      input.extraFields[ck] = prefixConfig[ck];
    }
    input.code = prefixInput + input.code;
  }
  compileCode(input,
      function(x) {
        outputResult(doc, id, x, compilers);
      }, doc.cells[id].mode);
}

function changeMode(id, newMode) {
   var currentCode = compilers[doc.cells[id].mode].editorToInput(doc, id).code;
   compilers[doc.cells[id].mode].removeEditor(id);
   doc.cells[id].mode = newMode;
   //text = doc.cells[id].editor.getSession().getValue();
   doc.cells[id].editor = compilers[newMode].editor(id, currentCode);
   doc.cells[id].editor.focus();
}

function newCellDiv(id) {
   return '
' +
   '
' +
   '
' +
   '
' +
   '      ' +
   '      <button id="addAbove' + id + '" type="button" class="btn btn-default" onclick="addCellAbove(doc,' + id + ',compilers)"></button>' +
   '      <button id="toggleCellConfig' + id + '" type="button" class="btn btn-default edit-btn" onclick="cellConfigClicked(' + id + ', doc, compilers)"></button>' +
   '      <button id="toggleEditor' + id + '" type="button" class="btn btn-default edit-btn" onclick="toggleEditor(doc,' + id + ')"></button>' +
   '      <button id="remove' + id + '" type="button" class="btn btn-default" onclick="removeCell(doc,' + id + ')"></button>' +
   '      <button id="addBelow' + id + '" type="button" class="btn btn-default" onclick="addCellBelow(doc,' + id + ',compilers)"></button>' +
   '      ' +
   '
' +
   '
' +
   //'  cell ' + id + ' contents' +
   '
' +
   '
' + editorToolbar() +
   '
' +
   '

' +
   '      <button id="runCode' + id + '" type="button" class="btn btn-default btn-xs" onclick="runCode(doc, ' + id + ',compilers)"></button>' +
   '
' +
   '

' +
   '
' +
   '
'
}

function makeCellFunctional(doc,id,compiler,compilers,initialContent,config) {
    doc.cells[id] = new Object();
    doc.cells[id].id = id;
    doc.cells[id].mode = compiler;
    doc.cells[id].renderDisplay = $('#renderDisplay' + id);
    doc.cells[id].config = config;

    doc.cells[id].editor = compilers[compiler].editor(id,initialContent);
    doc.cells[id].showEditor = true;

    $('.btn').button();

    var sz = $('#modeForm'+id+' label');
    for (var i=0, len=sz.length; i<len; i++) {
        sz[i].onclick = function() {
            newMode = this.querySelector('input').value;
            //console.log(doc.cells[id].mode, newMode);
            if(doc.cells[id].mode != newMode) {
              changeMode(id, newMode);
            }
        };
    }
}

function addCellFromJson(doc,format,content,compilers,config) {
  $( "#cells" ).append(newCellDiv(doc.numCells));
  doc.ids.push(doc.numCells);
  makeCellFunctional(doc,doc.numCells,format,compilers,content, config);
  //doc.cells[doc.numCells].editor.getSession().setValue(content);
  $('#modeForm'+ doc.numCells +' label input[value='+ format +']').parent().click()
  //runCode(doc, doc.numCells, compilers);
  doc.numCells += 1;
}

function addCell(doc,compilers) {
  $( "#cells" ).append(newCellDiv(doc.numCells));
  doc.ids.push(doc.numCells);
  makeCellFunctional(doc,doc.numCells, "scala",compilers,"",{});
  doc.numCells += 1;
}

function addCellAbove(doc,id,compilers) {
  console.log("TODO: adding above " + id);
  $( "#cell"+id ).before(newCellDiv(doc.numCells));
  doc.ids.splice(doc.ids.indexOf(id),0,doc.numCells);
  makeCellFunctional(doc,doc.numCells, "scala",compilers,"",{});
  doc.numCells += 1;
}

function addCellBelow(doc,id,compilers) {
  console.log("TODO: adding below " + id);
  $( "#cell"+id ).after(newCellDiv(doc.numCells));
  doc.ids.splice(doc.ids.indexOf(id)+1,0,doc.numCells);
  makeCellFunctional(doc,doc.numCells, "scala",compilers,"",{});
  doc.numCells += 1;
}

function moveCellAbove(doc,id,compilers) {
  console.log("TODO: move cell up " + id);
  //$( "#cell"+id ).before(newCellDiv(doc.numCells));
  //doc.ids.splice(doc.ids.indexOf(id),0,doc.numCells);
  //makeCellFunctional(doc,doc.numCells, "scala",compilers,{});
  //doc.numCells += 1;
}

function moveCellBelow(doc,id,compilers) {
  console.log("TODO: move cell down " + id);
  //$( "#cell"+id ).after(newCellDiv(doc.numCells));
  //doc.ids.splice(doc.ids.indexOf(id)+1,0,doc.numCells);
  //makeCellFunctional(doc,doc.numCells, "scala",compilers,{});
  //doc.numCells += 1;
}

function toggleEditor(doc,id) {
  doc.cells[id].showEditor = !doc.cells[id].showEditor;
  if(doc.cells[id].showEditor) {
    // console.log("showing editor" + id);
    $('#editCell' + id + ' .input').show();
  } else {
    // console.log("hiding editor" + id);
    $('#editCell' + id + ' .input').hide();
  }
}

function removeCell(doc,id) {
  console.log("removing " + id);
  $('#cell' + id).remove();
  delete doc.cells[id];
}

function saveDoc(doc, compilers) {
  console.log("saving doc to " + $('#saveAsInput')[0].value);
  var d = docToJson(doc,compilers);
  console.log(d);
  $.ajax({
       type: "POST",
       contentType: "application/json",
       url: '/doc/save/' + $('#saveAsInput')[0].value,
       data: JSON.stringify(d),
       success: function(d) {
         bootstrap_alert("success", "Success", "Saved to " + $('#saveAsInput')[0].value, 2000);
         console.log(d);
       },
       error: function(j,t,e) {
         bootstrap_alert("danger", "Failed", JSON.stringify(e), 5000);
         console.log(d);
       }
    });
}

function runAll(doc, compilers) {
  for (var idx in doc.ids){
    var id = doc.ids[idx];
    if (doc.cells.hasOwnProperty(id)) {
      runCode(doc, id, compilers);
    }
  }
}
<|endoftext|>


<commit_before>/* global requirejs, require */
/**
  A custom resolver to allow template names in the format we like.

  @class Resolver
  @extends Ember.DefaultResolver
  @namespace Discourse
  @module Discourse
**/

var classify = Ember.String.classify;
var get = Ember.get;

function parseName(fullName) {
    /*jshint validthis:true */

    var nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

    return {
      fullName: fullName,
      type: type,
      fullNameWithoutType: fullNameWithoutType,
      name: name,
      root: root,
      resolveMethodName: "resolve" + classify(type)
    };
}

Discourse.Resolver = Ember.DefaultResolver.extend({

  parseName: parseName,

  normalize: function(fullName) {
    var split = fullName.split(':');
    if (split.length > 1) {
      var dashed = Ember.String.dasherize(split[1].replace(/\./g, '/')),
          moduleName = 'discourse/' + split[0] + 's/' + dashed;
      if (requirejs.entries[moduleName]) {
        return split[0] + ":" + dashed;
      }
    }
    return this._super(fullName);
  },

  customResolve: function(parsedName) {
    var moduleName = 'discourse/' + parsedName.type + 's/' + parsedName.fullNameWithoutType,
        module = requirejs.entries[moduleName];

    if (module) {
      module = require(moduleName, null, null, true /* force sync */);
      if (module && module['default']) { module = module['default']; }
    }
    return module;
  },

  resolveController: function(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveComponent: function(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  /**
    Attaches a view and wires up the container properly

    @method resolveTemplate
    @param {String} parsedName the name of the template we want to resolve
    @returns {Template} the template (if found)
  **/
  resolveTemplate: function(parsedName) {
    return this.findPluginTemplate(parsedName) ||
           this.findMobileTemplate(parsedName) ||
           this.findTemplate(parsedName) ||
           Ember.TEMPLATES.not_found;
  },

  findPluginTemplate: function(parsedName) {
    var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/"));
    return this.findTemplate(pluginParsedName);
  },

  findMobileTemplate: function(parsedName) {
    if (Discourse.Mobile.mobileView) {
      var mobileParsedName = this.parseName(parsedName.fullName.replace("template:", "template:mobile/"));
      return this.findTemplate(mobileParsedName);
    }
  },

  findTemplate: function(parsedName) {
    return this._super(parsedName) || this.findSlashedTemplate(parsedName) || this.findAdminTemplate(parsedName);
  },

  // Try to find a template with slash instead of first underscore, e.g. foo_bar_baz => foo/bar_baz
  findSlashedTemplate: function(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    var slashed = decamelized.replace("_", "/");
    return Ember.TEMPLATES[slashed];
  },

  // Try to find a template within a special admin namespace, e.g. adminEmail => admin/templates/email
  // (similar to how discourse lays out templates)
  findAdminTemplate: function(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    if (decamelized.indexOf('admin') === 0) {
      decamelized = decamelized.replace(/^admin\_/, 'admin/templates/');
      decamelized = decamelized.replace(/^admin\./, 'admin/templates/');
      decamelized = decamelized.replace(/\./, '_');
      return Ember.TEMPLATES[decamelized];
    }
  }

});
<commit_msg>Support for defining components within plugins<commit_after>/* global requirejs, require */
/**
  A custom resolver to allow template names in the format we like.

  @class Resolver
  @extends Ember.DefaultResolver
  @namespace Discourse
  @module Discourse
**/

var classify = Ember.String.classify;
var get = Ember.get;

function parseName(fullName) {
    /*jshint validthis:true */

    var nameParts = fullName.split(":"),
        type = nameParts[0], fullNameWithoutType = nameParts[1],
        name = fullNameWithoutType,
        namespace = get(this, 'namespace'),
        root = namespace;

    return {
      fullName: fullName,
      type: type,
      fullNameWithoutType: fullNameWithoutType,
      name: name,
      root: root,
      resolveMethodName: "resolve" + classify(type)
    };
}

Discourse.Resolver = Ember.DefaultResolver.extend({

  parseName: parseName,

  normalize: function(fullName) {
    var split = fullName.split(':');
    if (split.length > 1) {
      var dashed = Ember.String.dasherize(split[1].replace(/\./g, '/')),
          moduleName = 'discourse/' + split[0] + 's/' + dashed;
      if (requirejs.entries[moduleName]) {
        return split[0] + ":" + dashed;
      }
    }
    return this._super(fullName);
  },

  customResolve: function(parsedName) {
    // If we end with the name we want, use it. This allows us to define components within plugins.
    var suffix = parsedName.type + 's/' + parsedName.fullNameWithoutType,
        moduleName = Ember.keys(requirejs.entries).find(function(e) {
          return e.indexOf(suffix, e.length - suffix.length) !== -1;
        });

    var module;
    if (moduleName) {
      module = require(moduleName, null, null, true /* force sync */);
      if (module && module['default']) { module = module['default']; }
    }
    return module;
  },

  resolveController: function(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  resolveComponent: function(parsedName) {
    return this.customResolve(parsedName) || this._super(parsedName);
  },

  /**
    Attaches a view and wires up the container properly

    @method resolveTemplate
    @param {String} parsedName the name of the template we want to resolve
    @returns {Template} the template (if found)
  **/
  resolveTemplate: function(parsedName) {
    return this.findPluginTemplate(parsedName) ||
           this.findMobileTemplate(parsedName) ||
           this.findTemplate(parsedName) ||
           Ember.TEMPLATES.not_found;
  },

  findPluginTemplate: function(parsedName) {
    var pluginParsedName = this.parseName(parsedName.fullName.replace("template:", "template:javascripts/"));
    return this.findTemplate(pluginParsedName);
  },

  findMobileTemplate: function(parsedName) {
    if (Discourse.Mobile.mobileView) {
      var mobileParsedName = this.parseName(parsedName.fullName.replace("template:", "template:mobile/"));
      return this.findTemplate(mobileParsedName);
    }
  },

  findTemplate: function(parsedName) {
    return this._super(parsedName) || this.findSlashedTemplate(parsedName) || this.findAdminTemplate(parsedName);
  },

  // Try to find a template with slash instead of first underscore, e.g. foo_bar_baz => foo/bar_baz
  findSlashedTemplate: function(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    var slashed = decamelized.replace("_", "/");
    return Ember.TEMPLATES[slashed];
  },

  // Try to find a template within a special admin namespace, e.g. adminEmail => admin/templates/email
  // (similar to how discourse lays out templates)
  findAdminTemplate: function(parsedName) {
    var decamelized = parsedName.fullNameWithoutType.decamelize();
    if (decamelized.indexOf('admin') === 0) {
      decamelized = decamelized.replace(/^admin\_/, 'admin/templates/');
      decamelized = decamelized.replace(/^admin\./, 'admin/templates/');
      decamelized = decamelized.replace(/\./, '_');
      return Ember.TEMPLATES[decamelized];
    }
  }

});
<|endoftext|>


<commit_before>function(doc, req){
        // Don't send the design document.
        if ( !doc || (doc.doc_type != "resource_data_distributable")){
            //print("Ignore document that is not resource_data_distributable: "+ doc);
            return false;
        }
        // If there is no query parameters return send the document.
        if (!req){
            //print("no req value");
            return true;
        }
        // Check to see the query parameter is valid  node filter description. if not
        // we can filter anything out so send it.
        if(("custom_filter" in req) && req.custom_filter == true){
            //print("No filtering needed custom filter is being used");
            return true;
        }
        // If there is no filter in the parameter just send the document.
        var filter_doc = req.query;
        if (!filter_doc){
            //print("No filter available...");
            return true;
        }
        // Variable to hold if the document is filter out on match.
        // If include_exclude  is T if the filters describe what documents to accept
        // all others are rejected F if the filters describe what documents to reject
        // all others are accepted optional, T if not present
        var include_doc =  (!("include_exclude" in filter_doc) ||filter_doc.include_exclude==true);
        //print("Include doc on match: "+include_doc);

        //Go through all the filters
        for(var i in filter_doc.filter){
            var filter_key = filter_doc.filter[i]["filter_key"];
            var filter_value = filter_doc.filter[i]["filter_value"];
            var matched_value = null;
            var filter_match = null;

            if (!filter_key || !filter_value){
                //print("Continuing the key/value loop... invalid filter_key: "+filter_key+" or filter_value: "+filter_value );
                continue;
            }
            //create a regular expression for the filter_key to check for matching against
            //the document key.
            var regex_key = new RegExp(filter_key);

            //Create regular expression for the key value
            var regex_value = new RegExp(filter_value);

            //print("Filter key:  "+filter_key+"\tFilter value: "+filter_value+"\t key regx: "+regex_key);
             //Look though the keys and for the variable that matches the filter key
            for (var key in doc){
                //print("key: "+key);
                if (!key.match(regex_key)){
                    continue;
                }
                matched_value = doc[key];
                //print("find a match: '"+matched_value+"'  for filter key:  "+filter_key);

                //Make we have a valid data for filter_value and matched value
                // otherwise keep looping.
                if (!matched_value){
                    //print("The matched_value is bad:  '"+matched_value +"'...keep going\n");
                    continue;
                }
                //Check if there is match
                filter_match = JSON.stringify(matched_value).match(regex_value);
                //print("The match between '"+regex_value+"' and '"+matched_value+" is: "+filter_match+"\n");
                //Exclude the document if there is a match
                if((include_doc ==false && filter_match) ||
                (include_doc == true && !filter_match )){
                    //print("There is no match rejecting document...");
                    return false;
                }
            }
        }
        //print("The document just match everything...\n");
        return true;
   }
<commit_msg>Fix logical error.<commit_after>function(doc, req){
        // Don't send the design document.
        if ( !doc || (doc.doc_type != "resource_data_distributable")){
            //print("Ignore document that is not resource_data_distributable: "+ doc);
            return false;
        }
        // If there is no query parameters return send the document.
        if (!req){
            //print("no req value");
            return true;
        }
        // Check to see the query parameter is valid  node filter description. if not
        // we can filter anything out so send it.
        if(("custom_filter" in req) && req.custom_filter == true){
            //print("No filtering needed custom filter is being used");
            return true;
        }
        // If there is no filter in the parameter just send the document.
        var filter_doc = req.query;
        if (!filter_doc){
            //print("No filter available...");
            return true;
        }
        // Variable to hold if the document is filter out on match.
        // If include_exclude  is T if the filters describe what documents to accept
        // all others are rejected F if the filters describe what documents to reject
        // all others are accepted optional, T if not present
        var include_doc =  (!("include_exclude" in filter_doc) ||filter_doc.include_exclude==true);
        //print("Include doc on match: "+include_doc);

        //Keep track the see if the document match all the filters.
         var match_all_filters = true;

        //Go through all the filters
        for(var i in filter_doc.filter){
            var filter_key = filter_doc.filter[i]["filter_key"];
            var filter_value = filter_doc.filter[i]["filter_value"];
            var matched_value = null;
            var filter_match = null;

            if (!filter_key || !filter_value){
                //print("Continuing the key/value loop... invalid filter_key: "+filter_key+" or filter_value: "+filter_value );
                continue;
            }
            //create a regular expression for the filter_key to check for matching against
            //the document key.
            var regex_key = new RegExp(filter_key);

            //Create regular expression for the key value
            var regex_value = new RegExp(filter_value);

            //print("Filter key:  "+filter_key+"\tFilter value: "+filter_value+"\t key regx: "+regex_key);
             //Look though the keys and for the variable that matches the filter key
            for (var key in doc){
                //print("key: "+key);
                if (!key.match(regex_key)){
                    continue;
                }
                matched_value = doc[key];
                //print("find a match: '"+matched_value+"'  for filter key:  "+filter_key);

                //Make we have a valid data for filter_value and matched value
                // otherwise keep looping.
                if (!matched_value){
                    //print("The matched_value is bad:  '"+matched_value +"'...keep going\n");
                    continue;
                }
                //Check if there is match
                filter_match = JSON.stringify(matched_value).match(regex_value);
                match_all_filters = match_all_filters && filter_match;

                //print("The match between '"+regex_value+"' and '"+matched_value+" is: "+filter_match+"\n");
                //Exclude the document if there is a match
                if((include_doc == true && !filter_match )){
                    //print("There is no match rejecting document...");
                    return false;
                }
            }
        }
        if( (include_doc == false) &&(match_all_filters == true))
        {
            //printf("rejecting document because it matches exclue filter...\n")
            return false;
        }
        //print("The document just match everything...\n");
        return true;
    }
<|endoftext|>