module.exports = function(app, configurations, express) { var nconf = require('nconf'); var i18n = require('i18next'); var maxAge = 24 * 60 * 60 * 1000 * 28; var nativeClients = require('./clients.json'); var RedisStore = require('connect-redis')(express); var passport = require('passport'); var csrf = express.csrf(); nconf.argv().env().file({ file: 'local.json' }); // Configuration var checkApiKey = function (req, res, next) { if (req.body.apiKey && nativeClients.indexOf(req.body.apiKey) > -1) { req.isApiUser = true; } next(); }; var clientBypassCSRF = function (req, res, next) { if (req.isApiUser) { next(); } else { csrf(req, res, next); } }; i18n.init({ lng: nconf.get('locale'), // undefined detects user browser settings supportedLngs: ['en', 'fr', 'es', 'ru'], fallbackLng: 'en', useCookie: false, resGetPath: 'locales/__lng__.json' }); i18n.registerAppHelper(app); app.configure(function () { app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.set('view options', { layout: false }); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); if (!process.env.NODE_ENV) { app.use(express.logger('dev')); } app.use(express.static(__dirname + '/public')); app.use(express.cookieParser()); app.use(express.session({ secret: nconf.get('session_secret'), store: new RedisStore({ db: nconf.get('redis_db'), prefix: 'meatspacechat' }), cookie: { maxAge: maxAge } })); app.use(passport.initialize()); app.use(passport.session()); app.use(checkApiKey); app.use(clientBypassCSRF); app.use(function (req, res, next) { res.locals.session = req.session; if (!req.body.apiKey) { res.locals.csrf = req.csrfToken(); } else { res.locals.csrf = false; } if (!process.env.NODE_ENV) { res.locals.debug = true; } else { res.locals.debug = false; } res.locals.analytics = nconf.get('analytics'); res.locals.appId = nconf.get('appId'); res.locals.analyticsHost = nconf.get('analyticsHost'); next(); }); app.use(i18n.handle); app.enable('trust proxy'); app.locals.pretty = true; app.use(function (req, res, next) { // prevent framing by other sites res.set('X-Frame-Options', 'SAMEORIGIN'); next(); }); app.use(app.router); app.use(function (req, res, next) { res.status(404); res.render('404', { url: req.url, layout: false }); return; }); app.use(function (req, res, next) { res.status(403); res.render('403', { url: req.url, layout: false }); return; }); }); app.configure('development, test', function() { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('prod', function() { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('500', { error: err, layout: false }); }); app.use(express.errorHandler()); }); return app; };
import i18n from 'i18next'; i18n.init({ fallbackLng: 'en', // allow keys to be phrases having `:`, `.` nsSeparator: false, keySeparator: false, interpolation: { escapeValue: false, // Not needed for react }, }); export default i18n;
var express = require('express'); var app = express(); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var load = require('express-load'); var passport = require('passport'); var i18next = require('i18next'); var methodoverride = require('method-override')(); var cookieParser = require('cookie-parser'); var flash = require('express-flash'); var session = require('express-session'); var server_port = process.env.OPENSHIFT_NODEJS_PORT || 3000; var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'; i18next.init(); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); app.use(express.static(__dirname + "/public")); app.use(cookieParser()); app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true })); app.use(i18next.handle); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());
, fs = require('fs') , hbs = require('hbs') , hbsHelpers = require(cwd + '/lib/hbs-helpers') , i18n = require('i18next') , path = require('path') , favicon = require('serve-favicon') , logger = require('morgan') , cookieParser = require('cookie-parser') , bodyParser = require('body-parser') , localVars = require(cwd + "/middleware/locals") ; i18n.init({ saveMissing: true, debug: process.env.NODE_ENV === 'development', lng: 'en-US', ignoreRoutes: ['images/', 'public/', 'css/', 'js/'] }); var staticRoutes = require('./routes/index'); var smsRoutes = require("./routes/api/sms"); var subscriberRoutes = require("./routes/api/subscribers"); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hbs'); hbsHelpers.register(hbs); i18n.registerAppHelper(app); hbs.registerPartials(__dirname + "/views/partials");
i18n.init({ resources: { fr: { [I18N_DOMAIN_COMPONENTS]: { LIST_TOOLBAR_DISPLAY: 'Affichage :', LIST_TOOLBAR_SORT_BY: 'Trier par :', LIST_TOOLBAR_PAGINATION_SHOW: 'Nombre :', LIST_SELECT_ALL: 'Sélectionner', LIST_SELECT_SORT_BY_ORDER_ASC: 'Croissant', LIST_SELECT_SORT_BY_ORDER_DESC: 'Décroissant', LIST_SELECT_DISPLAY_MODE_TABLE: 'Tableau', LIST_SELECT_DISPLAY_MODE_LARGE: 'Large', LIST_SELECT_DISPLAY_MODE_TILE: 'Tuile', LIST_FILTER_TOGGLE: 'Afficher le filtre', LIST_FILTER_REMOVE: 'Supprimer le filtre', LISTVIEW_NO_RESULT: 'Aucun résultat.', LISTVIEW_EMPTY: 'Cette liste est vide.', LISTVIEW_HEADER_TITLE: 'Valeurs', LISTVIEW_HEADER_SELECTED: '{{count}}/{{total}} élément sélectionné', LISTVIEW_HEADER_SELECTED_plural: '{{count}}/{{total}} éléments sélectionnés', LISTVIEW_HEADERINPUT_SEARCH_PLACEHOLDER: 'Rechercher…', LISTVIEW_ITEMS_TOGGLE_ALL: 'Tout', ENUMERATION_EMPTY_LIST: 'La liste est vide', ENUMERATION_HEADER_LABEL: 'Valeurs', SIDEPANEL_EXPAND: 'Développer', SIDEPANEL_COLLAPSE: 'Réduire', VIRTUALIZEDLIST_NO_RESULT: 'Aucun résultat', }, }, it: { [I18N_DOMAIN_COMPONENTS]: { LIST_TOOLBAR_DISPLAY: 'Affissione :', LIST_TOOLBAR_SORT_BY: 'Ordina per :', LIST_TOOLBAR_PAGINATION_SHOW: 'Mostrare :', LIST_SELECT_ALL: 'Seleziona tutto', LIST_SELECT_SORT_BY_ORDER_ASC: 'Ascendente', LIST_SELECT_SORT_BY_ORDER_DESC: 'Discendente', LIST_SELECT_DISPLAY_MODE_TABLE: 'Tabella', LIST_SELECT_DISPLAY_MODE_LARGE: 'Grande', LIST_SELECT_DISPLAY_MODE_TILE: 'Piastrella', LIST_FILTER_TOGGLE: 'Ginocchiera filtro', LIST_FILTER_REMOVE: 'Rimuova il filtro', LISTVIEW_NO_RESULT: 'Nessun risultato.', LISTVIEW_EMPTY: 'Questa lista è vuota.', LISTVIEW_HEADER_TITLE: 'Valori', LISTVIEW_HEADER_SELECTED: '{{count}}/{{total}} articolo selezionato', LISTVIEW_HEADER_SELECTED_plural: '{{count}}/{{total}} articoli selezionati', LISTVIEW_HEADERINPUT_SEARCH_PLACEHOLDER: 'Ricercare…', LISTVIEW_ITEMS_TOGGLE_ALL: 'Tutto', ENUMERATION_EMPTY_LIST: "L'elenco è vuoto", ENUMERATION_HEADER_LABEL: 'Valori', SIDEPANEL_EXPAND: 'Espandere', SIDEPANEL_COLLAPSE: 'Collassare', VIRTUALIZEDLIST_NO_RESULT: 'Nessun risultato', }, }, }, debug: false, wait: true, // globally set to wait for loaded translations in translate hoc });
/** * Module dependencies. */ var express = require('express'); var flash = require('connect-flash'); var helpers = require('view-helpers'); var config = require('./config'); var i18n = require('i18next'); var form = require( 'express-form2' ); var field = form.field; i18n.init({ saveMissing: true, debug: true, ignoreRoutes: ['public/'] }); module.exports = function(app, passport) { console.log('Initializing Express'); app.set('showStackError', true); //Prettify HTML app.locals.pretty = true; //Should be placed before express.static app.use(express.compress({ filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, level: 9 }));
var express = require('express') , app = express() , fs = require('fs') , url = require('url') , i18n = require('i18next'); // use filesys i18n.init({ ns: { namespaces: ['ns.common', 'ns.app', 'ns.layout', 'ns.msg', 'ns.public', 'ns.special'], defaultNs: 'ns.common'}, preload: ['en', 'zh', 'de', 'fr', 'it', 'dev'], resSetPath: 'locales/__lng__/new.__ns__.json', saveMissing: true, debug: true }); // Configuration app.configure(function() { app.use(express.bodyParser()); app.use(i18n.handle); // have i18n befor app.router app.use(app.router); // app.set('view engine', 'jade'); // app.set('views', __dirname); app.use('/app', express.static('client/app')); app.use('/assets', express.static('client/assets')); app.use('/app/templates', express.static('client/assets/templates')); // for release app.use('/release', express.static('client/dist/release/assets'));
hbs = require('hbs'), moment = require('moment'), router = require(__dirname + '/routes').router, app = express(), error = require(__dirname + '/middleware/error'); //i18n i18n.init({ lng : 'pt-BR' , languages : ['pt-BR', 'en'] , cookieName : 'lang' , useCookie : true , fallbackLng : 'pt-BR' , fallbackOnNull : false , fallbackOnEmpty : false , load : 'current' , debug : true , resGetPath : 'locales/__lng__/__ns__.json' , resSetPath : 'locales/__lng__/__ns__.json' , saveMissing : true , resStore : false , returnObjectTrees : false , getAsync : true , dynamicLoad : true }); app.use(i18n.handle); i18n.registerAppHelper(app); hbs.registerHelper('t', function(i18n_key) { var result = i18n.t(i18n_key); return new hbs.SafeString(result);
var FacebookStrategy = require('passport-facebook').Strategy; var LocalStrategy = require('passport-local').Strategy; var TwitterStrategy = require('passport-twitter').Strategy; var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var sessions = require('./sessions'); var xapi = require('./xapi'); //localization var i18n = require("i18next"); var option = { lng: 'is', resGetPath: (libpath.resolve("./locales/__lng__/__ns__.json")) //debug: true }; i18n.init(option); console.log("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); console.log('Welcome to Sandbox.\nType "create application" to create your first app.'); console.log('Type "help" for a list of commands.\n'); var errorlog = null; global.error = function() { var red, brown, reset; red = '\u001b[31m'; brown = '\u001b[33m'; reset = '\u001b[0m'; var args = Array.prototype.slice.call(arguments); if (errorlog) errorlog.write(args[0] + '\n');
var i18n = require('i18next'), app = require('./app_config'); // multilamguage modal initialization i18n.init({ ns: { namespaces: ['ns.common', 'ns.special'], defaultNs: 'ns.special'}, resSetPath: 'locales/__lng__/new.__ns__.json', saveMissing: true, debug: true, sendMissingTo: 'fallback', preload: ['en-US', 'ru-RU'] }); i18n.registerAppHelper(app) .serveClientScript(app) .serveDynamicResources(app) .serveMissingKeyRoute(app); i18n.serveWebTranslate(app, { i18nextWTOptions: { languages: ['en-US', 'ru-RU', 'dev'], namespaces: ['ns.common', 'ns.special'], resGetPath: "locales/resources.json?lng=__lng__&ns=__ns__", resChangePath: 'locales/change/__lng__/__ns__', resRemovePath: 'locales/remove/__lng__/__ns__', fallbackLng: "dev", dynamicLoad: true, } });
var express = require('express'); var i18next = require('i18next'); var path = require('path'); var config = require('./config'); var db = require('./db'); var app = express(); i18next.init({ fallbackLng: config.i18n.defaultLanguage, resGetPath: path.join(__dirname, 'locales/__lng__.json') }); i18next.registerAppHelper(app); app.use(i18next.handle); app.use(express.static(path.join(__dirname, 'static'))); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser()); app.use(app.router); app.use(express.errorHandler());
if (!defaultPort) { portvalue = !isNaN(process.argv[2])?(process.argv[2]-0):process.env.JASMINE_PORT; } var isOpenShift = function() { return process.env.OPENSHIFT_NODEJS_PORT || process.env.OPENSHIFT_INTERNAL_PORT; }; var port = process.env.OPENSHIFT_NODEJS_PORT || process.env.OPENSHIFT_INTERNAL_PORT || portvalue; var sport = process.env.LOOWID_HTTPS_PORT || 443; var sserver; i18n.init({ saveMissing : true, debug : false, fallbackLng : 'en', supportedLngs : [ 'en', 'es', 'ca', 'de','ru','hu' ], resGetPath : 'public/i18n/bundle/__ns_____lng__.json', ns : 'resourceBundle' }); var app = express(); var http = require('http'); var server = http.createServer(app); var rooms = require('./app/controllers/rooms'); var wsevents = require('./app/controllers/events'); var logs = require('./app/controllers/log'); var stats = require('./app/controllers/stats'); if (!isOpenShift() && defaultPort) { try { var fs = require('fs');
define(function(require, exports, module) { // validate里的提醒,需要i18n,confirm,alert里需要i18n; require('ie-shim').init(); var $ = require('jquery'); require("bootstrap"); require('validate'); require('cookie'); require('jqueryui'); var Handlebars = require('Handlebars'); require('./console_com'); var errors = require("./msmErrors"); var helper = require('./helper'); var utils = require('./utils'); require('../libs/jquery/placeholder'); // var buyModal = require('./tpl-buy-modal.js'); if (!window.i18n) { var i18nx = require("i18next"); i18nx.init({ lng: $.cookie("i18next") || "zh-CN", fallbackLng: false, load: 'current' }, function(t) { LoadContent(); }); window.i18n = i18nx; } else { LoadContent(); } function LoadContent() { var lang = $.cookie('i18next'); if (lang) { if ($("#langSelect")[0]) { $("#langSelect").find('option:selected')[0].selected = false; $("#langSelect").find('option[value="' + lang + '"]')[0].selected = true; } } //切换语言 $("#langSelect").on("change", function() { i18n.setLng($(this).val()); location.reload(); }); // 个人信息 $.ajax({ url: '/api/user/setting', type: 'GET', dataType: 'json', cache: false }).done(function(data) { if (data.status == 1) { var phone = data.result.phone || ''; if (data.result.icon1) { $('#my_photo_icon').attr('src', data.result.icon1); $.cookie('userIcon', data.result.icon1, { expires: 7 }); } else { $('#my_photo_icon').attr('src', '/img/favicon-30.png'); $.cookie('nickname', data.result.userName, { expires: 7 }); } if (phone) { /*force add phone*/ $('.main-applist-out #createApp').attr('data-phone', phone); } var email = $.cookie('username') || ''; if (data.result.userName) { $('#userName span').eq(0).html(data.result.userName); if ($.cookie('remMe')) { $.cookie('nickname', data.result.userName, { expires: 7 }); } else { $.cookie('nickname', data.result.userName, { expires: 1 }); } } else { $('#userName span').eq(0).html(email); $.removeCookie('nickname', { expires: 1 }); } if (!data.result.state && $.cookie("VerfyEmail") != $.cookie('username')) { var $str = $('<div id="errTopMiddle" class="err-top fail">' + // ' <i class="err-close">'+ // ' <i class="icon-remove"></i>'+ // ' </i>'+ ' <div class="err-out">' + ' <div class="err-switch">' + ' <i class="err-switch-i icon-smile"></i>' + ' <i class="err-switch-i icon-frown"></i>' + ' <span class="err-content">' + i18n.t('appInfo.unActive') + '</span>' + ' </div>' + ' </div>' + '</div>'); $str.appendTo($("body")); $str.slideDown(); $str.find(".icon-remove").on("click", function() { $(this).slideUp(400, function() { $str.remove(); $.cookie("VerfyEmail", $.cookie('username'), { expires: 7 }); }); }); } } else { // console.log(data); } }).always(function() {}); $('.main-applist-out').on('click', '.tpl-accredit', function() { var taobao = $(this).attr('data-url'); var parent = $(this).parents('.dd-right'); var name = parent.find('h5').text(); var info = parent.find('h5').attr('data-info'); $('#tpl-app-name').val(name).trigger('input'); $('#tpl-intro').val(info).trigger('input'); $('.buy-at-once').attr('href', taobao); buyModal.createApp(); }); $('.main-applist-out').on('click', '.tpl-dele', function() { var id = $(this).parents('dd').attr('temid'); var parent = $(this).parents('dd.clearfix'); $.ajax({ url: '/deleteNotPayTem', type: 'POSt', dataType: 'json', data: { id: id }, success: function(data) { if (data.status) { parent.remove(); utils.alertMessage(1, data.msg); } else if (data.code) { alert(i18n.t("tplStore.err_" + data.code)); } else { alert(data.msg); }; }, error: function(data) { } }); }); $('.main-applist-out').on('click', 'dd.app', function(event) { var $this = $(this); var appId = $this.attr('appid'); var appname = $this.find('h5').html(); $.cookie('curAppId', appId, { expires: 7 }); $.cookie('curAppName', appname, { expires: 7 }); window.location.href = '/appoverview'; }); $('.loading-more').on('click', function(event) { $('.main-applist-out').addClass('all'); event.preventDefault(); }); //退出登录 $('#sign_out').one('click', function() { $.removeCookie('curAppId'); $.removeCookie('curAppName'); $.removeCookie('username'); $.removeCookie('nickname'); $.removeCookie('ul_token'); //BBS login $.ajax({ url: '/api/user/signout', type: 'GET', cache: false, async: false }).done(function() { var bbsFrm = $('#bbsLogin')[0].contentWindow.document.getElementById('bbsFrm3'); bbsFrm.submit(); setTimeout(function() { location.href = '/signin'; }, 2000); }); return false; }); //load page exec script var pathname = location.pathname; var fun = pathname.slice(1); fun = fun || 'appoverview'; var jname = getJsName(); if (jname) { fun = jname; } //require.async("{ENV}/" + fun, function (module) { // setTimeout(function () { // module.init(); // }, 400); // }); helper.init(); } // exports.init = function(){ // }; });
require('./app/models/file'); require('./app/models/client'); require('./app/models/authorization_code'); require('./app/models/access_token'); /* SETUP OAUTH2 SERVER */ oauth2server = require('./app/services/oauth2/oauth2'); /* SETUP PASSPORT */ passport = require('./config/passport'); /* SETUP I18N */ i18next.init({ ns: { namespaces: ['common'], defaultNs: 'common' }, resGetPath: 'app/locales/__lng__/__ns__.json', lowerCaseLng: true }); app.use(i18next.handle); i18next.registerAppHelper(app); /* SETUP EXPRESS SERVER */ if( config.env !== 'production' ) { app.use(morgan('dev')); // Log every request to the console } app.use(express.static('./public')); app.set('views', './app/views'); app.set('view engine', 'jade');
grunt.registerTask('makeBundles','Package all the various frontend files into modules',function(){ // Setup our tasks var tasks = [ 'clean:modules', 'copy:templates', 'jade', 'copy:locales', 'i18n:dist', 'dust:dist', 'concat:modules', 'concat:templates', 'concat:dist', 'uglify:modules', 'concatModules', 'sass:dist', 'copy:app', 'clean:dist', 'uglify:dist', 'cssmin', 'copy:final', //'clean:final' ]; // Our grunt build directory var writeDir = '.grunt/.build'; // Where all the JS files live for the Backbone application var dir = 'public/js/app'; // Get all of our module names var modules = fs.readdirSync(dir); grunt.log.writeln(modules.length + ' modules to compile'); // Get the Copy config var copyConfig = grunt.config('copy'); // Get the Concat config var concatConfig = grunt.config('concat'); // Get the Uglify config var uglifyConfig = grunt.config('uglify'); // Get the JADE config var jadeConfig = grunt.config('jade'); // Get the Dust config var dustConfig = grunt.config('dust'); // Get all our locales var locales = fs.readdirSync('locales'); grunt.log.writeln(locales.length + ' locales to compile'); copyConfig.templates.files.push( {expand:true,cwd:'app/views/includes',src:'*.*',dest:'.grunt/.templates/includes'}, {expand:true,cwd:'app/views/snippets',src:'*.*',dest:'.grunt/.templates/snippets'} ); // Iterate over the modules modules.forEach(function(moduleName){ var filesPath = dir + '/' + moduleName; var moduleFile = writeDir + '/' + moduleName + '.js'; var filePaths = []; // Get the files in our module var files = fs.readdirSync(filesPath); files.forEach(function(file){ var filePath = filesPath + '/' + file; // Find all the templates used in the views if(file.indexOf('view') !== -1){ var templates = fs.readFileSync(filePath,'utf8').match(/tpl_\w+/g); var templateConfig = { expand:true, flatten:true, src:[], dest:'.grunt/.templates/' + moduleName }; // Append the templates we need to copy templates.forEach(function(template){ templateConfig.src.push('app/views/templates/' + template + '.jade'); // Set up the templates to compile to HTML jadeConfig.dist.files['.grunt/.templates/' + moduleName + '/' + template + '.html'] = '.grunt/.templates/' + moduleName + '/' + template + '.jade'; }); // Append the copy config for the templates copyConfig.templates.files.push(templateConfig); // Set up the Dust compiles for the localized HTML files that will get generated dustConfig.dist.files.push({ expand: true, cwd: '.grunt/.localized/', src: ['**/' + moduleName + '/*.html'], dest: '.grunt/.localized', ext: '.js' }); } // Get each file we need to concat filePaths.push(filePath); locales.forEach(function(locale){ // Concat the templates together concatConfig.templates.files['.grunt/.localized/' + locale + '/' + moduleName + '.js'] = ['.grunt/.localized/' + locale + '/' + moduleName + '/*.js']; }); }); // Create the concat step for grunt for the module concatConfig.modules.files[moduleFile] = filePaths; locales.forEach(function(locale){ // Concat the templates and modules together concatConfig.dist.files['.grunt/.modules/' + locale + '/' + moduleName + '.js'] = ['.grunt/.localized/' + locale + '/' + moduleName + '.js','.grunt/.build/' + moduleName + '.js']; }); }); // Build the localized base files for the games and pages i18n.init({ resGetPath: '../../locales/__lng__/__ns__.json', fallbackLng: 'en-US', ns: 'server', saveMissing: false, debug: false }); var languages = fs.readdirSync('locales'); languages.forEach(function(language){ i18n.setLng(language); var locale = language.substr(0,2); (function(Helpers){ var games = JSON.parse(fs.readFileSync('public/json/' + locale + '-games-full.json','utf8')); Helpers.games = games; Helpers.gamesJSON = JSON.stringify({games:games}); var files = {}; files['.dist/' + language + '/index.html'] = 'app/views/index.jade'; files['.dist/' + language + '/library.html'] = 'app/views/library.jade'; games.forEach(function(game){ Helpers.gamesByShort[game.short] = game; var gameFile = {}; gameFile['.dist/' + language + '/' + game.short + '.html'] = 'app/views/detail.jade'; var data = Helpers.getFiles({locale:locale,rel:'',fileExt:'.html',params:{game:game.short}}); data.t = i18n.t; jadeConfig['html-' + language + '-' + game.short] = { options: { data: data }, files: gameFile }; }); var data = Helpers.getFiles({locale:locale,rel:'',fileExt:'.html',params:{}}); data.t = i18n.t; jadeConfig['html-' + language] = { options: { data: data }, files: files }; }(Helpers)); copyConfig.final.files.push({expand: true, cwd: 'public/js/dist/', src: '*.js', dest: '.dist/' + language + '/js'}); copyConfig.final.files.push({expand: true, cwd: 'public/js/dist/' + language, src: '*.js', dest: '.dist/' + language + '/js'}); copyConfig.final.files.push({expand: true, cwd: 'public/js/dist/libraries/', src: '*.js', dest: '.dist/' + language + '/js/libraries'}); copyConfig.final.files.push({expand: true, cwd: 'public/js/dist/libraries/bower/', src: '*.js', dest: '.dist/' + language + '/js/libraries/bower'}); copyConfig.final.files.push({expand: true, cwd: 'public/css', src: '**/*.*', dest: '.dist/' + language + '/css'}); copyConfig.final.files.push({expand: true, cwd: 'public/fonts', src: '*.*', dest: '.dist/' + language + '/fonts'}); copyConfig.final.files.push({expand: true, cwd: 'public/img', src: '*.*', dest: '.dist/' + language + '/img'}); copyConfig.final.files.push({expand: true, cwd: 'public/', src: 'favicon.ico', dest: '.dist/' + language}); }); // Set our new configs grunt.config('concat',concatConfig); grunt.config('uglify',uglifyConfig); grunt.config('copy',copyConfig); grunt.config('jade',jadeConfig); grunt.config('dust',dustConfig); // Run it! grunt.task.run(tasks); });
import i18n from 'i18next' i18n.init({ defaultNS: 'common', fallbackLng: 'en', interpolation: { escapeValue: false }, lng: 'en', ns: ['common'], resources: { en: { common: { test_string: 'This is a test string from i18next.' } } } }) export default i18n
} var conf = require('nconf'); var beans = conf.get('beans'); // initialize winston and two concrete loggers var winston = require('winston-config').fromFileSync(path.join(__dirname, 'config/winston-config.json')); var appLogger = winston.loggers.get('application'); var httpLogger = winston.loggers.get('http'); // initialize i18n i18n.init({ ignoreRoutes: ['clientscripts/', 'fonts/', 'images/', 'img/', 'stylesheets/'], supportedLngs: ['de', 'en'], preload: ['de', 'en'], fallbackLng: 'de', resGetPath: 'locales/__ns__-__lng__.json' }); // stream the log messages of express to winston, remove line breaks on message var winstonStream = { write: function (message) { httpLogger.info(message.replace(/(\r\n|\n|\r)/gm, '')); } }; module.exports = { create: function () { var app = express(); app.set('view engine', 'jade');
initialize: function (cb) { var initOptions = {}; // Only include options that are explicitly set. if (i18next in sails.config) { if (config in sails.config.i18next) { if (cookieDomain in sails.config.i18next.config) { initOptions.cookieDomain = sails.config.i18next.config.cookieDomain; } if (cookieName in sails.config.i18next.config) { initOptions.cookieName = sails.config.i18next.config.cookieName; } if (dynamicLoad in sails.config.i18next.config) { initOptions.dynamicLoad = sails.config.i18next.config.dynamicLoad; } if (fallbackLng in sails.config.i18next.config) { initOptions.fallbackLng = sails.config.i18next.config.fallbackLng; } if (lng in sails.config.i18next.config) { initOptions.lng = sails.config.i18next.config.lng; } if (load in sails.config.i18next.config) { initOptions.load = sails.config.i18next.config.load; } if (ns in sails.config.i18next.config) { initOptions.ns = sails.config.i18next.config.ns; } if (saveMissing in sails.config.i18next.config) { initOptions.saveMissing = sails.config.i18next.config.saveMissing; } if (useCookie in sails.config.i18next.config) { initOptions.useCookie = sails.config.i18next.config.useCookie; } } if (debug in sails.config.i18next) { initOptions.debug = sails.config.i18next.debug; } if (detectLngFromHeaders in sails.config.i18next) { initOptions.detectLngFromHeaders = sails.config.i18next.detectLngFromHeaders; } if (detectLngFromPath in sails.config.i18next) { initOptions.detectLngFromPath = sails.config.i18next.detectLngFromPath; } if (detectLngQS in sails.config.i18next.config) { initOptions.detectLngQS = sails.config.i18next.config.detectLngQS; } if (resGetPath in sails.config.i18next) { // Assume the absolute path is compiled from the application path // and the path specified in the settings for the server side. // Note: This path is typically derived from the resGetPath // specified for the client, since that path is relative to the // home URL for the application. // To Do: Check for existence of the file at the specified path, // falling back to a relative path if needed. initOptions.resGetPath = sails.config.appPath + sails.config.i18next.resGetPath; } if (resSetPath in sails.config.i18next) { // Assume the absolute path is compiled from the application path // and the path specified in the settings for the server side. // To Do: Check for existence of the file as specified, falling back // to a relative path if needed. initOptions.resSetPath = sails.config.appPath + sails.config.i18next.resSetPath; } if (supportedLngs in sails.config.i18next) { initOptions.supportedLngs = sails.config.i18next.supportedLngs; } } i18next.init(initOptions); return cb(); }
app.set( 'authentication cookie name', '__enketo' ); // views app.set( 'views', path.resolve( __dirname, '../app/views' ) ); app.set( 'view engine', 'jade' ); // pretty json API responses app.set( 'json spaces', 4 ); // setup i18next i18n.init( { // don't bother with these routes ignoreRoutes: [ 'css/', 'fonts/', 'images/', 'js/', 'lib/' ], // only attemp to translate the supported languages supportedLngs: app.get( 'languages supported' ), // allow query string lang override detectLngQS: 'lang', // fallback language fallbackLng: 'en', // don't use cookies, always detect useCookie: false } ); // make i18n apphelper available in jade templates i18n.registerAppHelper( app ); // middleware app.use( compression() ); app.use( bodyParser.json() ); app.use( bodyParser.urlencoded( { extended: true } ) ); app.use( cookieParser( app.get( 'encryption key' ) ) );
define(function(require,exports,module){ /* # Expression Helpers Helper methods and defined functions for expressions */ var _ = require('underscore'); var lookbehind = require('lookbehind'); var XRegExp = require('xregexp'); var i18n = require('i18next'); i18n.init(); lookbehind(XRegExp); var intializeExpressionHelpers = module.exports = function(data){ exh.es_data = data; return exh; } var exh = { handleError: function(e){ console.log(e); return e; }, callFunction: function(function_name, args){ var fn = function_name.toLowerCase(); var args = args; if(exh.userFunctions[fn]){ if(_.isArray(args)){ var args = args.reverse(); } return exh.userFunctions[fn].method.call(exh,args); } else { return "ERR: No such function." } }, parseCellValue: function(cell_id){ var COL = 0; var ROW = 1; var sheet_id = exh.es_data.users.getCurrentUser().getCurrentSheetId(); var sheet = exh.es_data.sheets.get(sheet_id); var cell_id = cell_id.match(/[a-zA-Z]+|[0-9]+/g); var row_id = sheet.rowAt(cell_id[ROW] * 1 - 1); var col_id = sheet.colAt(sheet.identifierToIndex(cell_id[COL])); var cell = sheet.getCell(row_id,col_id); return sheet.getRawValue(cell); }, parseCellRange: function(cell_range){ var COL = 0; var ROW = 1; var sheet_id = exh.es_data.users.getCurrentUser().getCurrentSheetId(); var sheet = exh.es_data.sheets.get(sheet_id); var coords = cell_range.split(":"); var topLeftCID = this.xlRefToEsRef(coords[0]); var bottomRightCID = this.xlRefToEsRef(coords[1]); var tl_cell_id = topLeftCID.match(/[a-zA-Z]+|[0-9]+/g); var tl_row_idx = tl_cell_id[ROW] * 1 - 1; var tl_col_idx = sheet.identifierToIndex(tl_cell_id[COL]); var br_cell_id = bottomRightCID.match(/[a-zA-Z]+|[0-9]+/g); var br_row_idx = br_cell_id[ROW] * 1 - 1; var br_col_idx = sheet.identifierToIndex(br_cell_id[COL]); var cell_values = []; for(var i = tl_row_idx; i <= br_row_idx; i++){ for(var j = tl_col_idx; j <= br_col_idx; j++){ cell_values.push(sheet.getRawValue(sheet.getCell(sheet.rowAt(i),sheet.colAt(j)))); } } return cell_values; }, //Convert an ethersheet style cell reference to an excel style reference xlRefToEsRef: function(formula){ var self = exh; var sig = /cellReference\(([-_a-zA-Z0-9_," ]+)\)/g; var f = formula.replace(sig,function(str,args){ args = args.split(', '); sheet_id = args[0].slice(1,-1); row_id = args[1].slice(1,-1); col_id = args[2].slice(1,-1); var sheet = exh.es_data.sheets.get(sheet_id); row_idx = sheet.rows.indexOf(row_id) + 1; col_idx = sheet.cols.indexOf(col_id) + 1; return self.excelColumnFromNumber(col_idx) + row_idx; }); return f; }, excelColumnFromNumber: function(columnNumber) { var columnString = ""; while (columnNumber > 0) { var currentLetterNumber = (columnNumber - 1) % 26; var currentLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(currentLetterNumber); columnString = currentLetter + columnString; columnNumber = (columnNumber - (currentLetterNumber + 1)) / 26; } return columnString; }, preprocessFormula: function(formula,id){ var sheet = exh.es_data.sheets.get(id); // ([^"'0-9_$-])([a-zA-Z]+[\d]+)(?!["'a-zA-Z_-]) var cell_reference = /([a-zA-Z]+[\d]+)(?!["'a-zA-Z_-]+)/g; var lookbehind = '(?<!["a-zA-Z0-9_$-]+)'; //translate excel style cell references like A1 into ethersheet formula var f = XRegExp.replaceLb(formula, lookbehind, cell_reference, function(str,pre,cell_id,post){ COL = 0; ROW = 1; var cell_id = str.match(/[a-zA-Z]+|[0-9]+/g); var row_id = sheet.rowAt(cell_id[ROW] * 1 - 1); var col_id = sheet.colAt(sheet.identifierToIndex(cell_id[COL])); return 'cellReference("' + sheet.id + '", "' + row_id + '", "' + col_id + '")'; }); return f; }, loopThroughNums: function(initializer, args, cb){ var total = initializer; if(!_.isArray(args)){return args * 1;} for(var i = 0; i < args.length; i++) { if(_.isNaN(args[i] * 1)){ continue; } else { total = cb(total, args[i]); } } return total; }, userFunctions: { /********************************************** * Make sure you make any function names all * lower case alpha numeric, no _ or caps!!! * ********************************************/ cellreference: { method: function(args){ var sheet_id = args[0]; var row_id = args[1]; var col_id = args[2]; var sheet = exh.es_data.sheets.get(sheet_id); var cell = sheet.getCell(row_id, col_id); var value = sheet.getRawValue(cell); return value; }, }, sum: { method: function(addatives){ var total = this.loopThroughNums(0,addatives,function(memo,item){ memo += item * 1; return memo; }); return total; }, def: i18n.t("sum_def"), desc: i18n.t("sum_desc"), }, product: { method: function(args){ if(_.contains(args,0)){return 0}; var total = this.loopThroughNums(1,args,function(memo,item){ memo = memo * item; return memo; }); return total; }, def: i18n.t("product_def"), desc: i18n.t("product_desc"), }, avg: { method: function(args){ var avg = this.loopThroughNums(0,args,function(memo,item){ memo += item * 1; return memo; }); avg = avg / args.length; return avg; }, def: i18n.t("avg_def"), desc: i18n.t("avg_desc"), }, abs: { method: function(num){ return Math.abs(num); }, def: i18n.t("abs_def"), desc: i18n.t("abs_desc"), }, acos: { method: function(num){ return Math.acos(num); }, def: i18n.t("acos_def"), desc: i18n.t("acos_desc"), }, asin: { method: function(num){ return Math.asin(num); }, def: i18n.t("asin_def"), desc: i18n.t("asin_desc"), }, atan: { method: function(num){ return Math.atan(num); }, def: i18n.t("atan_def"), desc: i18n.t("atan_desc"), }, atan2: { method: function(num){ var y = num[0]; var x = num[1]; return Math.atan2(y, x); }, def: i18n.t("atan2_def"), desc: i18n.t("atan2_desc"), }, ceil: { method: function(num){ return Math.ceil(num); }, def: i18n.t("ceil_def"), desc: i18n.t("ceil_desc"), }, cos: { method: function(num){ return Math.cos(num); }, def: i18n.t("cos_def"), desc: i18n.t("cos_desc"), }, exp: { method: function(num){ return Math.exp(num); }, def: i18n.t("exp_def"), desc: i18n.t("exp_desc"), }, floor: { method: function(num){ return Math.floor(num); }, def: i18n.t("floor_def"), desc: i18n.t("floor_desc"), }, log: { method: function(num){ return Math.log(num); }, def: i18n.t("log_def"), desc: i18n.t("log_desc"), }, pow: { method: function(num){ var base = num[0]; var exp = num[1]; return Math.pow(base,exp); }, def: i18n.t("pow_def"), desc: i18n.t("pow_desc"), }, rand: { method: function(){ return Math.random(); }, }, random: { method: function(){ return rand(); }, def: i18n.t("rand_def"), desc: i18n.t("rand_desc"), }, sin: { method: function(num){ return Math.sin(num); }, def: i18n.t("sin_def"), desc: i18n.t("sin_desc"), }, sqrt: { method: function(num){ return Math.sqrt(num); }, def: i18n.t("sqrt_def"), desc: i18n.t("sqrt_desc"), }, tan: { method: function(num){ return Math.tan(num); }, def: i18n.t("tan_def"), desc: i18n.t("tan_desc"), }, } }; });
//Populates req.session app.use(session()); /** * Configuration de i18next (traduction multilanguage) */ i18n.init({ lng : 'fr-FR' , languages : ['fr-FR', 'fr', 'en_US', 'en', 'es_ES', 'es'] , cookieName : 'lang' , useCookie : true , fallbackLng : false , fallbackOnNull : false , fallbackOnEmpty : false , load : 'current' , debug : false , resGetPath : './logicEasySecure/locales/__lng__.json' , resSetPath : './logicEasySecure/locales/__lng__.json' , saveMissing : true , resStore : false , returnObjectTrees : false , getAsync : true , dynamicLoad : true }); i18n.registerAppHelper(app); app.use(bodyParser()); app.use(i18n.handle); //all environments
level: 'trace', stream: new PrettyStream() } ] }); // Configure i18next to handle translations of a few common errors. See http://i18next.com/ i18next.init({ lng: "en-US", nsSeparator: false, resources: { en: { translation: { "server" : { "400" : { "notfound": "The page {{- page}} could not be found", //There is a '-' before page because the value is unescaped. See http://i18next.com/translate/interpolation/ "forbidden": "The page is forbidden", "unauthorized": "You are not authorized to access this page" } } } } } }); // Create a new express application instance. let app = express(); // Create a new remie instance and configure it. let remie = new Remie({ // Exclude a stack trace in errors.
fs = require('fs'), i18next = require('i18next'), Db = require('mongodb').Db, mongoStore = require('connect-mongodb'), session_store, port = process.env.PORT || 3000, schedule = require('node-schedule'); Db.connect("mongodb://*****:*****@ds029257.mongolab.com:29257/nomination-sessions", function(err, db) { session_store = new mongoStore({db: db}); }); var app = module.exports = express.createServer(); i18next.init({ ns: { namespaces: ['translation'], defaultNs: 'translation'} }); // Configuration app.configure('development', function() { log.level = Log.DEBUG; log.stream = fs.createWriteStream('logs/dev.log', { flags: 'w' }); port = 80; //cambiar a puerto deseado app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); });
express = require('express'), compress = require('compression'), passport = require('passport'), session = require('express-session'), bodyParser = require('body-parser'), i18n = require('i18next'), path = require('path'); var log = new (require('./libs/log'))(config.log), database = new (require('./libs/database/'))(config, log), oauth2 = new (require('./libs/oauth2/'))(config, log), responseHandler = new (require('seedio-response'))(config, log), MongoStore = require('connect-mongo')(session); // Initialize internationalization options. i18n.init(config.i18n); // Create an express application object. var app = module.exports = express(); // If the cookie is secure and proxy is enabled. We need to enable express' trust proxy for it set cookies correctly. if(config.session.cookie.secure && config.session.proxy) { app.enable('trust proxy'); } // Disable the "X-Powered-By: Express" HTTP header, which is enabled by default. app.disable("x-powered-by"); // Log all incoming requests, if enabled in config. if(config.server.requests) { app.use(log.requestLogger());
var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var bcrypt = require('bcrypt'); var i18n = require('i18next'); var requirejsMiddleware = require('requirejs-middleware'); var models = require('./models'); var requirejs = require('requirejs'); var routes = require('./routes/index'); var users = require('./routes/users'); i18n.init({ saveMissing: true }); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({
// contact email var email = require('./routes/sendEmail'); // youthcouncil 2016 routes var youthcouncils2016 = require('./routes/youthcouncil2016'); // youthcouncil 2015 routes var youthcouncils2015 = require('./routes/youthcouncil2015'); // youthcouncil 2013 routes var youthcouncils2013 = require('./routes/youthcouncil2013'); var app = express(); // initialization of the language framework i18n.init({ saveMissing: true, lng: 'en-US', debug: true, fallbackLng: 'en-US' }); function compile(str, path) { return stylus(str) .set('translation', path) .use(nib()) } // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');
i18n.init({ lng: "en-US", fallbackLng: 'en-US' }, function(t) { // Load your project's Models keystone.import('models'); // Setup common locals for your templates. The following are required for the // bundled templates and layouts. Any runtime locals (that should be set uniquely // for each request) should be added to ./routes/middleware.js keystone.set('locals', { _: require('underscore'), env: keystone.get('env'), utils: keystone.utils, editable: keystone.content.editable }); // Load your project's Routes keystone.set('routes', require('./routes')); // Configure the navigation bar in Keystone's Admin UI keystone.set('nav', { 'users': 'User', 'challenges': ['Challenge', 'Waypoint'], 'personal-marker': ['PersonalMarker'], 'meeting-hotspots': ['MeetingHotspotTemplate', 'MeetingHotspot', 'MeetingHotspotScan'], 'experiences':['Experience', 'ExperienceTicket'], 'user-data': ['Scan', 'UserChallenge', 'UserGeneratedContent', 'UserGeneratedContentRating', 'ActionLog'], 'settings': 'GameSetting' }); // Start Keystone to connect to your database and initialise the web server keystone.start(function(){ //Load game settings var GameSetting = keystone.list('GameSetting'); GameSetting.model.find(function(err, settings) { _.each(settings,function(setting){ keystone.set(setting.name, setting.value); }); //Start agenda keystone.agenda = agenda(['meetinghotspot', 'email']); //Schedule random hotspots keystone.agenda.cancel({name:'spawnRandomMeetingHotspot'}, function(err, removed) { var job = keystone.agenda.create('spawnRandomMeetingHotspot'); job.schedule(keystone.get('randomHotspotTime')); job.repeatAt('tomorrow at '+keystone.get('randomHotspotTime')); job.save(function(err){ console.log('Random hotspot job saved'); }); }); }); }); });
app.on('ready', function() { i18n.init({ ns: { namespaces: ['app', 'menus'], defaultNs: 'app' }, resGetPath: appPath + 'locales/__lng__/__ns__-__lng__.json', // Path to find file resSetPath: appPath + 'locales/__lng__/__ns__-__lng__.json', // Path to store file sendMissingTo: 'fallback|current|all', // Send missing values to lng: 'en-US' }, function(){ var windowSettings = { 'min-width': 680, 'min-height': 420, width: app.settings.v.window.width, height: app.settings.v.window.height, resizable: true, icon: appPath + "resources/app.png", title: "PancakePainter" }; // Centered or fixed window position? if (app.settings.v.window.y === 'center') { windowSettings.center = true; } else { windowSettings.x = app.settings.v.window.x; windowSettings.y = app.settings.v.window.y; } // Create the main application window. mainWindow = new BrowserWindow(windowSettings); // Window wrapper for dialog (can't include module outside of this) :P mainWindow.dialog = function(options, callback) { return dialog['show' + options.t](mainWindow, options, callback); }; // and load the index.html of the app. mainWindow.loadURL('file://' + __dirname + '/index.html'); // Save Move/Resize back to file mainWindow.on('move', function(){ var b = this.getBounds(); app.settings.v.window.x = b.x; app.settings.v.window.y = b.y; app.settings.v.window.width = b.width; app.settings.v.window.height = b.height; app.settings.save(); }); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null; }); }); });
* Given a language code, get best matched code from supported languages. * * > getBestMatchedLangCode('en-US') * 'en' * > getBestMatchedLangCode('zh-TW') * 'zh-TW' * > getBestMatchedLangCode('no-such-code') * 'en' */ i18n.getBestMatchedLangCode = langCode => { const codeList = Object.keys(resources); let bestMatchedCode = langCode; if (codeList.indexOf(langCode) === -1) { if (codeList.indexOf(langCode.substr(0, 2)) > -1) { bestMatchedCode = langCode.substr(0, 2); } else { bestMatchedCode = 'en'; } } return bestMatchedCode; }; // init i18n i18n.init({ lng: global.language || 'en', resources, interpolation: { prefix: '__', suffix: '__' } }); module.exports = i18n;
// image in order to generate a new one with reduced size and palette // ## Dependences // The face recognition uses Opencv and the image manipulation is done via // graphicsmagick var gm = require('gm'), cv = require('opencv'), i18n = require('i18next'), config = require('./config'), utils = require('./utils'), logger = require('./logger'), local_config = require('./local_config') // configuration for 18n i18n.init({ //default language from config lng: local_config.LANGUAGE, ns: 'translation', resGetPath: __dirname + '/locales/__ns__-__lng__.json' }) // #ProduceThumb // reduce and crop the given image // // params: // ``` // @input: image file // @output: where to write. Must be a PNG file // @width: width of the face // @height: height of the face // @x: x values of the top corner of face // @y: y values of the top corner of face // ```