code stringlengths 2 1.05M |
|---|
module.exports = {
init: function() {
var nrom128 = ( this.prgBanks === 1 );
if ( nrom128 ) {
this.loadPRGBank( 0x8000, 0, 0x4000 );
this.loadPRGBank( 0xc000, 0, 0x4000 );
} else {
this.loadPRGBank( 0x8000, 0, 0x8000 );
}
},
readCHR: function( address ) {
return this.chrData[ address ];
},
writeCHR: function( address, value ) {
if ( !this.chrBanks ) {
// TODO, probably not doing this right for all ROMs (eg, ROMs that have both CHR ROM *and* CHR RAM)
this.chrData[ address ] = value;
}
return value;
}
}; |
module.exports = function(sails) {
/**
* Module dependencies.
*/
var _ = require('lodash'),
util = require('sails-util'),
Hook = require('../../index');
/**
* Expose hook definition
*/
return {
SECURITY_LEVEL_NORMAL: 0,
SECURITY_LEVEL_HIGH: 1,
SECURITY_LEVEL_VERYHIGH: 2,
defaults: {
cors: {
origin: '*',
credentials: true,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
headers: 'content-type',
securityLevel: 0,
}
},
initialize: function(cb) {
sails.on('router:before', function () {
// If we're setting CORS on all routes by default, set up a universal route for it here.
// CORS can still be turned off for specific routes by setting "cors:false"
if (sails.config.cors.allRoutes === true) {
sails.router.bind('/*', sendHeaders(), null, {_middlewareType: 'CORS HOOK: sendHeaders'});
}
// Otherwise clear all the headers by default
else {
sails.router.bind('/*', clearHeaders, null, {_middlewareType: 'CORS HOOK: clearHeaders'});
}
var optionsRouteConfigs = {};
// Loop through all configured routes, looking for CORS options
_.each(sails.config.routes, function(config, route) {
var routeInfo = sails.util.detectVerb(route);
var path = routeInfo.original.toLowerCase();
var verb = routeInfo.verb.toLowerCase();
if (!_.isUndefined(config.cors)) {
optionsRouteConfigs[path] = optionsRouteConfigs[path] || {"default": sails.config.cors};
// If cors is set to "true", and we're not doing all routes by default, set
// the CORS headers for this route using the default origin
if (config.cors === true) {
// Use the default CORS config for this path on an OPTIONS request
optionsRouteConfigs[path][verb || "default"] = sails.config.cors;
if (!sails.config.cors.allRoutes) {
sails.router.bind(route, sendHeaders(), null);
}
}
// If cors is set to "false", clear the CORS headers for this route
else if (config.cors === false) {
// Clear headers on an OPTIONS request for this path
optionsRouteConfigs[path][verb || "default"] = "clear";
sails.router.bind(route, clearHeaders, null, {_middlewareType: 'CORS HOOK: clearHeaders'});
return;
}
// Else if cors is set to a string, use that has the origin
else if (typeof config.cors === "string") {
optionsRouteConfigs[path][verb || "default"] = _.extend({origin: config.cors},{methods: verb});
sails.router.bind(route, sendHeaders({origin:config.cors}), null);
}
// Else if cors is an object, use that as the config
else if (_.isPlainObject(config.cors)) {
// If the route has a verb, it shouldn't have a "methods" CORS setting
if (routeInfo.verb && config.cors.methods) {
sails.log.warn("Ignoring 'methods' CORS setting for route "+route+" because it has a verb specified.");
config.cors.methods = verb;
}
optionsRouteConfigs[path][verb || "default"] = config.cors;
sails.router.bind(route, sendHeaders(config.cors), null);
}
// Otherwise throw a warning
else {
sails.log.warn("Invalid CORS settings for route "+route);
}
}
});
_.each(optionsRouteConfigs, function(config, path) {
sails.router.bind("options "+path, sendHeaders(config, true), null, {_middlewareType: 'CORS HOOK: preflight'});
});
// IF SECURITY_LEVEL > "normal"--don't process requests from disallowed origins
//
// We can't just rely on the browser implementing "access-control-allow-origin" correctly;
// we need to make sure that if a request is made from an origin that isn't whitelisted,
// that we don't end up processing that request.
if (sails.config.cors.securityLevel > sails.hooks.cors.SECURITY_LEVEL_NORMAL) {
sails.router.bind('/*', function(req, res, next) {
// If it's a cross-origin request, and the access-control-allow-origin header doesn't match
// the origin header, then we don't approve of this origin and shouldn't continue
// with this request.
if (!sails.util.isSameOrigin(req, sails.config.cors.securityLevel == sails.hooks.cors.SECURITY_LEVEL_VERYHIGH) && res.get('Access-Control-Allow-Origin') != req.headers.origin) {
return res.forbidden();
}
return next();
}, null, {_middlewareType: 'CORS HOOK: catchall'});
}
});
cb();
}
};
function sendHeaders(_routeCorsConfig, isOptionsRoute) {
if (!_routeCorsConfig) {
_routeCorsConfig = {};
}
var _sendHeaders = function(req, res, next) {
var routeCorsConfig;
// If this is an options route handler, pull the config to use based on the method
// that would be used in the follow-on request
if (isOptionsRoute) {
var method = (req.headers['access-control-request-method'] || '').toLowerCase() || "default";
routeCorsConfig = _routeCorsConfig[method];
if (routeCorsConfig == 'clear') {
return clearHeaders(req, res, next);
}
}
// Otherwise just use the config that was passed down
else {
routeCorsConfig = _routeCorsConfig;
}
// If we have an origin header...
if (req.headers && req.headers.origin) {
// Get the allowed origins
var origins = (routeCorsConfig.origin || sails.config.cors.origin).split(',');
// Match the origin of the request against the allowed origins
var foundOrigin = false;
_.every(origins, function(origin) {
origin = origin.trim();
// If we find a whitelisted origin, send the Access-Control-Allow-Origin header
// to greenlight the request.
if (origin == req.headers.origin || origin == "*") {
res.set('Access-Control-Allow-Origin', req.headers.origin);
foundOrigin = true;
return false;
}
return true;
});
if (!foundOrigin) {
// For HTTP requests, set the Access-Control-Allow-Origin header to '', which the browser will
// interpret as, "no way Jose."
res.set('Access-Control-Allow-Origin', '');
}
// Determine whether or not to allow cookies to be passed cross-origin
res.set('Access-Control-Allow-Credentials', !_.isUndefined(routeCorsConfig.credentials) ? routeCorsConfig.credentials : sails.config.cors.credentials);
// Handle preflight requests
if (req.method == "OPTIONS") {
res.set('Access-Control-Allow-Methods', !_.isUndefined(routeCorsConfig.methods) ? routeCorsConfig.methods : sails.config.cors.methods);
res.set('Access-Control-Allow-Headers', !_.isUndefined(routeCorsConfig.headers) ? routeCorsConfig.headers : sails.config.cors.headers);
}
}
next();
};
_sendHeaders._middlewareType = "CORS HOOK: sendHeaders";
return _sendHeaders;
}
function clearHeaders(req, res, next) {
// If we can set headers (i.e. it's not a socket request), do so.
if (res.set) {
res.set('Access-Control-Allow-Origin', '');
res.set('Access-Control-Allow-Credentials', '');
res.set('Access-Control-Allow-Methods', '');
res.set('Access-Control-Allow-Headers', '');
}
next();
}
};
|
"use strict";
var fs = require('fs');
var gm = require('gm').subClass({ imageMagick: true });;
var pdf = require('pdfinfo');
var path = require('path');
var async = require('async');
var logger = require('../logger').serverLogger;
var options = {
type : 'png',
size : 1024,
density : 600,
outputdir : null,
targetname: 'test_',
mem_limit : '32Mb',
thread : 4
};
var Pdf2Img = function() {};
Pdf2Img.prototype.setOptions = function(opts) {
options.type = opts.type || options.type;
options.size = opts.size || options.size;
options.density = opts.density || options.density;
options.outputdir = opts.outputdir || options.outputdir;
options.targetname = opts.targetname || options.targetname;
options.mem_limit = opts.mem_limit || options.mem_limit;
options.thread = opts.thread || options.thread;
};
Pdf2Img.prototype.convert = function(file, callbackreturn) {
async.waterfall([
function(callback) {
fs.stat(file, function(error, result) {
if (error) callback('[Error: File not found]', null);
else {
if (!fs.existsSync(options.outputdir)) {
fs.mkdirSync(options.outputdir);
}
var input = fs.createReadStream(file);
callback(null, input);
}
});
},
function(input, callback) {
pdf(input).info(function(error, data) {
if (error) callback(error, null);
else callback(null, data);
});
},
function(data, callback) {
var pages = [];
if (data.pages === 0 || data.pages === '0')
callback('[Error: Invalid page number]', null);
for (var i = 1; i <= data.pages; i++) {
pages.push(i);
if (i === data.pages) callback(null, pages);
}
},
function(pages, callback) {
async.map(pages, function(page, callbackmap) {
var inputStream = fs.createReadStream(file);
var outputStream = fs.createWriteStream(options.outputdir + '/' + options.targetname + page + '.' + options.type);
convertPdf2Img(inputStream, outputStream, page, function(error, result) {
if (result) {
result.page = page;
callbackmap(null, result);
}
});
}, function(error, results) {
callback(null, results);
});
}
], function(error, result) {
if (error) logger.error(error);
else callbackreturn(result);
});
};
var convertPdf2Img = function(input, output, page, callback) {
var datasize = 0;
if (input.path) {
var filepath = input.path;
} else {
callback('[Error: Invalid file path]', null);
}
var filename = filepath + '[' + (page - 1) + ']';
var result = gm(input, filename).limit('memory', options.mem_limit)//.limit('threads', options.thread)
.density(options.density, options.density)
.resize(options.size)
.stream(options.type);
output.on('error', function(error) {
callback(error, null);
});
result.on('error', function(error) {
callback(error, null);
});
result.on('data', function(data) {
datasize = data.length;
});
result.on('end', function() {
if (datasize < 127) {
callback('[Error: Invalid data size]', null);
}
var results = {
page: 0,
name: path.basename(output.path),
path: output.path
};
output.end();
callback(null, results);
});
result.pipe(output);
};
module.exports = new Pdf2Img; |
/*
* Document : uiIcons.js
* Author : pixelcave
* Description: Custom javascript code used in Icon Packs pages (Font Awesome and Glyphicons Pro)
*/
var UiIcons = function() {
return {
init: function() {
var titleAttr;
// When an icon button is clicked
$('#page-content .btn').click(function(){
// Get the icon class from the button attribute (data-original-title is created by tooltip)
titleAttr = $(this).attr('data-original-title');
// Set the content of the input and select it
$('#icon-gen-input')
.val( '<i class="' + titleAttr + '"></i>' )
.select();
// Animate scrolling to the icon generator
$('html,body')
.animate({ scrollTop: $('#icon-gen').offset().top - 15 });
return false;
});
}
};
}(); |
( function(Dataflow) {
var Source = Dataflow.prototype.plugin("source");
// Whether the graph may be updated via the source form
Source.updateAllowed = true;
Source.initialize = function(dataflow){
var $form = $(
'<form class="dataflow-plugin-view-source">'+
'<div style="">'+
'<textarea class="code" style="width:99%; height:400px;; margin:0; padding: 0;"></textarea><br/>'+
'</div>'+
'<input class="apply" type="submit" value="apply changes" style="position: absolute; right:5px; bottom:5px;" />'+
'</form>'
);
var $code = $form.find(".code");
dataflow.addPlugin({
id: "source",
label: "view source",
name: "",
menu: $form,
icon: "code",
pinned: true
});
Source.show = function(source) {
var scrollBackTop = $code.prop("scrollTop");
$code.val( source );
$code.scrollTop( scrollBackTop );
};
var showGraph = function(graph){
if (dataflow.graph) {
Source.show( JSON.stringify(dataflow.graph.toJSON(), null, " ") );
}
};
// Method for setting graph change listeners on or off
Source.listeners = function(boo){
if (boo) {
// On change update code view
dataflow.on("change", showGraph);
} else {
// Custom
dataflow.off("change", showGraph);
}
};
// By default we listen to graph changes
Source.listeners(true);
// Whether to allow updating the graph from the form
Source.allowUpdate = function (allowed) {
var $button = $form.find('.apply');
if (allowed) {
Source.updateAllowed = true;
$button.show();
$code.removeAttr('readonly');
return;
}
Source.updateAllowed = false;
$button.hide();
$code.attr('readonly', 'readonly');
};
// Apply source to test graph
$form.submit(function(){
Source.updateGraph($code, dataflow);
return false;
});
};
// Method for updating the graph from the form. Override
// this for systems using another graph format (for example,
// NoFlo).
Source.updateGraph = function ($code, dataflow) {
if (!Source.updateAllowed) {
return;
}
var graph;
try {
graph = JSON.parse( $code.val() );
} catch(error) {
dataflow.log("Invalid JSON");
return false;
}
if (graph) {
var g = dataflow.loadGraph(graph);
g.trigger("change");
}
};
}(Dataflow) );
|
var counter = require("./counter");
exports.increment = function(){
counter.increment();
};
|
var graphics = (function() {
var projections = {"mercator": d3.geo.mercator,
"orthographic": d3.geo.orthographic}
var init = function(){
set_projection("mercator")
}
var projection
var path
function set_projection(proj_str){
projection = projections[proj_str]()
.translate([window.innerWidth / 2, window.innerHeight / 2])
.precision(.1);
projection.string = proj_str
path = d3.geo.path()
.pointRadius(0.1)
.projection(projection);
}
var update_projection = function(orbit) {
var tles = window.tles
var tracking = window.tracking
position = ephemgen(
[
tles[tracking]["tle1"],
tles[tracking]["tle2"]
],
1
)
if (projection.string == "orthographic") {
projection.clipAngle(90)
.rotate([- position[0][0], -position[0][1]/2])
.scale((window.innerWidth + 1) / 1.5 / Math.PI)
}
if (projection.string == "mercator") {
// rotate view along spin axis only
projection.rotate([- position[0][0], 0])
.scale((window.innerWidth + 1) / 1.5 / Math.PI)
}
}
var render_earth = function(earth, path, svg) {
$("#mysvg").empty();
svg.append("defs").append("path")
.datum({type: "Sphere"})
.attr("id", "sphere")
.attr("d", path);
svg.append("path")
.datum(earth.grid)
.attr("class", "graticule")
.attr("d", path);
svg.insert("path", ".graticule")
.datum(earth.land)
.attr("class", "land")
.call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", window.zoom))
.attr("d", path);
svg.insert("path", ".graticule")
.datum(earth.borders)
.attr("class", "boundary")
.attr("d", path);
}
var render_ephemeris = function(orbit, path, svg) {
var sat = {type: 'MultiPoint', coordinates : orbit}
svg.insert("path", ".graticule")
.datum(sat)
.attr("class", "orbit")
.attr("d", path);
}
var render = function(orbits, satellites) {
update_projection(orbit);
render_earth(window.earth, path, window.svg)
for (var i = 0; i < satellites.length; i++) {
console.log(satellites);
console.log(tles[satellites[i]]);
var orbit = orbits[i]//ephemgen(tles[satellites[i]], 1500)
render_ephemeris(orbit, path, window.svg)
}
}
init()
return { render: render,
set_projection: set_projection,
update_projection: update_projection
}
}());
|
define("#base/0.9.0/base",["class","events","./options"],function(a){var b=a("class"),c=a("events"),d=a("./options");return b.create({Implements:[c,d]})}); |
ClassExtend('Controller', function PluginListController() {
this.__construct = function() {
this.load.ajax();
this.load.module('ui');
};
this.index = function() {
Module.ready('ui', function() {
new Module.zoom('plugin_detail', 'ajax', {width : 700, height : 500});
}) ;
//DOM.id('scan_plg').event('click', this.__scanPlugins, this);
this.event.exprLive('a#toggle_check', 'click', this.toggleCheck, this);
this.event.exprLive('div#scaned_plugin_list table td', 'click', this.checkControl, this);
// remove confirm
this.event.exprLive('a#remove_plugin, a.delete', 'click', this.__deleteConfirm, this);
};
this.toggleCheck = function(ev) {
var t = DOM(ev.target),
checked = (t.readAttr('rel') === 'is_check') ? false : true,
nch = checked ? 'is_check' : '';
DOM('div#scaned_plugin_list table input').foreach(function() {
this.checked = checked;
});
t.attr('rel', nch);
};
this.checkControl = function (ev) {
var check = DOM(ev.target).parent().getOne('input').get();
if (!check) { return;}
else {
check.checked = (check.checked === true) ? false : true;
}
};
this.__deleteConfirm = function(ev) {
if ( ! confirm('プラグインをアンインストールします。\n'
+ 'このプラグインにより生成されたページがある場合、バージョンも含め削除されます。'
+ '(ブロックは以前のバージョンのものは表示されますが、新規追加はできなくなります。)\n\nよろしいですか?')) {
return false;
}
};
this.__scanPlugins = function(ev) {
ev.preventDefault();
var that = this,
state = DOM(ev.target).next().show('i'),
box = DOM.id('scaned_plugin_list')
.addStyle({
height : '0px',
overflow : 'hidden'
});
this.ajax.get(ev.target.href, {
error : function() {
alert('プラグインのスキャンに失敗しました。');
},
success: function(resp) {
box.html(resp.responseText)
.animate('blindDown', {
mode : 'y',
speed : 30,
easing : -50,
callback : function () {state.hide();}
});
}
});
};
this.__getPluginDescription = function(ev) {
var e = DOM(ev.target),
pName = ev.target.rel,
target = e.parent().prev().last();
if (target.isEmpty()) {
this.ajax.get('dashboard/plugins/plugin_list/get_plugin_detail/' + pName + '/' + this.config.item('sz_token'), {
error : function() {
alert('プラグイン詳細の取得に失敗しました。');
},
success: function(resp) {
target.html(resp.responseText)
.show();
}
});
} else {
target.show();
}
};
}); |
var searchData=
[
['rock_5fcount',['rock_count',['../structlevel__rock__spawn.html#a91c9ec87f6ade8287ddcb9a8018f988f',1,'level_rock_spawn']]],
['rock_5fspawns',['rock_spawns',['../classlevel.html#a40952b770c5ff48d042380811fff8186',1,'level']]],
['rocks_5fspawned',['rocks_spawned',['../structlevel__rock__spawn.html#aa49b5dc0a6711b9512f242fd283d7d0f',1,'level_rock_spawn']]]
];
|
var Serializer = require("../../models").Serializer
exports.addSerializer = function() {
return new Serializer({ select: ['id', 'body', 'createdAt', 'updatedAt', 'createdBy', 'postId'],
createdBy: { select: ['id', 'username', 'info'],
info: { select: ['screenName'] } }
});
};
|
import { Reactor } from 'nuclear-js'
import expect from 'expect'
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from '../src/index'
import setup from './setup'
describe('Provider', () => {
setup()
it('should provide reactor context to children', (done) => {
var reactor = new Reactor()
class Child extends React.Component {
constructor(props, context) {
super(props, context)
}
componentDidMount() {
expect(this.context.reactor).toEqual(reactor)
done()
}
render() {
return <div></div>
}
}
Child.contextTypes = {
reactor: null,
}
class TestComponent extends React.Component {
constructor(props, context) {
super(props, context)
}
render() {
return <Provider reactor={reactor} ><Child /></Provider>
}
}
ReactDOM.render(<TestComponent />, document.getElementById('test-root'))
})
})
|
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
'use strict';
var _ = require('underscore');
var url = require('url');
var util = require('../util/util');
var ServiceSettings = require('./servicesettings');
var Constants = require('../util/constants');
var StorageServiceClientConstants = Constants.StorageServiceClientConstants;
var ConnectionStringKeys = Constants.ConnectionStringKeys;
var Validate = require('../util/validate');
var SR = require('../util/sr');
var useDevelopmentStorageSetting = ServiceSettings.setting(ConnectionStringKeys.USE_DEVELOPMENT_STORAGE_NAME, true);
var developmentStorageProxyUriSetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME, Validate.isValidUri);
var defaultEndpointsProtocolSetting = ServiceSettings.setting(ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME, 'http', 'https');
var accountNameSetting = ServiceSettings.setting(ConnectionStringKeys.ACCOUNT_NAME_NAME);
var accountKeySetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.ACCOUNT_KEY_NAME, Validate.isBase64Encoded);
var sasSetting = ServiceSettings.settingWithFunc(ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME, _.isString);
var blobEndpointSetting = ServiceSettings.settingWithFunc(
ConnectionStringKeys.BLOB_ENDPOINT_NAME,
Validate.isValidHost
);
var queueEndpointSetting = ServiceSettings.settingWithFunc(
ConnectionStringKeys.QUEUE_ENDPOINT_NAME,
Validate.isValidHost
);
var tableEndpointSetting = ServiceSettings.settingWithFunc(
ConnectionStringKeys.TABLE_ENDPOINT_NAME,
Validate.isValidHost
);
var fileEndpointSetting = ServiceSettings.settingWithFunc(
ConnectionStringKeys.FILE_ENDPOINT_NAME,
Validate.isValidHost
);
var validKeys = [
ConnectionStringKeys.USE_DEVELOPMENT_STORAGE_NAME,
ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME,
ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME,
ConnectionStringKeys.ACCOUNT_NAME_NAME,
ConnectionStringKeys.ACCOUNT_KEY_NAME,
ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME,
ConnectionStringKeys.BLOB_ENDPOINT_NAME,
ConnectionStringKeys.QUEUE_ENDPOINT_NAME,
ConnectionStringKeys.TABLE_ENDPOINT_NAME,
ConnectionStringKeys.FILE_ENDPOINT_NAME
];
/**
* Creates new storage service settings instance.
*
* @param {string} name The storage service name.
* @param {string} key The storage service key.
* @param {string} sasToken The storage service shared access signature token.
* @param {string} blobEndpoint The storage service blob endpoint.
* @param {string} queueEndpoint The storage service queue endpoint.
* @param {string} tableEndpoint The storage service table endpoint.
* @param {string} fileEndpoint The storage service file endpoint.
* @param {bool} usePathStyleUri Boolean value indicating wether to use path style uri or not.
*/
function StorageServiceSettings(name, key, sasToken, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, usePathStyleUri) {
this._name = name;
this._key = key;
if (sasToken && sasToken[0] === '?') {
this._sasToken = sasToken.slice(1);
} else {
this._sasToken = sasToken;
}
this._blobEndpoint = blobEndpoint;
this._queueEndpoint = queueEndpoint;
this._tableEndpoint = tableEndpoint;
this._fileEndpoint = fileEndpoint;
if (usePathStyleUri) {
this._usePathStyleUri = usePathStyleUri;
} else {
this._usePathStyleUri = false;
}
}
/**
* Creates a StorageServiceSettings object from the given connection string.
*
* @param {string} connectionString The storage settings connection string.
* @return {StorageServiceSettings}
*/
StorageServiceSettings.createFromConnectionString = function (connectionString) {
var tokenizedSettings = ServiceSettings.parseAndValidateKeys(connectionString, validKeys);
try {
return StorageServiceSettings.createFromSettings(tokenizedSettings);
} catch (e) {
if (e instanceof ServiceSettings.NoMatchError) {
// Replace no match settings exception by no match connection string one.
ServiceSettings.noMatchConnectionString(connectionString);
} else {
throw e;
}
}
};
StorageServiceSettings.createExplicitly = function (storageAccount, storageAccessKey, host, sasToken) {
var settings = {};
function addIfNotNullOrEmpty(key, value){
if(typeof value === 'string' && !util.stringIsEmpty(value)){
settings[key] = value;
} else if (typeof value == 'object' && !util.objectIsNull(value)) {
settings[key] = value;
}
}
// Endpoints
if (host) {
addIfNotNullOrEmpty('blobendpoint', host);
addIfNotNullOrEmpty('tableendpoint', host);
addIfNotNullOrEmpty('queueendpoint', host);
addIfNotNullOrEmpty('fileendpoint', host);
} else {
addIfNotNullOrEmpty('defaultendpointsprotocol', ServiceSettings.DEFAULT_PROTOCOL.split(':', 1)[0]);
}
addIfNotNullOrEmpty('accountname', storageAccount);
addIfNotNullOrEmpty('accountkey', storageAccessKey);
addIfNotNullOrEmpty('sharedaccesssignature', sasToken);
return StorageServiceSettings.createFromSettings(settings);
};
StorageServiceSettings.createFromEnvironment = function () {
var emulated = process.env[StorageServiceClientConstants.EnvironmentVariables.EMULATED];
if (emulated) {
return StorageServiceSettings.getDevelopmentStorageAccountSettings();
}
var connectionString = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_CONNECTION_STRING];
if (connectionString) {
return StorageServiceSettings.createFromConnectionString(connectionString);
}
var storageAccount = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCOUNT];
var storageAccessKey = process.env[StorageServiceClientConstants.EnvironmentVariables.AZURE_STORAGE_ACCESS_KEY];
if(storageAccount && storageAccessKey){
return StorageServiceSettings.createExplicitly(storageAccount, storageAccessKey, null, null);
}
throw new Error(SR.NO_CREDENTIALS_PROVIDED);
};
/**
* Creates a StorageServiceSettings object from a set of settings.
*
* @param {object} settings The settings object.
* @return {StorageServiceSettings}
*/
StorageServiceSettings.createFromSettings = function (settings) {
// Devstore case
var matchedSpecs = ServiceSettings.matchedSpecification(
settings,
ServiceSettings.allRequired(useDevelopmentStorageSetting),
ServiceSettings.optional(developmentStorageProxyUriSetting)
);
if (matchedSpecs) {
var proxyUri = util.tryGetValueInsensitive(
ConnectionStringKeys.DEVELOPMENT_STORAGE_PROXY_URI_NAME,
settings
);
return this.getDevelopmentStorageAccountSettings(proxyUri);
}
// Account/Key automatic case
matchedSpecs = ServiceSettings.matchedSpecification(
settings,
ServiceSettings.allRequired(
defaultEndpointsProtocolSetting,
accountNameSetting,
accountKeySetting
),
ServiceSettings.optional(
blobEndpointSetting,
queueEndpointSetting,
tableEndpointSetting,
fileEndpointSetting
)
);
if (matchedSpecs) {
return this._createStorageServiceSettings(settings);
}
// Account/Key explicit case
matchedSpecs = ServiceSettings.matchedSpecification(
settings,
ServiceSettings.allRequired(
accountNameSetting,
accountKeySetting
),
ServiceSettings.atLeastOne(
blobEndpointSetting,
queueEndpointSetting,
tableEndpointSetting,
fileEndpointSetting
)
);
if (matchedSpecs) {
return this._createStorageServiceSettings(settings);
}
// SAS case
matchedSpecs = ServiceSettings.matchedSpecification(
settings,
ServiceSettings.allRequired(
sasSetting
),
ServiceSettings.atLeastOne(
blobEndpointSetting,
queueEndpointSetting,
tableEndpointSetting,
fileEndpointSetting
)
);
if(matchedSpecs) {
return this._createStorageServiceSettings(settings);
}
// anonymous explicit case
// Only blob anonymous access is valid.
matchedSpecs = ServiceSettings.matchedSpecification(
settings,
ServiceSettings.allRequired(
blobEndpointSetting
),
ServiceSettings.optional(
fileEndpointSetting,
queueEndpointSetting,
tableEndpointSetting
)
);
if(matchedSpecs) {
return this._createStorageServiceSettings(settings);
}
ServiceSettings.noMatchSettings(settings);
};
/**
* Returns a StorageServiceSettings with development storage credentials using
* the specified proxy Uri.
*
* @param {string} proxyUri The proxy endpoint to use.
* @return {StorageServiceSettings}
*/
StorageServiceSettings.getDevelopmentStorageAccountSettings = function (proxyUri) {
if (!proxyUri) {
proxyUri = StorageServiceClientConstants.DEV_STORE_URI;
}
var parsedUri = url.parse(proxyUri);
var scheme = parsedUri.protocol;
var host = parsedUri.host;
var prefix = scheme + '//' + host;
var blobEndpoint = {
primaryHost: prefix + ':10000' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
secondaryHost: prefix + ':10000' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary'
};
var queueEndpoint = {
primaryHost: prefix + ':10001' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
secondaryHost: prefix + ':10001' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary'
};
var tableEndpoint = {
primaryHost: prefix + ':10002' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
secondaryHost: prefix + ':10002' + '/' + StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT + '-secondary'
};
return new StorageServiceSettings(
StorageServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT,
StorageServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY,
null,
blobEndpoint,
queueEndpoint,
tableEndpoint,
null,
true
);
};
/**
* Creates StorageServiceSettings object given endpoints uri.
*
* @ignore
* @param {array} settings The service settings.
* @param {string} blobEndpointUri The blob endpoint uri.
* @param {string} queueEndpointUri The queue endpoint uri.
* @param {string} tableEndpointUri The table endpoint uri.
* @param {string} fileEndpointUri The file endpoint uri.
* @return {StorageServiceSettings}
*/
StorageServiceSettings._createStorageServiceSettings = function (settings) {
var standardizeHost = function (host, accountName, scheme, dns){
var storageHost;
if (host) {
storageHost = {};
storageHost.primaryHost = _.isString(host) ? host : host.primaryHost;
storageHost.secondaryHost = _.isString(host) ? undefined : host.secondaryHost;
}
if (scheme && accountName && dns) {
storageHost = storageHost ? storageHost : {};
storageHost.primaryHost = storageHost.primaryHost ? storageHost.primaryHost : url.format({ protocol: scheme, hostname: accountName + '.' + dns});
storageHost.secondaryHost = storageHost.secondaryHost ? storageHost.secondaryHost : url.format({ protocol: scheme, hostname: accountName + '-secondary.' + dns});
}
return storageHost;
};
var scheme = util.tryGetValueInsensitive(
ConnectionStringKeys.DEFAULT_ENDPOINTS_PROTOCOL_NAME,
settings
);
var accountName = util.tryGetValueInsensitive(
ConnectionStringKeys.ACCOUNT_NAME_NAME,
settings
);
var accountKey = util.tryGetValueInsensitive(
ConnectionStringKeys.ACCOUNT_KEY_NAME,
settings
);
var sasToken = util.tryGetValueInsensitive(
ConnectionStringKeys.SHARED_ACCESS_SIGNATURE_NAME,
settings
);
var blobEndpoint = standardizeHost(
util.tryGetValueInsensitive(ConnectionStringKeys.BLOB_ENDPOINT_NAME, settings),
accountName,
scheme,
StorageServiceClientConstants.CLOUD_BLOB_HOST);
var queueEndpoint = standardizeHost(
util.tryGetValueInsensitive(ConnectionStringKeys.QUEUE_ENDPOINT_NAME, settings),
accountName,
scheme,
StorageServiceClientConstants.CLOUD_QUEUE_HOST);
var tableEndpoint = standardizeHost(
util.tryGetValueInsensitive(ConnectionStringKeys.TABLE_ENDPOINT_NAME, settings),
accountName,
scheme,
StorageServiceClientConstants.CLOUD_TABLE_HOST);
var fileEndpoint = standardizeHost(
util.tryGetValueInsensitive(ConnectionStringKeys.FILE_ENDPOINT_NAME, settings),
accountName,
scheme,
StorageServiceClientConstants.CLOUD_FILE_HOST);
return new StorageServiceSettings(
accountName,
accountKey,
sasToken,
blobEndpoint,
queueEndpoint,
tableEndpoint,
fileEndpoint
);
};
StorageServiceSettings.validKeys = validKeys;
exports = module.exports = StorageServiceSettings; |
#!/usr/bin/env node
var util = require('util'),
http = require('http'),
fs = require('fs'),
url = require('url'),
events = require('events');
var DEFAULT_PORT = 8000;
function main(argv) {
new HttpServer({
'GET': createServlet(StaticServlet),
'HEAD': createServlet(StaticServlet),
}).start(Number(argv[2]) || DEFAULT_PORT);
}
function escapeHtml(value) {
return value.toString().
replace('<', '<').
replace('>', '>').
replace('"', '"');
}
function createServlet(Class) {
var servlet = new Class();
return servlet.handleRequest.bind(servlet);
}
/**
* An Http server implementation that uses a map of methods to decide
* action routing.
*
* @param {Object} Map of method => Handler function
*/
function HttpServer(handlers) {
this.handlers = handlers;
this.server = http.createServer(this.handleRequest_.bind(this));
}
HttpServer.prototype.start = function(port) {
this.port = port;
this.server.listen(port);
util.puts('FireMote demo Http Server running at http://localhost:' + port + '/');
};
HttpServer.prototype.parseUrl_ = function(urlString) {
var parsed = url.parse(urlString);
parsed.pathname = url.resolve('/', parsed.pathname);
return url.parse(url.format(parsed), true);
};
HttpServer.prototype.handleRequest_ = function(req, res) {
var logEntry = req.method + ' ' + req.url;
if (req.headers['user-agent']) {
logEntry += ' ' + req.headers['user-agent'];
}
util.puts(logEntry);
req.url = this.parseUrl_(req.url);
var handler = this.handlers[req.method];
if (!handler) {
res.writeHead(501);
res.end();
} else {
handler.call(this, req, res);
}
};
/**
* Handles static content.
*/
function StaticServlet() {}
StaticServlet.MimeMap = {
'txt': 'text/plain',
'html': 'text/html',
'css': 'text/css',
'xml': 'application/xml',
'json': 'application/json',
'js': 'application/javascript',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'png': 'image/png',
'svg': 'image/svg+xml'
};
StaticServlet.prototype.handleRequest = function(req, res) {
var self = this;
var path = ('./' + req.url.pathname).replace('//','/').replace(/%(..)/g, function(match, hex){
return String.fromCharCode(parseInt(hex, 16));
});
if (path.indexOf("FireMote") === 2) {
util.puts("FireMote[" + path.substring(10) + "]");
return self.sendFireMote_(req, res, path.substring(10));
}
var parts = path.split('/');
if (parts[parts.length-1].charAt(0) === '.')
return self.sendForbidden_(req, res, path);
fs.stat(path, function(err, stat) {
if (err)
return self.sendMissing_(req, res, path);
if (stat.isDirectory())
return self.sendDirectory_(req, res, path);
return self.sendFile_(req, res, path);
});
}
StaticServlet.prototype.sendError_ = function(req, res, error) {
res.writeHead(500, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>Internal Server Error</title>\n');
res.write('<h1>Internal Server Error</h1>');
res.write('<pre>' + escapeHtml(util.inspect(error)) + '</pre>');
util.puts('500 Internal Server Error');
util.puts(util.inspect(error));
};
StaticServlet.prototype.sendMissing_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(404, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>404 Not Found</title>\n');
res.write('<h1>Not Found</h1>');
res.write(
'<p>The requested URL ' +
escapeHtml(path) +
' was not found on this server.</p>'
);
res.end();
util.puts('404 Not Found: ' + path);
};
StaticServlet.prototype.sendForbidden_ = function(req, res, path) {
path = path.substring(1);
res.writeHead(403, {
'Content-Type': 'text/html'
});
res.write('<!doctype html>\n');
res.write('<title>403 Forbidden</title>\n');
res.write('<h1>Forbidden</h1>');
res.write(
'<p>You do not have permission to access ' +
escapeHtml(path) + ' on this server.</p>'
);
res.end();
util.puts('403 Forbidden: ' + path);
};
StaticServlet.prototype.sendRedirect_ = function(req, res, redirectUrl) {
res.writeHead(301, {
'Content-Type': 'text/html',
'Location': redirectUrl
});
res.write('<!doctype html>\n');
res.write('<title>301 Moved Permanently</title>\n');
res.write('<h1>Moved Permanently</h1>');
res.write(
'<p>The document has moved <a href="' +
redirectUrl +
'">here</a>.</p>'
);
res.end();
util.puts('301 Moved Permanently: ' + redirectUrl);
};
StaticServlet.prototype.sendFireMote_ = function(req, res, path) {
var self = this;
res.writeHead(200, { 'Content-Type': 'application/json' });
if (req.method === 'HEAD') {
res.end();
} else if (req.method === 'GET') {
util.puts("sending FireMote GET response");
res.write("{'response':'GET hello'}");
res.end();
} else {
util.puts("sending FireMote POST response");
res.write("{'response':'POST greetings'}");
res.end();
}
};
StaticServlet.prototype.sendFile_ = function(req, res, path) {
var self = this;
var file = fs.createReadStream(path);
res.writeHead(200, {
'Content-Type': StaticServlet.
MimeMap[path.split('.').pop()] || 'text/plain'
});
if (req.method === 'HEAD') {
res.end();
} else {
file.on('data', res.write.bind(res));
file.on('close', function() {
res.end();
});
file.on('error', function(error) {
self.sendError_(req, res, error);
});
}
};
StaticServlet.prototype.sendDirectory_ = function(req, res, path) {
var self = this;
if (path.match(/[^\/]$/)) {
req.url.pathname += '/';
var redirectUrl = url.format(url.parse(url.format(req.url)));
return self.sendRedirect_(req, res, redirectUrl);
}
fs.readdir(path, function(err, files) {
if (err)
return self.sendError_(req, res, error);
if (!files.length)
return self.writeDirectoryIndex_(req, res, path, []);
var remaining = files.length;
files.forEach(function(fileName, index) {
fs.stat(path + '/' + fileName, function(err, stat) {
if (err)
return self.sendError_(req, res, err);
if (stat.isDirectory()) {
files[index] = fileName + '/';
}
if (!(--remaining))
return self.writeDirectoryIndex_(req, res, path, files);
});
});
});
};
StaticServlet.prototype.writeDirectoryIndex_ = function(req, res, path, files) {
path = path.substring(1);
res.writeHead(200, {
'Content-Type': 'text/html'
});
if (req.method === 'HEAD') {
res.end();
return;
}
res.write('<!doctype html>\n');
res.write('<title>' + escapeHtml(path) + '</title>\n');
res.write('<style>\n');
res.write(' ol { list-style-type: none; font-size: 1.2em; }\n');
res.write('</style>\n');
res.write('<h1>Directory: ' + escapeHtml(path) + '</h1>');
res.write('<ol>');
files.forEach(function(fileName) {
if (fileName.charAt(0) !== '.') {
res.write('<li><a href="' +
escapeHtml(fileName) + '">' +
escapeHtml(fileName) + '</a></li>');
}
});
res.write('</ol>');
res.end();
};
// Must be last,
main(process.argv);
|
var _ = require('underscore');
var Backbone = require('backbone');
var config = require('../conf');
exports = module.exports = Backbone.Model.extend({
idAttribute: '_id',
url: config.api.host + '/accounts',
defaults: {
email: '',
password:'',
username: '',
avatar: '',
biography: '',
status: {},
},
validate: function(attrs, options){
var errors = [];
if(!/^([a-zA-Z0-9_-])+$/.test(attrs.username)){
errors.push({
name: 'username',
message: '用户名不合法'
});
}
if(!( /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(attrs.email))){
errors.push({
name: 'email',
message: '不是有效的电子邮件'
});
}
if(!_.isEmpty(attrs.password) && attrs.password.length < 5){
errors.push({
name: 'password',
message: '密码长度不正确'
});
}
if(attrs.cpassword != attrs.password){
errors.push({
name: 'cpassword',
message: '两次输入不一致'
});
}
if(!_.isEmpty(errors)) return errors;
},
});
|
var a = "сенсея";
console.log(a);
|
var should = require('chai').should(); // eslint-disable-line
describe('is', () => {
var Hexo = require('../../../lib/hexo');
var hexo = new Hexo(__dirname);
var is = require('../../../lib/plugins/helper/is');
it('is_current', () => {
is.current.call({path: 'index.html', config: hexo.config}).should.be.true;
is.current.call({path: 'foo/bar', config: hexo.config}, 'foo').should.be.true;
is.current.call({path: 'foo/bar', config: hexo.config}, 'foo/bar').should.be.true;
is.current.call({path: 'foo/bar', config: hexo.config}, 'foo/baz').should.be.false;
});
it('is_home', () => {
is.home.call({page: {__index: true}}).should.be.true;
is.home.call({page: {}}).should.be.false;
});
it('is_post', () => {
is.post.call({page: {__post: true}}).should.be.true;
is.post.call({page: {}}).should.be.false;
});
it('is_page', () => {
is.page.call({page: {__page: true}}).should.be.true;
is.page.call({page: {}}).should.be.false;
});
it('is_archive', () => {
is.archive.call({page: {}}).should.be.false;
is.archive.call({page: {archive: true}}).should.be.true;
is.archive.call({page: {archive: false}}).should.be.false;
});
it('is_year', () => {
is.year.call({page: {}}).should.be.false;
is.year.call({page: {archive: true}}).should.be.false;
is.year.call({page: {archive: true, year: 2014}}).should.be.true;
is.year.call({page: {archive: true, year: 2014}}, 2014).should.be.true;
is.year.call({page: {archive: true, year: 2014}}, 2015).should.be.false;
is.year.call({page: {archive: true, year: 2014, month: 10}}).should.be.true;
});
it('is_month', () => {
is.month.call({page: {}}).should.be.false;
is.month.call({page: {archive: true}}).should.be.false;
is.month.call({page: {archive: true, year: 2014}}).should.be.false;
is.month.call({page: {archive: true, year: 2014, month: 10}}).should.be.true;
is.month.call({page: {archive: true, year: 2014, month: 10}}, 2014, 10).should.be.true;
is.month.call({page: {archive: true, year: 2014, month: 10}}, 2015, 10).should.be.false;
is.month.call({page: {archive: true, year: 2014, month: 10}}, 2014, 12).should.be.false;
is.month.call({page: {archive: true, year: 2014, month: 10}}, 10).should.be.true;
is.month.call({page: {archive: true, year: 2014, month: 10}}, 12).should.be.false;
});
it('is_category', () => {
is.category.call({page: {category: 'foo'}}).should.be.true;
is.category.call({page: {category: 'foo'}}, 'foo').should.be.true;
is.category.call({page: {category: 'foo'}}, 'bar').should.be.false;
is.category.call({page: {}}).should.be.false;
});
it('is_tag', () => {
is.tag.call({page: {tag: 'foo'}}).should.be.true;
is.tag.call({page: {tag: 'foo'}}, 'foo').should.be.true;
is.tag.call({page: {tag: 'foo'}}, 'bar').should.be.false;
is.tag.call({page: {}}).should.be.false;
});
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M20 12c0-1.1.9-2 2-2V4H2.01v6c1.1 0 1.99.9 1.99 2s-.89 2-2 2v6h20v-6c-1.1 0-2-.9-2-2zm-4.42 4.8L12 14.5l-3.58 2.3 1.08-4.12-3.29-2.69 4.24-.25L12 5.8l1.54 3.95 4.24.25-3.29 2.69 1.09 4.11z" />
, 'LocalActivitySharp');
|
var test = require("tape");
var intercept = require("intercept-stdout");
var Logger = require("../../src/logger.js");
var Logger2 = require("../../src/logger.js");
//test("should skip low level log by default",function(t){
// Logger.debug("test");
//
// t.end();
//});
test("should keep the verbose config",function(t){
Logger.setVerboseLevel(0);
var captured_text = "";
var unhook_intercept = intercept(function(txt) {
captured_text += txt;
});
Logger.info("test Logger 1");
Logger2.info("test Logger 2");
Logger.setVerboseLevel(4);
Logger2.info("test");
t.equal(captured_text,"\x1b[34mtest\x1b[0m\x1b[0m\n");
unhook_intercept();
t.end();
}); |
$('.selectize').selectize({
plugins: ['remove_button'],
selectOnTab: true,
closeAfterSelect: true
});
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
autoclose: true,
todayHighlight: true
});
$('[data-toggle="popover"]').on('click', function(e){
e.preventDefault();
}).popover();
$('[data-toggle="tooltip"]').on('click', function(e){
e.preventDefault();
}).tooltip();
|
import React from 'react'
import StreamList from './StreamList'
import StreamCardContainer from './StreamCardContainer'
export default ({
streams
}) => (
<StreamList>
{streams.map((stream) => (
<StreamCardContainer streamId={stream.id} key={stream.id} />
))}
{streams.length === 0 &&
<p className='none'>No streams found.</p>}
</StreamList>
)
|
module.exports = function(DwUrlExtraction) {
}; |
describe("nesting views", function () {
describe("delegating events", function () {
it('should delegate events to the parent view only', function () {
var subViewSpy = sinon.spy(),
viewSpy = sinon.spy();
var SubView = Thumbs.View.extend({
clickEvent: subViewSpy
});
var TestView = Thumbs.TemplateView.extend({
template: '<div data-thumbs-id="subView" data-thumbs-view="SubView"><a data-thumbs-delegate="click:clickEvent">Link</a></div>',
SubView: SubView,
clickEvent: viewSpy
});
var view = new TestView();
view.render();
view.$("a").click();
expect(subViewSpy).toHaveBeenCalled();
expect(viewSpy).toHaveBeenCalled();
});
it('should delegate events to the subview if not nested', function () {
var subViewSpy = sinon.spy(),
viewSpy = sinon.spy();
var SubView = Thumbs.TemplateView.extend({
template: '<a data-thumbs-delegate="click:clickEvent">Link</a>',
clickEvent: subViewSpy
});
var TestView = Thumbs.TemplateView.extend({
template: '<div data-thumbs-id="subView" data-thumbs-view="SubView"></div>',
SubView: SubView,
clickEvent: viewSpy
});
var view = new TestView();
view.render();
view.$("a").click();
expect(subViewSpy).toHaveBeenCalledOnce();
expect(viewSpy).toHaveNotBeenCalled();
});
});
describe("binding", function () {
it('should thumbs-bind on nested views to the parent model', function () {
var TestModel = Thumbs.Model.extend({});
var SubView = Thumbs.View.extend({
});
var model = new TestModel({val: "A"});
var otherModel = new TestModel();
var TestView = Thumbs.TemplateView.extend({
template: '<div data-thumbs-id="subView" data-thumbs-view="SubView" data-thumbs-args="model:otherModel"><span data-thumbs-bind="val"></span></div>',
SubView: SubView,
otherModel: otherModel
});
var view = new TestView({model: model});
view.render();
expect(view.$("span").text()).toBe("A");
model.set("val", "B");
expect(view.$("span").text()).toBe("B");
});
it('should thumbs-bind-class on nested views to the parent view', function () {
var TestModel = Thumbs.Model.extend({});
var SubView = Thumbs.View.extend({
});
var TestView = Thumbs.TemplateView.extend({
template: '<div data-thumbs-id="subView" data-thumbs-view="SubView"><span data-thumbs-bind-class="visible:isVisible"></span></div>',
SubView: SubView
});
var model = new TestModel({isVisible: false});
var view = new TestView({model: model});
view.render();
expect(view.$("span").is(".visible")).toBe(false);
model.set("isVisible", true);
expect(view.$("span").is(".visible")).toBe(true);
});
it('should thumbs-bind-event on nested views to the parent view', function () {
var changeSpy = sinon.spy(),
destroySpy = sinon.spy(),
syncSpy = sinon.spy(),
errorSpy = sinon.spy();
var TestModel = Thumbs.Model.extend({});
var SubView = Thumbs.View.extend({});
var TestView = Thumbs.TemplateView.extend({
template: '<div data-thumbs-el data-thumbs-bind-event="change:modelChange destroy:modelDestroy sync:modelSync error:modelError">' +
' <button data-thumbs-bind="val:lastName"></button>' +
'</div>',
SubView: SubView,
modelChange: changeSpy,
modelDestroy: destroySpy,
modelSync: syncSpy,
modelError: errorSpy
});
var model = new TestModel({lastName:"test"});
var view = new TestView({model: model});
view.render();
model.trigger("change");
expect(changeSpy).toHaveBeenCalledOnce();
expect(destroySpy).toHaveNotBeenCalled();
expect(syncSpy).toHaveNotBeenCalled();
expect(errorSpy).toHaveNotBeenCalled();
model.trigger("sync");
expect(changeSpy).toHaveBeenCalledOnce();
expect(syncSpy).toHaveBeenCalledOnce();
expect(errorSpy).toHaveNotBeenCalled();
expect(destroySpy).toHaveNotBeenCalled();
model.trigger("error");
expect(changeSpy).toHaveBeenCalledOnce();
expect(syncSpy).toHaveBeenCalledOnce();
expect(errorSpy).toHaveBeenCalledOnce();
expect(destroySpy).toHaveNotBeenCalled();
model.trigger("destroy");
expect(changeSpy).toHaveBeenCalledOnce();
expect(syncSpy).toHaveBeenCalledOnce();
expect(errorSpy).toHaveBeenCalledOnce();
expect(destroySpy).toHaveBeenCalledOnce();
});
});
describe("nested identifiers", function () {
it('should set thumbs-id on nested views to the parent and not the child', function () {
var SubView = Thumbs.View.extend({});
var TestView = Thumbs.TemplateView.extend({
template: '<div data-thumbs-id="subView" data-thumbs-view="SubView"><a data-thumbs-id="link">Link</a></div>',
SubView: SubView
});
var view = new TestView();
view.render();
expect(view.$link).toBeDefined();
expect(view.link).toBeDefined();
expect(view.subView.link).toBeUndefined();
});
});
describe("nested formatters", function () {
it('should use formatters on the parent to format the nested ', function () {
var TestModel = Thumbs.Model.extend({});
var SubView = Thumbs.View.extend({});
var TestView = Thumbs.TemplateView.extend({
template: '<div data-thumbs-id="subView" data-thumbs-view="SubView">' +
'<div data-thumbs-format="upperCase"><%= firstName %></div>' +
'<div data-thumbs-format="lowerCase"><%= lastName %></div></div>',
SubView: SubView,
upperCase: function (data) {
return data.toUpperCase();
},
lowerCase: function (data) {
return data.toLowerCase();
}
});
var model = new TestModel({firstName: "bob", lastName: "YUKON"});
var view = new TestView({ model: model });
view.render();
expect(view.$('[data-thumbs-format="upperCase"]')).toHaveText("BOB");
expect(view.$('[data-thumbs-format="lowerCase"]')).toHaveText("yukon");
});
});
}); |
(google_async_config = window.google_async_config || {})['ca-pub-0826595092783671'] = {"sra_enabled":false}; |
import EventEmitter from 'events'
import {Assertion, TestStart, TestEnd, SuiteStart, SuiteEnd} from '../Data.js'
export default class MochaAdapter extends EventEmitter {
constructor (mocha) {
super()
this.mocha = mocha
this.origReporter = mocha._reporter
mocha.reporter((runner) => {
this.runner = runner
// eslint-disable-next-line no-unused-vars
let origReporterInstance = new (this.origReporter.bind(this.mocha,
this.runner))()
runner.on('start', this.onStart.bind(this))
runner.on('suite', this.onSuite.bind(this))
runner.on('test', this.onTest.bind(this))
runner.on('pending', this.onPending.bind(this))
runner.on('fail', this.onFail.bind(this))
runner.on('test end', this.onTestEnd.bind(this))
runner.on('suite end', this.onSuiteEnd.bind(this))
runner.on('end', this.onEnd.bind(this))
})
}
convertToSuiteStart (mochaSuite) {
return new SuiteStart(
mochaSuite.title,
this.buildSuiteFullName(mochaSuite),
mochaSuite.tests.map(this.convertTest.bind(this)),
mochaSuite.suites.map(this.convertToSuiteStart.bind(this))
)
}
convertToSuiteEnd (mochaSuite) {
return new SuiteEnd(
mochaSuite.title,
this.buildSuiteFullName(mochaSuite),
mochaSuite.tests.map(this.convertTest.bind(this)),
mochaSuite.suites.map(this.convertToSuiteEnd.bind(this))
)
}
convertTest (mochaTest) {
var suiteName
var fullName
if (!mochaTest.parent.root) {
suiteName = mochaTest.parent.title
fullName = this.buildSuiteFullName(mochaTest.parent)
// Add also the test name.
fullName.push(mochaTest.title)
} else {
fullName = [mochaTest.title]
}
// If the test has the errors attached a "test end" must be emitted, else
// a "test start".
if (mochaTest.errors !== undefined) {
var status = (mochaTest.state === undefined) ? 'skipped' : mochaTest.state
let errors = []
mochaTest.errors.forEach(function (error) {
errors.push(new Assertion(false, error.actual, error.expected,
error.message || error.toString(), error.stack))
})
// Test end, for the assertions property pass an empty array.
return new TestEnd(mochaTest.title, suiteName, fullName, status,
mochaTest.duration, errors, errors)
}
// Test start.
return new TestStart(mochaTest.title, suiteName, fullName)
}
/**
* Builds an array with the names of nested suites.
*/
buildSuiteFullName (mochaSuite) {
var fullName = []
var parent = mochaSuite.parent
if (!mochaSuite.root) {
fullName.push(mochaSuite.title)
}
while (parent && !parent.root) {
fullName.unshift(parent.title)
parent = parent.parent
}
return fullName
}
onStart () {
var globalSuiteStart = this.convertToSuiteStart(this.runner.suite)
globalSuiteStart.name = undefined
this.emit('runStart', globalSuiteStart)
}
onSuite (mochaSuite) {
if (!mochaSuite.root) {
this.emit('suiteStart', this.convertToSuiteStart(mochaSuite))
}
}
onTest (mochaTest) {
this.errors = []
this.emit('testStart', this.convertTest(mochaTest))
}
/**
* Emits the start of pending tests, because Mocha does not emit skipped tests
* on its "test" event.
*/
onPending (mochaTest) {
this.emit('testStart', this.convertTest(mochaTest))
}
onFail (test, error) {
this.errors.push(error)
}
onTestEnd (mochaTest) {
// Save the errors on Mocha's test object, because when the suite that
// contains this test is emitted on the "suiteEnd" event, it should contain
// also this test with all its details (errors, status, runtime). Runtime
// and status are already attached to the test, but the errors don't.
mochaTest.errors = this.errors
this.emit('testEnd', this.convertTest(mochaTest))
}
onSuiteEnd (mochaSuite) {
if (!mochaSuite.root) {
this.emit('suiteEnd', this.convertToSuiteEnd(mochaSuite))
}
}
onEnd () {
var globalSuiteEnd = this.convertToSuiteEnd(this.runner.suite)
globalSuiteEnd.name = undefined
this.emit('runEnd', globalSuiteEnd)
}
}
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.17/esri/copyright.txt for details.
//>>built
require({cache:{"url:esri/dijit/metadata/types/arcgis/common/templates/LanguageCode.html":'\x3cdiv data-dojo-attach-point\x3d"containerNode"\x3e\r\n \x3cdiv data-dojo-type\x3d"esri/dijit/metadata/form/Element"\r\n data-dojo-props\x3d"target:\'languageCode\',minOccurs:0,showHeader:false"\x3e\r\n \x3cdiv data-dojo-type\x3d"esri/dijit/metadata/form/Attribute"\r\n data-dojo-props\x3d"target:\'value\',minOccurs:0,showHeader:false"\x3e\r\n \x3cdiv data-dojo-type\x3d"esri/dijit/metadata/types/arcgis/form/InputSelectCode"\r\n data-dojo-props\x3d"codelistType:\'LanguageCode\'"\x3e\r\n \x3c/div\x3e\r\n \x3c/div\x3e\r\n \x3c/div\x3e\r\n\x3c/div\x3e'}});
define("esri/dijit/metadata/types/arcgis/common/LanguageCode","dojo/_base/declare dojo/_base/lang dojo/has ../../../../../kernel ../../../base/Descriptor dojo/text!./templates/LanguageCode.html".split(" "),function(a,b,c,d,e,f){a=a(e,{templateString:f});c("extend-esri")&&b.setObject("dijit.metadata.types.arcgis.common.LanguageCode",a,d);return a}); |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.i18next = factory());
}(this, function () { 'use strict';
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
function _typeof(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
_typeof = function _typeof(obj) {
return _typeof2(obj);
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
var consoleLogger = {
type: 'logger',
log: function log(args) {
this.output('log', args);
},
warn: function warn(args) {
this.output('warn', args);
},
error: function error(args) {
this.output('error', args);
},
output: function output(type, args) {
var _console;
/* eslint no-console: 0 */
if (console && console[type]) (_console = console)[type].apply(_console, _toConsumableArray(args));
}
};
var Logger =
/*#__PURE__*/
function () {
function Logger(concreteLogger) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Logger);
this.init(concreteLogger, options);
}
_createClass(Logger, [{
key: "init",
value: function init(concreteLogger) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
this.prefix = options.prefix || 'i18next:';
this.logger = concreteLogger || consoleLogger;
this.options = options;
this.debug = options.debug;
}
}, {
key: "setDebug",
value: function setDebug(bool) {
this.debug = bool;
}
}, {
key: "log",
value: function log() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return this.forward(args, 'log', '', true);
}
}, {
key: "warn",
value: function warn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return this.forward(args, 'warn', '', true);
}
}, {
key: "error",
value: function error() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return this.forward(args, 'error', '');
}
}, {
key: "deprecate",
value: function deprecate() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);
}
}, {
key: "forward",
value: function forward(args, lvl, prefix, debugOnly) {
if (debugOnly && !this.debug) return null;
if (typeof args[0] === 'string') args[0] = "".concat(prefix).concat(this.prefix, " ").concat(args[0]);
return this.logger[lvl](args);
}
}, {
key: "create",
value: function create(moduleName) {
return new Logger(this.logger, _objectSpread({}, {
prefix: "".concat(this.prefix, ":").concat(moduleName, ":")
}, this.options));
}
}]);
return Logger;
}();
var baseLogger = new Logger();
var EventEmitter =
/*#__PURE__*/
function () {
function EventEmitter() {
_classCallCheck(this, EventEmitter);
this.observers = {};
}
_createClass(EventEmitter, [{
key: "on",
value: function on(events, listener) {
var _this = this;
events.split(' ').forEach(function (event) {
_this.observers[event] = _this.observers[event] || [];
_this.observers[event].push(listener);
});
return this;
}
}, {
key: "off",
value: function off(event, listener) {
if (!this.observers[event]) return;
if (!listener) {
delete this.observers[event];
return;
}
this.observers[event] = this.observers[event].filter(function (l) {
return l !== listener;
});
}
}, {
key: "emit",
value: function emit(event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (this.observers[event]) {
var cloned = [].concat(this.observers[event]);
cloned.forEach(function (observer) {
observer.apply(void 0, args);
});
}
if (this.observers['*']) {
var _cloned = [].concat(this.observers['*']);
_cloned.forEach(function (observer) {
observer.apply(observer, [event].concat(args));
});
}
}
}]);
return EventEmitter;
}();
// http://lea.verou.me/2016/12/resolve-promises-externally-with-this-one-weird-trick/
function defer() {
var res;
var rej;
var promise = new Promise(function (resolve, reject) {
res = resolve;
rej = reject;
});
promise.resolve = res;
promise.reject = rej;
return promise;
}
function makeString(object) {
if (object == null) return '';
/* eslint prefer-template: 0 */
return '' + object;
}
function copy(a, s, t) {
a.forEach(function (m) {
if (s[m]) t[m] = s[m];
});
}
function getLastOfPath(object, path, Empty) {
function cleanKey(key) {
return key && key.indexOf('###') > -1 ? key.replace(/###/g, '.') : key;
}
function canNotTraverseDeeper() {
return !object || typeof object === 'string';
}
var stack = typeof path !== 'string' ? [].concat(path) : path.split('.');
while (stack.length > 1) {
if (canNotTraverseDeeper()) return {};
var key = cleanKey(stack.shift());
if (!object[key] && Empty) object[key] = new Empty();
object = object[key];
}
if (canNotTraverseDeeper()) return {};
return {
obj: object,
k: cleanKey(stack.shift())
};
}
function setPath(object, path, newValue) {
var _getLastOfPath = getLastOfPath(object, path, Object),
obj = _getLastOfPath.obj,
k = _getLastOfPath.k;
obj[k] = newValue;
}
function pushPath(object, path, newValue, concat) {
var _getLastOfPath2 = getLastOfPath(object, path, Object),
obj = _getLastOfPath2.obj,
k = _getLastOfPath2.k;
obj[k] = obj[k] || [];
if (concat) obj[k] = obj[k].concat(newValue);
if (!concat) obj[k].push(newValue);
}
function getPath(object, path) {
var _getLastOfPath3 = getLastOfPath(object, path),
obj = _getLastOfPath3.obj,
k = _getLastOfPath3.k;
if (!obj) return undefined;
return obj[k];
}
function getPathWithDefaults(data, defaultData, key) {
var value = getPath(data, key);
if (value !== undefined) {
return value;
} // Fallback to default values
return getPath(defaultData, key);
}
function deepExtend(target, source, overwrite) {
/* eslint no-restricted-syntax: 0 */
for (var prop in source) {
if (prop in target) {
// If we reached a leaf string in target or source then replace with source or skip depending on the 'overwrite' switch
if (typeof target[prop] === 'string' || target[prop] instanceof String || typeof source[prop] === 'string' || source[prop] instanceof String) {
if (overwrite) target[prop] = source[prop];
} else {
deepExtend(target[prop], source[prop], overwrite);
}
} else {
target[prop] = source[prop];
}
}
return target;
}
function regexEscape(str) {
/* eslint no-useless-escape: 0 */
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
/* eslint-disable */
var _entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
/* eslint-enable */
function escape(data) {
if (typeof data === 'string') {
return data.replace(/[&<>"'\/]/g, function (s) {
return _entityMap[s];
});
}
return data;
}
var isIE10 = typeof window !== 'undefined' && window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1;
var ResourceStore =
/*#__PURE__*/
function (_EventEmitter) {
_inherits(ResourceStore, _EventEmitter);
function ResourceStore(data) {
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
ns: ['translation'],
defaultNS: 'translation'
};
_classCallCheck(this, ResourceStore);
_this = _possibleConstructorReturn(this, _getPrototypeOf(ResourceStore).call(this));
if (isIE10) {
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
}
_this.data = data || {};
_this.options = options;
if (_this.options.keySeparator === undefined) {
_this.options.keySeparator = '.';
}
return _this;
}
_createClass(ResourceStore, [{
key: "addNamespaces",
value: function addNamespaces(ns) {
if (this.options.ns.indexOf(ns) < 0) {
this.options.ns.push(ns);
}
}
}, {
key: "removeNamespaces",
value: function removeNamespaces(ns) {
var index = this.options.ns.indexOf(ns);
if (index > -1) {
this.options.ns.splice(index, 1);
}
}
}, {
key: "getResource",
value: function getResource(lng, ns, key) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
var path = [lng, ns];
if (key && typeof key !== 'string') path = path.concat(key);
if (key && typeof key === 'string') path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf('.') > -1) {
path = lng.split('.');
}
return getPath(this.data, path);
}
}, {
key: "addResource",
value: function addResource(lng, ns, key, value) {
var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
silent: false
};
var keySeparator = this.options.keySeparator;
if (keySeparator === undefined) keySeparator = '.';
var path = [lng, ns];
if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf('.') > -1) {
path = lng.split('.');
value = ns;
ns = path[1];
}
this.addNamespaces(ns);
setPath(this.data, path, value);
if (!options.silent) this.emit('added', lng, ns, key, value);
}
}, {
key: "addResources",
value: function addResources(lng, ns, resources) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
silent: false
};
/* eslint no-restricted-syntax: 0 */
for (var m in resources) {
if (typeof resources[m] === 'string' || Object.prototype.toString.apply(resources[m]) === '[object Array]') this.addResource(lng, ns, m, resources[m], {
silent: true
});
}
if (!options.silent) this.emit('added', lng, ns, resources);
}
}, {
key: "addResourceBundle",
value: function addResourceBundle(lng, ns, resources, deep, overwrite) {
var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {
silent: false
};
var path = [lng, ns];
if (lng.indexOf('.') > -1) {
path = lng.split('.');
deep = resources;
resources = ns;
ns = path[1];
}
this.addNamespaces(ns);
var pack = getPath(this.data, path) || {};
if (deep) {
deepExtend(pack, resources, overwrite);
} else {
pack = _objectSpread({}, pack, resources);
}
setPath(this.data, path, pack);
if (!options.silent) this.emit('added', lng, ns, resources);
}
}, {
key: "removeResourceBundle",
value: function removeResourceBundle(lng, ns) {
if (this.hasResourceBundle(lng, ns)) {
delete this.data[lng][ns];
}
this.removeNamespaces(ns);
this.emit('removed', lng, ns);
}
}, {
key: "hasResourceBundle",
value: function hasResourceBundle(lng, ns) {
return this.getResource(lng, ns) !== undefined;
}
}, {
key: "getResourceBundle",
value: function getResourceBundle(lng, ns) {
if (!ns) ns = this.options.defaultNS; // COMPATIBILITY: remove extend in v2.1.0
if (this.options.compatibilityAPI === 'v1') return _objectSpread({}, {}, this.getResource(lng, ns));
return this.getResource(lng, ns);
}
}, {
key: "getDataByLanguage",
value: function getDataByLanguage(lng) {
return this.data[lng];
}
}, {
key: "toJSON",
value: function toJSON() {
return this.data;
}
}]);
return ResourceStore;
}(EventEmitter);
var postProcessor = {
processors: {},
addPostProcessor: function addPostProcessor(module) {
this.processors[module.name] = module;
},
handle: function handle(processors, value, key, options, translator) {
var _this = this;
processors.forEach(function (processor) {
if (_this.processors[processor]) value = _this.processors[processor].process(value, key, options, translator);
});
return value;
}
};
var checkedLoadedFor = {};
var Translator =
/*#__PURE__*/
function (_EventEmitter) {
_inherits(Translator, _EventEmitter);
function Translator(services) {
var _this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, Translator);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Translator).call(this));
if (isIE10) {
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
}
copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, _assertThisInitialized(_this));
_this.options = options;
if (_this.options.keySeparator === undefined) {
_this.options.keySeparator = '.';
}
_this.logger = baseLogger.create('translator');
return _this;
}
_createClass(Translator, [{
key: "changeLanguage",
value: function changeLanguage(lng) {
if (lng) this.language = lng;
}
}, {
key: "exists",
value: function exists(key) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
interpolation: {}
};
var resolved = this.resolve(key, options);
return resolved && resolved.res !== undefined;
}
}, {
key: "extractFromKey",
value: function extractFromKey(key, options) {
var nsSeparator = options.nsSeparator || this.options.nsSeparator;
if (nsSeparator === undefined) nsSeparator = ':';
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;
var namespaces = options.ns || this.options.defaultNS;
if (nsSeparator && key.indexOf(nsSeparator) > -1) {
var parts = key.split(nsSeparator);
if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();
key = parts.join(keySeparator);
}
if (typeof namespaces === 'string') namespaces = [namespaces];
return {
key: key,
namespaces: namespaces
};
}
}, {
key: "translate",
value: function translate(keys, options) {
var _this2 = this;
if (_typeof(options) !== 'object' && this.options.overloadTranslationOptionHandler) {
/* eslint prefer-rest-params: 0 */
options = this.options.overloadTranslationOptionHandler(arguments);
}
if (!options) options = {}; // non valid keys handling
if (keys === undefined || keys === null
/* || keys === ''*/
) return '';
if (!Array.isArray(keys)) keys = [String(keys)]; // separators
var keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator; // get namespace(s)
var _this$extractFromKey = this.extractFromKey(keys[keys.length - 1], options),
key = _this$extractFromKey.key,
namespaces = _this$extractFromKey.namespaces;
var namespace = namespaces[namespaces.length - 1]; // return key on CIMode
var lng = options.lng || this.language;
var appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
if (lng && lng.toLowerCase() === 'cimode') {
if (appendNamespaceToCIMode) {
var nsSeparator = options.nsSeparator || this.options.nsSeparator;
return namespace + nsSeparator + key;
}
return key;
} // resolve from store
var resolved = this.resolve(keys, options);
var res = resolved && resolved.res;
var resUsedKey = resolved && resolved.usedKey || key;
var resExactUsedKey = resolved && resolved.exactUsedKey || key;
var resType = Object.prototype.toString.apply(res);
var noObject = ['[object Number]', '[object Function]', '[object RegExp]'];
var joinArrays = options.joinArrays !== undefined ? options.joinArrays : this.options.joinArrays; // object
var handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
var handleAsObject = typeof res !== 'string' && typeof res !== 'boolean' && typeof res !== 'number';
if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === 'string' && resType === '[object Array]')) {
if (!options.returnObjects && !this.options.returnObjects) {
this.logger.warn('accessing an object - but returnObjects options is not enabled!');
return this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, options) : "key '".concat(key, " (").concat(this.language, ")' returned an object instead of string.");
} // if we got a separator we loop over children - else we just return object as is
// as having it set to false means no hierarchy so no lookup for nested values
if (keySeparator) {
var resTypeIsArray = resType === '[object Array]';
var copy$$1 = resTypeIsArray ? [] : {}; // apply child translation on a copy
/* eslint no-restricted-syntax: 0 */
var newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
for (var m in res) {
if (Object.prototype.hasOwnProperty.call(res, m)) {
var deepKey = "".concat(newKeyToUse).concat(keySeparator).concat(m);
copy$$1[m] = this.translate(deepKey, _objectSpread({}, options, {
joinArrays: false,
ns: namespaces
}));
if (copy$$1[m] === deepKey) copy$$1[m] = res[m]; // if nothing found use orginal value as fallback
}
}
res = copy$$1;
}
} else if (handleAsObjectInI18nFormat && typeof joinArrays === 'string' && resType === '[object Array]') {
// array special treatment
res = res.join(joinArrays);
if (res) res = this.extendTranslation(res, keys, options);
} else {
// string, empty or null
var usedDefault = false;
var usedKey = false; // fallback value
if (!this.isValidLookup(res) && options.defaultValue !== undefined) {
usedDefault = true;
if (options.count !== undefined) {
var suffix = this.pluralResolver.getSuffix(lng, options.count);
res = options["defaultValue".concat(suffix)];
}
if (!res) res = options.defaultValue;
}
if (!this.isValidLookup(res)) {
usedKey = true;
res = key;
} // save missing
var updateMissing = options.defaultValue && options.defaultValue !== res && this.options.updateMissing;
if (usedKey || usedDefault || updateMissing) {
this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? options.defaultValue : res);
var lngs = [];
var fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {
for (var i = 0; i < fallbackLngs.length; i++) {
lngs.push(fallbackLngs[i]);
}
} else if (this.options.saveMissingTo === 'all') {
lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
} else {
lngs.push(options.lng || this.language);
}
var send = function send(l, k) {
if (_this2.options.missingKeyHandler) {
_this2.options.missingKeyHandler(l, namespace, k, updateMissing ? options.defaultValue : res, updateMissing, options);
} else if (_this2.backendConnector && _this2.backendConnector.saveMissing) {
_this2.backendConnector.saveMissing(l, namespace, k, updateMissing ? options.defaultValue : res, updateMissing, options);
}
_this2.emit('missingKey', l, namespace, k, res);
};
if (this.options.saveMissing) {
var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
if (this.options.saveMissingPlurals && needsPluralHandling) {
lngs.forEach(function (l) {
var plurals = _this2.pluralResolver.getPluralFormsOfKey(l, key);
plurals.forEach(function (p) {
return send([l], p);
});
});
} else {
send(lngs, key);
}
}
} // extend
res = this.extendTranslation(res, keys, options, resolved); // append namespace if still key
if (usedKey && res === key && this.options.appendNamespaceToMissingKey) res = "".concat(namespace, ":").concat(key); // parseMissingKeyHandler
if (usedKey && this.options.parseMissingKeyHandler) res = this.options.parseMissingKeyHandler(res);
} // return
return res;
}
}, {
key: "extendTranslation",
value: function extendTranslation(res, key, options, resolved) {
var _this3 = this;
if (this.i18nFormat && this.i18nFormat.parse) {
res = this.i18nFormat.parse(res, options, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
resolved: resolved
});
} else if (!options.skipInterpolation) {
// i18next.parsing
if (options.interpolation) this.interpolator.init(_objectSpread({}, options, {
interpolation: _objectSpread({}, this.options.interpolation, options.interpolation)
})); // interpolate
var data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
if (this.options.interpolation.defaultVariables) data = _objectSpread({}, this.options.interpolation.defaultVariables, data);
res = this.interpolator.interpolate(res, data, options.lng || this.language, options); // nesting
if (options.nest !== false) res = this.interpolator.nest(res, function () {
return _this3.translate.apply(_this3, arguments);
}, options);
if (options.interpolation) this.interpolator.reset();
} // post process
var postProcess = options.postProcess || this.options.postProcess;
var postProcessorNames = typeof postProcess === 'string' ? [postProcess] : postProcess;
if (res !== undefined && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? _objectSpread({
i18nResolved: resolved
}, options) : options, this);
}
return res;
}
}, {
key: "resolve",
value: function resolve(keys) {
var _this4 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var found;
var usedKey; // plain key
var exactUsedKey; // key with context / plural
var usedLng;
var usedNS;
if (typeof keys === 'string') keys = [keys]; // forEach possible key
keys.forEach(function (k) {
if (_this4.isValidLookup(found)) return;
var extracted = _this4.extractFromKey(k, options);
var key = extracted.key;
usedKey = key;
var namespaces = extracted.namespaces;
if (_this4.options.fallbackNS) namespaces = namespaces.concat(_this4.options.fallbackNS);
var needsPluralHandling = options.count !== undefined && typeof options.count !== 'string';
var needsContextHandling = options.context !== undefined && typeof options.context === 'string' && options.context !== '';
var codes = options.lngs ? options.lngs : _this4.languageUtils.toResolveHierarchy(options.lng || _this4.language, options.fallbackLng);
namespaces.forEach(function (ns) {
if (_this4.isValidLookup(found)) return;
usedNS = ns;
if (!checkedLoadedFor["".concat(codes[0], "-").concat(ns)] && _this4.utils && _this4.utils.hasLoadedNamespace && !_this4.utils.hasLoadedNamespace(usedNS)) {
checkedLoadedFor["".concat(codes[0], "-").concat(ns)] = true;
_this4.logger.warn("key \"".concat(usedKey, "\" for namespace \"").concat(usedNS, "\" for languages \"").concat(codes.join(', '), "\" won't get resolved as namespace was not yet loaded"), 'This means something IS WRONG in your application setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
}
codes.forEach(function (code) {
if (_this4.isValidLookup(found)) return;
usedLng = code;
var finalKey = key;
var finalKeys = [finalKey];
if (_this4.i18nFormat && _this4.i18nFormat.addLookupKeys) {
_this4.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
} else {
var pluralSuffix;
if (needsPluralHandling) pluralSuffix = _this4.pluralResolver.getSuffix(code, options.count); // fallback for plural if context not found
if (needsPluralHandling && needsContextHandling) finalKeys.push(finalKey + pluralSuffix); // get key for context if needed
if (needsContextHandling) finalKeys.push(finalKey += "".concat(_this4.options.contextSeparator).concat(options.context)); // get key for plural if needed
if (needsPluralHandling) finalKeys.push(finalKey += pluralSuffix);
} // iterate over finalKeys starting with most specific pluralkey (-> contextkey only) -> singularkey only
var possibleKey;
/* eslint no-cond-assign: 0 */
while (possibleKey = finalKeys.pop()) {
if (!_this4.isValidLookup(found)) {
exactUsedKey = possibleKey;
found = _this4.getResource(code, ns, possibleKey, options);
}
}
});
});
});
return {
res: found,
usedKey: usedKey,
exactUsedKey: exactUsedKey,
usedLng: usedLng,
usedNS: usedNS
};
}
}, {
key: "isValidLookup",
value: function isValidLookup(res) {
return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');
}
}, {
key: "getResource",
value: function getResource(code, ns, key) {
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (this.i18nFormat && this.i18nFormat.getResource) return this.i18nFormat.getResource(code, ns, key, options);
return this.resourceStore.getResource(code, ns, key, options);
}
}]);
return Translator;
}(EventEmitter);
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var LanguageUtil =
/*#__PURE__*/
function () {
function LanguageUtil(options) {
_classCallCheck(this, LanguageUtil);
this.options = options;
this.whitelist = this.options.whitelist || false;
this.logger = baseLogger.create('languageUtils');
}
_createClass(LanguageUtil, [{
key: "getScriptPartFromCode",
value: function getScriptPartFromCode(code) {
if (!code || code.indexOf('-') < 0) return null;
var p = code.split('-');
if (p.length === 2) return null;
p.pop();
return this.formatLanguageCode(p.join('-'));
}
}, {
key: "getLanguagePartFromCode",
value: function getLanguagePartFromCode(code) {
if (!code || code.indexOf('-') < 0) return code;
var p = code.split('-');
return this.formatLanguageCode(p[0]);
}
}, {
key: "formatLanguageCode",
value: function formatLanguageCode(code) {
// http://www.iana.org/assignments/language-tags/language-tags.xhtml
if (typeof code === 'string' && code.indexOf('-') > -1) {
var specialCases = ['hans', 'hant', 'latn', 'cyrl', 'cans', 'mong', 'arab'];
var p = code.split('-');
if (this.options.lowerCaseLng) {
p = p.map(function (part) {
return part.toLowerCase();
});
} else if (p.length === 2) {
p[0] = p[0].toLowerCase();
p[1] = p[1].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
} else if (p.length === 3) {
p[0] = p[0].toLowerCase(); // if lenght 2 guess it's a country
if (p[1].length === 2) p[1] = p[1].toUpperCase();
if (p[0] !== 'sgn' && p[2].length === 2) p[2] = p[2].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1) p[1] = capitalize(p[1].toLowerCase());
if (specialCases.indexOf(p[2].toLowerCase()) > -1) p[2] = capitalize(p[2].toLowerCase());
}
return p.join('-');
}
return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
}
}, {
key: "isWhitelisted",
value: function isWhitelisted(code) {
if (this.options.load === 'languageOnly' || this.options.nonExplicitWhitelist) {
code = this.getLanguagePartFromCode(code);
}
return !this.whitelist || !this.whitelist.length || this.whitelist.indexOf(code) > -1;
}
}, {
key: "getFallbackCodes",
value: function getFallbackCodes(fallbacks, code) {
if (!fallbacks) return [];
if (typeof fallbacks === 'string') fallbacks = [fallbacks];
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') return fallbacks;
if (!code) return fallbacks["default"] || []; // asume we have an object defining fallbacks
var found = fallbacks[code];
if (!found) found = fallbacks[this.getScriptPartFromCode(code)];
if (!found) found = fallbacks[this.formatLanguageCode(code)];
if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];
if (!found) found = fallbacks["default"];
return found || [];
}
}, {
key: "toResolveHierarchy",
value: function toResolveHierarchy(code, fallbackCode) {
var _this = this;
var fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
var codes = [];
var addCode = function addCode(c) {
if (!c) return;
if (_this.isWhitelisted(c)) {
codes.push(c);
} else {
_this.logger.warn("rejecting non-whitelisted language code: ".concat(c));
}
};
if (typeof code === 'string' && code.indexOf('-') > -1) {
if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));
if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));
if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));
} else if (typeof code === 'string') {
addCode(this.formatLanguageCode(code));
}
fallbackCodes.forEach(function (fc) {
if (codes.indexOf(fc) < 0) addCode(_this.formatLanguageCode(fc));
});
return codes;
}
}]);
return LanguageUtil;
}();
/* eslint-disable */
var sets = [{
lngs: ['ach', 'ak', 'am', 'arn', 'br', 'fil', 'gun', 'ln', 'mfe', 'mg', 'mi', 'oc', 'pt', 'pt-BR', 'tg', 'ti', 'tr', 'uz', 'wa'],
nr: [1, 2],
fc: 1
}, {
lngs: ['af', 'an', 'ast', 'az', 'bg', 'bn', 'ca', 'da', 'de', 'dev', 'el', 'en', 'eo', 'es', 'et', 'eu', 'fi', 'fo', 'fur', 'fy', 'gl', 'gu', 'ha', 'hi', 'hu', 'hy', 'ia', 'it', 'kn', 'ku', 'lb', 'mai', 'ml', 'mn', 'mr', 'nah', 'nap', 'nb', 'ne', 'nl', 'nn', 'no', 'nso', 'pa', 'pap', 'pms', 'ps', 'pt-PT', 'rm', 'sco', 'se', 'si', 'so', 'son', 'sq', 'sv', 'sw', 'ta', 'te', 'tk', 'ur', 'yo'],
nr: [1, 2],
fc: 2
}, {
lngs: ['ay', 'bo', 'cgg', 'fa', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky', 'lo', 'ms', 'sah', 'su', 'th', 'tt', 'ug', 'vi', 'wo', 'zh'],
nr: [1],
fc: 3
}, {
lngs: ['be', 'bs', 'cnr', 'dz', 'hr', 'ru', 'sr', 'uk'],
nr: [1, 2, 5],
fc: 4
}, {
lngs: ['ar'],
nr: [0, 1, 2, 3, 11, 100],
fc: 5
}, {
lngs: ['cs', 'sk'],
nr: [1, 2, 5],
fc: 6
}, {
lngs: ['csb', 'pl'],
nr: [1, 2, 5],
fc: 7
}, {
lngs: ['cy'],
nr: [1, 2, 3, 8],
fc: 8
}, {
lngs: ['fr'],
nr: [1, 2],
fc: 9
}, {
lngs: ['ga'],
nr: [1, 2, 3, 7, 11],
fc: 10
}, {
lngs: ['gd'],
nr: [1, 2, 3, 20],
fc: 11
}, {
lngs: ['is'],
nr: [1, 2],
fc: 12
}, {
lngs: ['jv'],
nr: [0, 1],
fc: 13
}, {
lngs: ['kw'],
nr: [1, 2, 3, 4],
fc: 14
}, {
lngs: ['lt'],
nr: [1, 2, 10],
fc: 15
}, {
lngs: ['lv'],
nr: [1, 2, 0],
fc: 16
}, {
lngs: ['mk'],
nr: [1, 2],
fc: 17
}, {
lngs: ['mnk'],
nr: [0, 1, 2],
fc: 18
}, {
lngs: ['mt'],
nr: [1, 2, 11, 20],
fc: 19
}, {
lngs: ['or'],
nr: [2, 1],
fc: 2
}, {
lngs: ['ro'],
nr: [1, 2, 20],
fc: 20
}, {
lngs: ['sl'],
nr: [5, 1, 2, 3],
fc: 21
}, {
lngs: ['he'],
nr: [1, 2, 20, 21],
fc: 22
}];
var _rulesPluralsTypes = {
1: function _(n) {
return Number(n > 1);
},
2: function _(n) {
return Number(n != 1);
},
3: function _(n) {
return 0;
},
4: function _(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
5: function _(n) {
return Number(n === 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
},
6: function _(n) {
return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
},
7: function _(n) {
return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
8: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
},
9: function _(n) {
return Number(n >= 2);
},
10: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
},
11: function _(n) {
return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
},
12: function _(n) {
return Number(n % 10 != 1 || n % 100 == 11);
},
13: function _(n) {
return Number(n !== 0);
},
14: function _(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
},
15: function _(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
16: function _(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
},
17: function _(n) {
return Number(n == 1 || n % 10 == 1 ? 0 : 1);
},
18: function _(n) {
return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
},
19: function _(n) {
return Number(n == 1 ? 0 : n === 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
},
20: function _(n) {
return Number(n == 1 ? 0 : n === 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
},
21: function _(n) {
return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
},
22: function _(n) {
return Number(n === 1 ? 0 : n === 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
}
};
/* eslint-enable */
function createRules() {
var rules = {};
sets.forEach(function (set) {
set.lngs.forEach(function (l) {
rules[l] = {
numbers: set.nr,
plurals: _rulesPluralsTypes[set.fc]
};
});
});
return rules;
}
var PluralResolver =
/*#__PURE__*/
function () {
function PluralResolver(languageUtils) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, PluralResolver);
this.languageUtils = languageUtils;
this.options = options;
this.logger = baseLogger.create('pluralResolver');
this.rules = createRules();
}
_createClass(PluralResolver, [{
key: "addRule",
value: function addRule(lng, obj) {
this.rules[lng] = obj;
}
}, {
key: "getRule",
value: function getRule(code) {
return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
}
}, {
key: "needsPlural",
value: function needsPlural(code) {
var rule = this.getRule(code);
return rule && rule.numbers.length > 1;
}
}, {
key: "getPluralFormsOfKey",
value: function getPluralFormsOfKey(code, key) {
var _this = this;
var ret = [];
var rule = this.getRule(code);
if (!rule) return ret;
rule.numbers.forEach(function (n) {
var suffix = _this.getSuffix(code, n);
ret.push("".concat(key).concat(suffix));
});
return ret;
}
}, {
key: "getSuffix",
value: function getSuffix(code, count) {
var _this2 = this;
var rule = this.getRule(code);
if (rule) {
// if (rule.numbers.length === 1) return ''; // only singular
var idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
var suffix = rule.numbers[idx]; // special treatment for lngs only having singular and plural
if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
if (suffix === 2) {
suffix = 'plural';
} else if (suffix === 1) {
suffix = '';
}
}
var returnSuffix = function returnSuffix() {
return _this2.options.prepend && suffix.toString() ? _this2.options.prepend + suffix.toString() : suffix.toString();
}; // COMPATIBILITY JSON
// v1
if (this.options.compatibilityJSON === 'v1') {
if (suffix === 1) return '';
if (typeof suffix === 'number') return "_plural_".concat(suffix.toString());
return returnSuffix();
} else if (
/* v2 */
this.options.compatibilityJSON === 'v2') {
return returnSuffix();
} else if (
/* v3 - gettext index */
this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
return returnSuffix();
}
return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
}
this.logger.warn("no plural rule found for: ".concat(code));
return '';
}
}]);
return PluralResolver;
}();
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _toArray(arr) {
return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
}
var Interpolator =
/*#__PURE__*/
function () {
function Interpolator() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Interpolator);
this.logger = baseLogger.create('interpolator');
this.options = options;
this.format = options.interpolation && options.interpolation.format || function (value) {
return value;
};
this.init(options);
}
/* eslint no-param-reassign: 0 */
_createClass(Interpolator, [{
key: "init",
value: function init() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!options.interpolation) options.interpolation = {
escapeValue: true
};
var iOpts = options.interpolation;
this.escape = iOpts.escape !== undefined ? iOpts.escape : escape;
this.escapeValue = iOpts.escapeValue !== undefined ? iOpts.escapeValue : true;
this.useRawValueToEscape = iOpts.useRawValueToEscape !== undefined ? iOpts.useRawValueToEscape : false;
this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || '{{';
this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || '}}';
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ',';
this.unescapePrefix = iOpts.unescapeSuffix ? '' : iOpts.unescapePrefix || '-';
this.unescapeSuffix = this.unescapePrefix ? '' : iOpts.unescapeSuffix || '';
this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape('$t(');
this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(')');
this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ',';
this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1000;
this.alwaysFormat = iOpts.alwaysFormat !== undefined ? iOpts.alwaysFormat : false; // the regexp
this.resetRegExp();
}
}, {
key: "reset",
value: function reset() {
if (this.options) this.init(this.options);
}
}, {
key: "resetRegExp",
value: function resetRegExp() {
// the regexp
var regexpStr = "".concat(this.prefix, "(.+?)").concat(this.suffix);
this.regexp = new RegExp(regexpStr, 'g');
var regexpUnescapeStr = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix);
this.regexpUnescape = new RegExp(regexpUnescapeStr, 'g');
var nestingRegexpStr = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix);
this.nestingRegexp = new RegExp(nestingRegexpStr, 'g');
}
}, {
key: "interpolate",
value: function interpolate(str, data, lng, options) {
var _this = this;
var match;
var value;
var replaces;
var defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
function regexSafe(val) {
return val.replace(/\$/g, '$$$$');
}
var handleFormat = function handleFormat(key) {
if (key.indexOf(_this.formatSeparator) < 0) {
var path = getPathWithDefaults(data, defaultData, key);
return _this.alwaysFormat ? _this.format(path, undefined, lng) : path;
}
var p = key.split(_this.formatSeparator);
var k = p.shift().trim();
var f = p.join(_this.formatSeparator).trim();
return _this.format(getPathWithDefaults(data, defaultData, k), f, lng, options);
};
this.resetRegExp();
var missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
replaces = 0; // unescape if has unescapePrefix/Suffix
/* eslint no-cond-assign: 0 */
while (match = this.regexpUnescape.exec(str)) {
value = handleFormat(match[1].trim());
if (value === undefined) {
if (typeof missingInterpolationHandler === 'function') {
var temp = missingInterpolationHandler(str, match, options);
value = typeof temp === 'string' ? temp : '';
} else {
this.logger.warn("missed to pass in variable ".concat(match[1], " for interpolating ").concat(str));
value = '';
}
} else if (typeof value !== 'string' && !this.useRawValueToEscape) {
value = makeString(value);
}
str = str.replace(match[0], regexSafe(value));
this.regexpUnescape.lastIndex = 0;
replaces++;
if (replaces >= this.maxReplaces) {
break;
}
}
replaces = 0; // regular escape on demand
while (match = this.regexp.exec(str)) {
value = handleFormat(match[1].trim());
if (value === undefined) {
if (typeof missingInterpolationHandler === 'function') {
var _temp = missingInterpolationHandler(str, match, options);
value = typeof _temp === 'string' ? _temp : '';
} else {
this.logger.warn("missed to pass in variable ".concat(match[1], " for interpolating ").concat(str));
value = '';
}
} else if (typeof value !== 'string' && !this.useRawValueToEscape) {
value = makeString(value);
}
value = this.escapeValue ? regexSafe(this.escape(value)) : regexSafe(value);
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
replaces++;
if (replaces >= this.maxReplaces) {
break;
}
}
return str;
}
}, {
key: "nest",
value: function nest(str, fc) {
var _this2 = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var match;
var value;
var clonedOptions = _objectSpread({}, options);
clonedOptions.applyPostProcessor = false; // avoid post processing on nested lookup
delete clonedOptions.defaultValue; // assert we do not get a endless loop on interpolating defaultValue again and again
// if value is something like "myKey": "lorem $(anotherKey, { "count": {{aValueInOptions}} })"
function handleHasOptions(key, inheritedOptions) {
var sep = this.nestingOptionsSeparator;
if (key.indexOf(sep) < 0) return key;
var c = key.split(new RegExp("".concat(sep, "[ ]*{")));
var optionsString = "{".concat(c[1]);
key = c[0];
optionsString = this.interpolate(optionsString, clonedOptions);
optionsString = optionsString.replace(/'/g, '"');
try {
clonedOptions = JSON.parse(optionsString);
if (inheritedOptions) clonedOptions = _objectSpread({}, inheritedOptions, clonedOptions);
} catch (e) {
this.logger.warn("failed parsing options string in nesting for key ".concat(key), e);
return "".concat(key).concat(sep).concat(optionsString);
} // assert we do not get a endless loop on interpolating defaultValue again and again
delete clonedOptions.defaultValue;
return key;
} // regular escape on demand
while (match = this.nestingRegexp.exec(str)) {
var formatters = [];
/**
* If there is more than one parameter (contains the format separator). E.g.:
* - t(a, b)
* - t(a, b, c)
*
* And those parameters are not dynamic values (parameters do not include curly braces). E.g.:
* - Not t(a, { "key": "{{variable}}" })
* - Not t(a, b, {"keyA": "valueA", "keyB": "valueB"})
*/
if (match[0].includes(this.formatSeparator) && !/{.*}/.test(match[1])) {
var _match$1$split$map = match[1].split(this.formatSeparator).map(function (elem) {
return elem.trim();
});
var _match$1$split$map2 = _toArray(_match$1$split$map);
match[1] = _match$1$split$map2[0];
formatters = _match$1$split$map2.slice(1);
}
value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions); // is only the nesting key (key1 = '$(key2)') return the value without stringify
if (value && match[0] === str && typeof value !== 'string') return value; // no string to include or empty
if (typeof value !== 'string') value = makeString(value);
if (!value) {
this.logger.warn("missed to resolve ".concat(match[1], " for nesting ").concat(str));
value = '';
}
value = formatters.reduce(function (v, f) {
return _this2.format(v, f, options.lng, options);
}, value.trim()); // Nested keys should not be escaped by default #854
// value = this.escapeValue ? regexSafe(utils.escape(value)) : regexSafe(value);
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
}
return str;
}
}]);
return Interpolator;
}();
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function remove(arr, what) {
var found = arr.indexOf(what);
while (found !== -1) {
arr.splice(found, 1);
found = arr.indexOf(what);
}
}
var Connector =
/*#__PURE__*/
function (_EventEmitter) {
_inherits(Connector, _EventEmitter);
function Connector(backend, store, services) {
var _this;
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
_classCallCheck(this, Connector);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this));
if (isIE10) {
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
}
_this.backend = backend;
_this.store = store;
_this.services = services;
_this.languageUtils = services.languageUtils;
_this.options = options;
_this.logger = baseLogger.create('backendConnector');
_this.state = {};
_this.queue = [];
if (_this.backend && _this.backend.init) {
_this.backend.init(services, options.backend, options);
}
return _this;
}
_createClass(Connector, [{
key: "queueLoad",
value: function queueLoad(languages, namespaces, options, callback) {
var _this2 = this;
// find what needs to be loaded
var toLoad = [];
var pending = [];
var toLoadLanguages = [];
var toLoadNamespaces = [];
languages.forEach(function (lng) {
var hasAllNamespaces = true;
namespaces.forEach(function (ns) {
var name = "".concat(lng, "|").concat(ns);
if (!options.reload && _this2.store.hasResourceBundle(lng, ns)) {
_this2.state[name] = 2; // loaded
} else if (_this2.state[name] < 0) ; else if (_this2.state[name] === 1) {
if (pending.indexOf(name) < 0) pending.push(name);
} else {
_this2.state[name] = 1; // pending
hasAllNamespaces = false;
if (pending.indexOf(name) < 0) pending.push(name);
if (toLoad.indexOf(name) < 0) toLoad.push(name);
if (toLoadNamespaces.indexOf(ns) < 0) toLoadNamespaces.push(ns);
}
});
if (!hasAllNamespaces) toLoadLanguages.push(lng);
});
if (toLoad.length || pending.length) {
this.queue.push({
pending: pending,
loaded: {},
errors: [],
callback: callback
});
}
return {
toLoad: toLoad,
pending: pending,
toLoadLanguages: toLoadLanguages,
toLoadNamespaces: toLoadNamespaces
};
}
}, {
key: "loaded",
value: function loaded(name, err, data) {
var _name$split = name.split('|'),
_name$split2 = _slicedToArray(_name$split, 2),
lng = _name$split2[0],
ns = _name$split2[1];
if (err) this.emit('failedLoading', lng, ns, err);
if (data) {
this.store.addResourceBundle(lng, ns, data);
} // set loaded
this.state[name] = err ? -1 : 2; // consolidated loading done in this run - only emit once for a loaded namespace
var loaded = {}; // callback if ready
this.queue.forEach(function (q) {
pushPath(q.loaded, [lng], ns);
remove(q.pending, name);
if (err) q.errors.push(err);
if (q.pending.length === 0 && !q.done) {
// only do once per loaded -> this.emit('loaded', q.loaded);
Object.keys(q.loaded).forEach(function (l) {
if (!loaded[l]) loaded[l] = [];
if (q.loaded[l].length) {
q.loaded[l].forEach(function (ns) {
if (loaded[l].indexOf(ns) < 0) loaded[l].push(ns);
});
}
});
/* eslint no-param-reassign: 0 */
q.done = true;
if (q.errors.length) {
q.callback(q.errors);
} else {
q.callback();
}
}
}); // emit consolidated loaded event
this.emit('loaded', loaded); // remove done load requests
this.queue = this.queue.filter(function (q) {
return !q.done;
});
}
}, {
key: "read",
value: function read(lng, ns, fcName) {
var _this3 = this;
var tried = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var wait = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 350;
var callback = arguments.length > 5 ? arguments[5] : undefined;
if (!lng.length) return callback(null, {}); // noting to load
return this.backend[fcName](lng, ns, function (err, data) {
if (err && data
/* = retryFlag */
&& tried < 5) {
setTimeout(function () {
_this3.read.call(_this3, lng, ns, fcName, tried + 1, wait * 2, callback);
}, wait);
return;
}
callback(err, data);
});
}
/* eslint consistent-return: 0 */
}, {
key: "prepareLoading",
value: function prepareLoading(languages, namespaces) {
var _this4 = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var callback = arguments.length > 3 ? arguments[3] : undefined;
if (!this.backend) {
this.logger.warn('No backend was added via i18next.use. Will not load resources.');
return callback && callback();
}
if (typeof languages === 'string') languages = this.languageUtils.toResolveHierarchy(languages);
if (typeof namespaces === 'string') namespaces = [namespaces];
var toLoad = this.queueLoad(languages, namespaces, options, callback);
if (!toLoad.toLoad.length) {
if (!toLoad.pending.length) callback(); // nothing to load and no pendings...callback now
return null; // pendings will trigger callback
}
toLoad.toLoad.forEach(function (name) {
_this4.loadOne(name);
});
}
}, {
key: "load",
value: function load(languages, namespaces, callback) {
this.prepareLoading(languages, namespaces, {}, callback);
}
}, {
key: "reload",
value: function reload(languages, namespaces, callback) {
this.prepareLoading(languages, namespaces, {
reload: true
}, callback);
}
}, {
key: "loadOne",
value: function loadOne(name) {
var _this5 = this;
var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
var _name$split3 = name.split('|'),
_name$split4 = _slicedToArray(_name$split3, 2),
lng = _name$split4[0],
ns = _name$split4[1];
this.read(lng, ns, 'read', undefined, undefined, function (err, data) {
if (err) _this5.logger.warn("".concat(prefix, "loading namespace ").concat(ns, " for language ").concat(lng, " failed"), err);
if (!err && data) _this5.logger.log("".concat(prefix, "loaded namespace ").concat(ns, " for language ").concat(lng), data);
_this5.loaded(name, err, data);
});
}
}, {
key: "saveMissing",
value: function saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {};
if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
this.logger.warn("did not save key \"".concat(key, "\" for namespace \"").concat(namespace, "\" as the namespace was not yet loaded"), 'This means something IS WRONG in your application setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');
return;
} // ignore non valid keys
if (key === undefined || key === null || key === '') return;
if (this.backend && this.backend.create) {
this.backend.create(languages, namespace, key, fallbackValue, null
/* unused callback */
, _objectSpread({}, options, {
isUpdate: isUpdate
}));
} // write to store to avoid resending
if (!languages || !languages[0]) return;
this.store.addResource(languages[0], namespace, key, fallbackValue);
}
}]);
return Connector;
}(EventEmitter);
function get() {
return {
debug: false,
initImmediate: true,
ns: ['translation'],
defaultNS: ['translation'],
fallbackLng: ['dev'],
fallbackNS: false,
// string or array of namespaces
whitelist: false,
// array with whitelisted languages
nonExplicitWhitelist: false,
load: 'all',
// | currentOnly | languageOnly
preload: false,
// array with preload languages
simplifyPluralSuffix: true,
keySeparator: '.',
nsSeparator: ':',
pluralSeparator: '_',
contextSeparator: '_',
partialBundledLanguages: false,
// allow bundling certain languages that are not remotely fetched
saveMissing: false,
// enable to send missing values
updateMissing: false,
// enable to update default values if different from translated value (only useful on initial development, or when keeping code as source of truth)
saveMissingTo: 'fallback',
// 'current' || 'all'
saveMissingPlurals: true,
// will save all forms not only singular key
missingKeyHandler: false,
// function(lng, ns, key, fallbackValue) -> override if prefer on handling
missingInterpolationHandler: false,
// function(str, match)
postProcess: false,
// string or array of postProcessor names
postProcessPassResolved: false,
// pass resolved object into 'options.i18nResolved' for postprocessor
returnNull: true,
// allows null value as valid translation
returnEmptyString: true,
// allows empty string value as valid translation
returnObjects: false,
joinArrays: false,
// or string to join array
returnedObjectHandler: false,
// function(key, value, options) triggered if key returns object but returnObjects is set to false
parseMissingKeyHandler: false,
// function(key) parsed a key that was not found in t() before returning
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: function handle(args) {
var ret = {};
if (_typeof(args[1]) === 'object') ret = args[1];
if (typeof args[1] === 'string') ret.defaultValue = args[1];
if (typeof args[2] === 'string') ret.tDescription = args[2];
if (_typeof(args[2]) === 'object' || _typeof(args[3]) === 'object') {
var options = args[3] || args[2];
Object.keys(options).forEach(function (key) {
ret[key] = options[key];
});
}
return ret;
},
interpolation: {
escapeValue: true,
format: function format(value, _format, lng, options) {
return value;
},
prefix: '{{',
suffix: '}}',
formatSeparator: ',',
// prefixEscaped: '{{',
// suffixEscaped: '}}',
// unescapeSuffix: '',
unescapePrefix: '-',
nestingPrefix: '$t(',
nestingSuffix: ')',
nestingOptionsSeparator: ',',
// nestingPrefixEscaped: '$t(',
// nestingSuffixEscaped: ')',
// defaultVariables: undefined // object that can have values to interpolate on - extends passed in interpolation data
maxReplaces: 1000 // max replaces to prevent endless loop
}
};
}
/* eslint no-param-reassign: 0 */
function transformOptions(options) {
// create namespace object if namespace is passed in as string
if (typeof options.ns === 'string') options.ns = [options.ns];
if (typeof options.fallbackLng === 'string') options.fallbackLng = [options.fallbackLng];
if (typeof options.fallbackNS === 'string') options.fallbackNS = [options.fallbackNS]; // extend whitelist with cimode
if (options.whitelist && options.whitelist.indexOf('cimode') < 0) {
options.whitelist = options.whitelist.concat(['cimode']);
}
return options;
}
function noop() {}
var I18n =
/*#__PURE__*/
function (_EventEmitter) {
_inherits(I18n, _EventEmitter);
function I18n() {
var _this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
_classCallCheck(this, I18n);
_this = _possibleConstructorReturn(this, _getPrototypeOf(I18n).call(this));
if (isIE10) {
EventEmitter.call(_assertThisInitialized(_this)); // <=IE10 fix (unable to call parent constructor)
}
_this.options = transformOptions(options);
_this.services = {};
_this.logger = baseLogger;
_this.modules = {
external: []
};
if (callback && !_this.isInitialized && !options.isClone) {
// https://github.com/i18next/i18next/issues/879
if (!_this.options.initImmediate) {
_this.init(options, callback);
return _possibleConstructorReturn(_this, _assertThisInitialized(_this));
}
setTimeout(function () {
_this.init(options, callback);
}, 0);
}
return _this;
}
_createClass(I18n, [{
key: "init",
value: function init() {
var _this2 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
if (typeof options === 'function') {
callback = options;
options = {};
}
this.options = _objectSpread({}, get(), this.options, transformOptions(options));
this.format = this.options.interpolation.format;
if (!callback) callback = noop;
function createClassOnDemand(ClassOrObject) {
if (!ClassOrObject) return null;
if (typeof ClassOrObject === 'function') return new ClassOrObject();
return ClassOrObject;
} // init services
if (!this.options.isClone) {
if (this.modules.logger) {
baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
} else {
baseLogger.init(null, this.options);
}
var lu = new LanguageUtil(this.options);
this.store = new ResourceStore(this.options.resources, this.options);
var s = this.services;
s.logger = baseLogger;
s.resourceStore = this.store;
s.languageUtils = lu;
s.pluralResolver = new PluralResolver(lu, {
prepend: this.options.pluralSeparator,
compatibilityJSON: this.options.compatibilityJSON,
simplifyPluralSuffix: this.options.simplifyPluralSuffix
});
s.interpolator = new Interpolator(this.options);
s.utils = {
hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
};
s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options); // pipe events from backendConnector
s.backendConnector.on('*', function (event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
_this2.emit.apply(_this2, [event].concat(args));
});
if (this.modules.languageDetector) {
s.languageDetector = createClassOnDemand(this.modules.languageDetector);
s.languageDetector.init(s, this.options.detection, this.options);
}
if (this.modules.i18nFormat) {
s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
if (s.i18nFormat.init) s.i18nFormat.init(this);
}
this.translator = new Translator(this.services, this.options); // pipe events from translator
this.translator.on('*', function (event) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
_this2.emit.apply(_this2, [event].concat(args));
});
this.modules.external.forEach(function (m) {
if (m.init) m.init(_this2);
});
}
if (!this.modules.languageDetector && !this.options.lng) {
this.logger.warn('init: no languageDetector is used and no lng is defined');
} // append api
var storeApi = ['getResource', 'addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];
storeApi.forEach(function (fcName) {
_this2[fcName] = function () {
var _this2$store;
return (_this2$store = _this2.store)[fcName].apply(_this2$store, arguments);
};
});
var deferred = defer();
var load = function load() {
_this2.changeLanguage(_this2.options.lng, function (err, t) {
_this2.isInitialized = true;
_this2.logger.log('initialized', _this2.options);
_this2.emit('initialized', _this2.options);
deferred.resolve(t); // not rejecting on err (as err is only a loading translation failed warning)
callback(err, t);
});
};
if (this.options.resources || !this.options.initImmediate) {
load();
} else {
setTimeout(load, 0);
}
return deferred;
}
/* eslint consistent-return: 0 */
}, {
key: "loadResources",
value: function loadResources(language) {
var _this3 = this;
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
var usedCallback = callback;
var usedLng = typeof language === 'string' ? language : this.language;
if (typeof language === 'function') usedCallback = language;
if (!this.options.resources || this.options.partialBundledLanguages) {
if (usedLng && usedLng.toLowerCase() === 'cimode') return usedCallback(); // avoid loading resources for cimode
var toLoad = [];
var append = function append(lng) {
if (!lng) return;
var lngs = _this3.services.languageUtils.toResolveHierarchy(lng);
lngs.forEach(function (l) {
if (toLoad.indexOf(l) < 0) toLoad.push(l);
});
};
if (!usedLng) {
// at least load fallbacks in this case
var fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
fallbacks.forEach(function (l) {
return append(l);
});
} else {
append(usedLng);
}
if (this.options.preload) {
this.options.preload.forEach(function (l) {
return append(l);
});
}
this.services.backendConnector.load(toLoad, this.options.ns, usedCallback);
} else {
usedCallback(null);
}
}
}, {
key: "reloadResources",
value: function reloadResources(lngs, ns, callback) {
var deferred = defer();
if (!lngs) lngs = this.languages;
if (!ns) ns = this.options.ns;
if (!callback) callback = noop;
this.services.backendConnector.reload(lngs, ns, function (err) {
deferred.resolve(); // not rejecting on err (as err is only a loading translation failed warning)
callback(err);
});
return deferred;
}
}, {
key: "use",
value: function use(module) {
if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');
if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');
if (module.type === 'backend') {
this.modules.backend = module;
}
if (module.type === 'logger' || module.log && module.warn && module.error) {
this.modules.logger = module;
}
if (module.type === 'languageDetector') {
this.modules.languageDetector = module;
}
if (module.type === 'i18nFormat') {
this.modules.i18nFormat = module;
}
if (module.type === 'postProcessor') {
postProcessor.addPostProcessor(module);
}
if (module.type === '3rdParty') {
this.modules.external.push(module);
}
return this;
}
}, {
key: "changeLanguage",
value: function changeLanguage(lng, callback) {
var _this4 = this;
this.isLanguageChangingTo = lng;
var deferred = defer();
this.emit('languageChanging', lng);
var done = function done(err, l) {
if (l) {
_this4.language = l;
_this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
_this4.translator.changeLanguage(l);
_this4.isLanguageChangingTo = undefined;
_this4.emit('languageChanged', l);
_this4.logger.log('languageChanged', l);
} else {
_this4.isLanguageChangingTo = undefined;
}
deferred.resolve(function () {
return _this4.t.apply(_this4, arguments);
});
if (callback) callback(err, function () {
return _this4.t.apply(_this4, arguments);
});
};
var setLng = function setLng(l) {
if (l) {
if (!_this4.language) {
_this4.language = l;
_this4.languages = _this4.services.languageUtils.toResolveHierarchy(l);
}
if (!_this4.translator.language) _this4.translator.changeLanguage(l);
if (_this4.services.languageDetector) _this4.services.languageDetector.cacheUserLanguage(l);
}
_this4.loadResources(l, function (err) {
done(err, l);
});
};
if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
setLng(this.services.languageDetector.detect());
} else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
this.services.languageDetector.detect(setLng);
} else {
setLng(lng);
}
return deferred;
}
}, {
key: "getFixedT",
value: function getFixedT(lng, ns) {
var _this5 = this;
var fixedT = function fixedT(key, opts) {
var options;
if (_typeof(opts) !== 'object') {
for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
rest[_key3 - 2] = arguments[_key3];
}
options = _this5.options.overloadTranslationOptionHandler([key, opts].concat(rest));
} else {
options = _objectSpread({}, opts);
}
options.lng = options.lng || fixedT.lng;
options.lngs = options.lngs || fixedT.lngs;
options.ns = options.ns || fixedT.ns;
return _this5.t(key, options);
};
if (typeof lng === 'string') {
fixedT.lng = lng;
} else {
fixedT.lngs = lng;
}
fixedT.ns = ns;
return fixedT;
}
}, {
key: "t",
value: function t() {
var _this$translator;
return this.translator && (_this$translator = this.translator).translate.apply(_this$translator, arguments);
}
}, {
key: "exists",
value: function exists() {
var _this$translator2;
return this.translator && (_this$translator2 = this.translator).exists.apply(_this$translator2, arguments);
}
}, {
key: "setDefaultNamespace",
value: function setDefaultNamespace(ns) {
this.options.defaultNS = ns;
}
}, {
key: "hasLoadedNamespace",
value: function hasLoadedNamespace(ns) {
var _this6 = this;
if (!this.isInitialized) {
this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);
return false;
}
if (!this.languages || !this.languages.length) {
this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);
return false;
}
var lng = this.languages[0];
var fallbackLng = this.options ? this.options.fallbackLng : false;
var lastLng = this.languages[this.languages.length - 1]; // we're in cimode so this shall pass
if (lng.toLowerCase() === 'cimode') return true;
var loadNotPending = function loadNotPending(l, n) {
var loadState = _this6.services.backendConnector.state["".concat(l, "|").concat(n)];
return loadState === -1 || loadState === 2;
}; // loaded -> SUCCESS
if (this.hasResourceBundle(lng, ns)) return true; // were not loading at all -> SEMI SUCCESS
if (!this.services.backendConnector.backend) return true; // failed loading ns - but at least fallback is not pending -> SEMI SUCCESS
if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;
return false;
}
}, {
key: "loadNamespaces",
value: function loadNamespaces(ns, callback) {
var _this7 = this;
var deferred = defer();
if (!this.options.ns) {
callback && callback();
return Promise.resolve();
}
if (typeof ns === 'string') ns = [ns];
ns.forEach(function (n) {
if (_this7.options.ns.indexOf(n) < 0) _this7.options.ns.push(n);
});
this.loadResources(function (err) {
deferred.resolve();
if (callback) callback(err);
});
return deferred;
}
}, {
key: "loadLanguages",
value: function loadLanguages(lngs, callback) {
var deferred = defer();
if (typeof lngs === 'string') lngs = [lngs];
var preloaded = this.options.preload || [];
var newLngs = lngs.filter(function (lng) {
return preloaded.indexOf(lng) < 0;
}); // Exit early if all given languages are already preloaded
if (!newLngs.length) {
if (callback) callback();
return Promise.resolve();
}
this.options.preload = preloaded.concat(newLngs);
this.loadResources(function (err) {
deferred.resolve();
if (callback) callback(err);
});
return deferred;
}
}, {
key: "dir",
value: function dir(lng) {
if (!lng) lng = this.languages && this.languages.length > 0 ? this.languages[0] : this.language;
if (!lng) return 'rtl';
var rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam'];
return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng)) >= 0 ? 'rtl' : 'ltr';
}
/* eslint class-methods-use-this: 0 */
}, {
key: "createInstance",
value: function createInstance() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 ? arguments[1] : undefined;
return new I18n(options, callback);
}
}, {
key: "cloneInstance",
value: function cloneInstance() {
var _this8 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop;
var mergedOptions = _objectSpread({}, this.options, options, {
isClone: true
});
var clone = new I18n(mergedOptions);
var membersToCopy = ['store', 'services', 'language'];
membersToCopy.forEach(function (m) {
clone[m] = _this8[m];
});
clone.services = _objectSpread({}, this.services);
clone.services.utils = {
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
};
clone.translator = new Translator(clone.services, clone.options);
clone.translator.on('*', function (event) {
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
clone.emit.apply(clone, [event].concat(args));
});
clone.init(mergedOptions, callback);
clone.translator.options = clone.options; // sync options
clone.translator.backendConnector.services.utils = {
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
};
return clone;
}
}]);
return I18n;
}(EventEmitter);
var i18next = new I18n();
return i18next;
}));
|
import { BYTES_IN_KIB } from './constants';
/**
* Function that allows a number with an X amount of decimals
* to be formatted in the following fashion:
* * For 1 digit to the left of the decimal point and X digits to the right of it
* * * Show 3 digits to the right
* * For 2 digits to the left of the decimal point and X digits to the right of it
* * * Show 2 digits to the right
*/
export function formatRelevantDigits(number) {
let digitsLeft = '';
let relevantDigits = 0;
let formattedNumber = '';
if (!isNaN(Number(number))) {
digitsLeft = number.split('.')[0];
switch (digitsLeft.length) {
case 1:
relevantDigits = 3;
break;
case 2:
relevantDigits = 2;
break;
case 3:
relevantDigits = 1;
break;
default:
relevantDigits = 4;
break;
}
formattedNumber = Number(number).toFixed(relevantDigits);
}
return formattedNumber;
}
/**
* Utility function that calculates KiB of the given bytes.
*
* @param {Number} number bytes
* @return {Number} KiB
*/
export function bytesToKiB(number) {
return number / BYTES_IN_KIB;
}
|
(function(win, doc, App){
"use strict";
App.Models = {};
App.Models.Instances = {};
App.Collections = {};
App.Collections.Instances = {};
App.Views = {};
App.Views.Instances = {};
App.Routers = {};
App.Routers.Instances = {};
App.Events = {};
App.Languages = {};
App.Languages.Instances = {};
App.Languages.available = [];
// Store each timeouts ID
win.appTimesout = [];
win.syncTimesout = [];
// Default time before we return to the home page in seconds
win.TIMEOUT_BEFORE_HOME = 50;
// Display App's debug if it's 1, 0 to hide them
win.VERBOSE = 1;
/**
* Find our template inside the application
* @param {String} view Your partial name
* @return {Object} Your view for backbone. Parse by lodash
* @throws {Error} If The application cannot find the requested view
*/
win.tpl = function tpl(view) {
var $view = document.getElementById(view.toLowerCase() + '-viewtpl');
if(!$view) {
throw new Error('Cannot find the requested view : ' + view);
}
return _.template($view.innerHTML);
};
/**
* Clean each timesout
* It's also set a new timeout to the home page.
* The delay before the home page is defined in TIMEOUT_BEFORE_HOME
*/
win.resetTimeout = function resetTimeout() {
if(win.appTimesout.length) {
console.debug('[App@resetTimeout] Clear timeouts');
win.appTimesout.forEach(win.clearTimeout);
win.appTimesout.length = 0;
}
win.setTimeoutPage();
};
win.resetSyncTimeout = function resetSyncTimeout() {
if(win.syncTimesout.length) {
win.syncTimesout.forEach(win.clearTimeout);
}
};
/**
* Open a page after a custom delay
* @param {String} page Page name
* @param {Integer} delay How many seconds ?
*/
win.setTimeoutPage = function setTimeoutPage(page,delay) {
page = page || '';
delay = delay || win.TIMEOUT_BEFORE_HOME;
var _page = page || 'root';
console.debug('[App@setTimeoutPage] Open page ' + _page + ' in ' + delay + 's');
win.appTimesout.push(setTimeout(function() {
App.Routers.Instances.router.navigate(page,{trigger: true});
},delay * 1000));
};
/**
* Helper to open a page
* It can also open a page after a custom delay if you specify one.
* It sends log informations to the driver
* @param {String} page Page name
* @param {Integer} delay Delay in seconds
* @return {void}
*/
win.openPage = function openPage(page,delay) {
var _page = page || 'root';
if(delay) {
Kiwapp.log("[App@openPage] : Open the page - " + _page + " - with a delay of " + delay + "s");
return win.setTimeoutPage(page, delay);
}
Kiwapp.log("[App@openPage] : Open the page - " + _page);
App.Routers.Instances.router.navigate(page,{trigger: true});
};
/**
* Send logs to the driver
* @param {String} msg Your log
* @return {void}
*/
win.log = function log(msg) {
Kiwapp.log(msg || '[App@log]');
};
// Remove the App's debug message
if(!win.VERBOSE) {
console.debug = function(){};
}
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#Model
(function(win, doc, App){
/**
* Example model
* @type {object}
*/
App.Models.Registration = Backbone.Model.extend({
defaults: {
"appName" : "/SalonTicTacToe",
"company" : "",
"country" : "",
"email" : "",
"mobile" : "",
"name" : "",
"surname" : "",
"current_date" : ""
},
validate: function(attrs) {
var msg = {};
['name','surname','email','mobile'].forEach(function(input) {
if(!attrs[input].length) {
msg[input] = "This field cannot be empty";
}
if("email" === input && attrs.email.length) {
var email_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!email_filter.test(attrs.email)) {
msg[input] = "It is not a valid email.";
}
}
});
if(Object.keys(msg).length) {
return msg;
}
},
// Method for sync the model to the server
sync: function() {
// Check if the model's currents values are differents of defaults values
if (!this.modelIsDefault()) {
this.attributes.current_date = new Date();
var json = this.toJSON();
this.clear().set(this.defaults);
if(APP_CONFIG.activeMailChimp) {
var mailChimpService = new MailChimpConnector(APP_CONFIG.MailChimp_API_Key, APP_CONFIG.MailChimp_List_Name,APP_CONFIG.MailChimp_Welcome_Email);
function addSubscriberCallback(data){
console.log(data);
}
function getListCallback(data){
var idList = data.data[0].id;
mailChimpService.addSubscriber(addSubscriberCallback,idList,json);
}
mailChimpService.getList(getListCallback);
}
if(APP_CONFIG.customUrl) {
Kiwapp.session().store(json,{
url : APP_CONFIG.customUrl,
method : "POST"
}).send();
}
}
},
/**
* Check if the currents values are differentes from defaults values for the model
*/
modelIsDefault:function(){
// Iterate over all object's properties
// And conpare it to the defaults values
for(var k in this.attributes) {
var value = this.attributes[k];
var defaultValue = this.defaults[k];
if(value!==defaultValue){
return false;
}
}
return true;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.EndIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('end'),
events: {
"click .page-end" : 'stateChange'
},
initialize: function() {
},
stateChange : function() {
App.Routers.Instances.router.navigate('',{trigger: true});
},
render: function() {
win.setTimeoutPage('',15);
this.$el.html(this.template);
return this;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.FormIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('form'),
events: {
"click #play" : 'stateChange',
"click .btn-back" : "returnBack",
"click .error-field" : "clearField",
"change input" : "changed",
"keyup input" : "timeoutrestart"
},
initialize: function(model) {
this.model = model;
},
returnBack: function() {
win.syncTimesout.push(setTimeout(function() {
App.Routers.Instances.router.navigate('',{trigger: true});
},0));
},
clearField: function(evt) {
evt.currentTarget.value = '';
evt.currentTarget.placeholder = '';
evt.currentTarget.style.color = 'black';
evt.currentTarget.style.fontStyle = 'normal';
evt.currentTarget.style.borderColor = 'black';
return this;
},
stateChange : function() {
var that = this;
if (!that.model.isValid()) {
that.$el.html(that.template({
"data" : _.extend(that.model.toJSON(), that.model.validationError),
"error" : that.model.validationError,
"hasError" : true
}));
}else {
win.syncTimesout.push(setTimeout(function() {
that.model.sync();
},0));
App.Routers.Instances.router.navigate('game',{trigger: true});
}
},
// reset the timeout before the home page
timeoutrestart: function() {
resetTimeout();
},
/**
* Input values changed
* @param {type} evt
*/
changed: function(evt) {
var changed = evt.currentTarget,
value = $(evt.currentTarget).val(),
obj = {};
// Reset the timeout before home page
resetTimeout();
// We get the name of input and the value and we store it in the fomu
obj[changed.name] = value;
this.model.set(obj);
},
render: function() {
this.$el.html(this.template({data: {}, error : {}, hasError: false}));
return this;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.GameIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('game'),
events: {
"click .btn-back-form" : "returnBack"
},
initialize: function() {},
returnBack: function() {
win.setTimeoutPage('form',0.1);
// win.location.href = win.location.origin + '/#form';
},
/**
* Return the probability for an option
* @param {String} opt Name of this option
* @return {Integer} Value
*/
getProbability : function(opt) {
var day = moment().format('ddddDDYYYY'),
total = localStorage.getItem('totalgame' + day);
var proba = {
"win" : 25,
"lost-1" : 25,
"lost-2" : 25,
"lost-3" : 25
};
if(win.APP_CONFIG) {
proba.win = win.APP_CONFIG.probaWinner || 25;
proba['lost-1'] = win.APP_CONFIG.probaLost1 || 25;
proba['lost-2'] = win.APP_CONFIG.probaLost2 || 25;
proba['lost-3'] = win.APP_CONFIG.probaLost3 || 25;
}
if(total == 0 ) {
log("[GameIndex@getProbability] Probability to win set to 0");
proba = {
"win" : 0,
"lost-1" : proba['lost-1'] + Math.round(proba.win/3),
"lost-2" : proba['lost-2'] + Math.round(proba.win/3),
"lost-3" : proba['lost-3'] + Math.round(proba.win/3)
};
}
return proba[opt];
},
render: function() {
this.$el.html(this.template);
var day = moment().format('ddddDDYYYY'),
total = localStorage.getItem('totalgame' + day);
var widthRatio = Math.round(499 * (window.innerWidth / 1024)),
heightRatio = Math.round(474 * ( window.innerHeight / 768));
if(heightRatio < 474) {
heightRatio = 474;
}
var scracth = new ScratchCard(document.getElementById('scratchcard'),{
"picture" : [
{
"path" : "assets/images",
"file": "scratch-gagnant.jpg",
"luck" : this.getProbability('win'),
"event" : 'win',
},{
"path" : "assets/images",
"file": "scratch-perdant-1.jpg",
"luck" : this.getProbability('lost-1'),
"event" : 'lost',
"details" : "case-1"
},{
"path" : "assets/images",
"file": "scratch-perdant-2.jpg",
"luck" : this.getProbability('lost-2'),
"event" : 'lost',
"details" : "case-2"
},{
"path" : "assets/images",
"file": "scratch-perdant-3.jpg",
"luck" : this.getProbability('lost-3'),
"event" : 'lost',
"details" : "case-3"
}
],
"foreground" : {
"path" : "assets/images",
"file" : "scratch.jpg"
},
"minCompletion" : this.getMinCompletion(),
// "height" : window.innerHeight
"width" : widthRatio,
// "height" : 474 * ( window.innerHeight / 768)
"height" : heightRatio
});
log("[GameIndex@render] We have now " + total + " to win");
scracth.on('win', function() {
Kiwapp.stats().event('win');
localStorage.setItem('totalgame' + day, (total - 1));
win.setTimeoutPage('usb',1);
});
scracth.on('lost', function(opt) {
Kiwapp.stats().event(opt);
win.setTimeoutPage('lost',1);
});
return this;
},
/**
* Return the min Completion percent required to win or lose the game
* @return {Integer}
*/
getMinCompletion: function() {
if(win.APP_CONFIG) {
return win.APP_CONFIG.minCompletion || 90;
}
return 90;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.HomeIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('home'),
events: {
},
initialize: function() {
},
render: function() {
this.$el.html(this.template);
return this;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.LostIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('lost'),
events: {
"click #backtohome" : 'stateChange'
},
initialize: function() {
},
stateChange : function() {
App.Routers.Instances.router.navigate('',{trigger: true});
},
render: function() {
this.$el.html(this.template);
return this;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.RegisterIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('register'),
events: {
"click #backhome" : 'stateChange'
},
initialize: function() {
},
stateChange : function() {
App.Routers.Instances.router.navigate('',{trigger: true});
},
render: function() {
win.setTimeoutPage('',10);
this.$el.html(this.template);
return this;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.RootIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('main'),
events: {
"click #playhome" : 'stateChange',
"click #go-to-form" : 'stateChange'
},
initialize: function() {
// Kiwapp.session().start();
},
stateChange : function() {
App.Routers.Instances.router.navigate('form',{trigger: true});
// App.Routers.Instances.router.navigate('game',{trigger: true})
},
render: function() {
this.$el.html(this.template);
return this;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#View
(function(win, doc, App){
/**
* Root View
* @type {object}
*/
App.Views.UsbIndex = Backbone.View.extend({
el: '#wrapper',
template: tpl('usb'),
events: {
"click #openpage" : 'stateChange'
},
initialize: function() {
},
stateChange : function() {
App.Routers.Instances.router.navigate('',{trigger: true});
},
render: function() {
this.$el.html(this.template);
win.setTimeoutPage('',10);
return this;
}
});
})(window, window.document, window.app || (window.app = {}));
// http://backbonejs.org/#Router
(function(win, doc, App){
/**
* Router
* @type {object}
*/
App.Routers.Router = Backbone.Router.extend({
routes: {
'' : 'root',
'home' : 'root',
'form' : 'form',
'game' : 'game',
'lost' : 'lost',
'usb' : 'usb',
'register' : 'register',
'end' : 'end',
'*path' : 'redirect404' // ALWAYS MUST BE THE LAST ROUTE
},
/**
* Router init
* @return {void}
*/
initialize: function() {
App.Views.Instances.rootIndex = new App.Views.RootIndex();
App.Views.Instances.formIndex = new App.Views.FormIndex(new App.Models.Registration());
App.Views.Instances.registerIndex = new App.Views.RegisterIndex();
App.Views.Instances.lostIndex = new App.Views.LostIndex();
App.Views.Instances.usbIndex = new App.Views.UsbIndex();
App.Views.Instances.gameIndex = new App.Views.GameIndex();
App.Views.Instances.endIndex = new App.Views.EndIndex();
},
/**
* Used before every action
* @return {void}
*/
before: function(page) {
if('root' === page && Backbone.history.history.length > 1) {
Kiwapp.session().end();
}
win.resetTimeout();
Kiwapp.stats().page(page);
},
/**
* Used after every action
* @return {void}
*/
after: function(page) {
if('root' === page) {
win.resetSyncTimeout();
Kiwapp.session().start();
}
},
/**
* @return {void}
*/
root: function() {
this.before('root');
App.Views.Instances.rootIndex.render();
this.after('root');
},
form: function() {
this.before('form');
App.Views.Instances.formIndex.render();
this.after('form');
},
register: function() {
this.before('register');
App.Views.Instances.registerIndex.render();
this.after('register');
},
lost: function() {
this.before('lost');
App.Views.Instances.lostIndex.render();
this.after('lost');
},
usb: function() {
this.before('usb');
App.Views.Instances.usbIndex.render();
this.after('usb');
},
game: function() {
this.before('game');
App.Views.Instances.gameIndex.render();
this.after('game');
},
end: function() {
this.before('end');
App.Views.Instances.endIndex.render();
this.after('end');
},
//==route==//
/**
* Used when a page isn't found
* @return {void}
*/
redirect404: function() {
console.log('Oops, 404!');
}
});
})(window, window.document, window.app || (window.app = {}));
/**
* This is where all begins
*/
(function(win, doc, App){
var $doc = $(doc);
day = moment().format('ddddDDYYYY'),
total = localStorage.getItem('totalgame' + day);
$doc.ready(function() {
var wrap = document.getElementById('wrapper');
wrap.style.width = window.innerWidth + "px";
wrap.style.maxWidth = window.innerWidth + "px";
wrap.style.height = window.innerHeight + "px";
wrap.style.maxHeight = window.innerHeight + "px";
Kiwapp("../config/kiwapp_config.js", function(){
Kiwapp.driver().trigger('callApp', {call:'rotation', data:{
"orientation" : 10
}});
win.APP_CONFIG = Kiwapp.get('shopParameters');
if(total == null) {
localStorage.setItem('totalgame' + day,4);
}
App.Routers.Instances.router = new App.Routers.Router();
Backbone.history.start();
});
});
})(window, window.document, window.app || (window.app = {}));
|
module.exports={title:'Adobe',slug:'adobe',svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Adobe icon</title><path d="M15.1 2H24v20L15.1 2zM8.9 2H0v20L8.9 2zM12 9.4L17.6 22h-3.8l-1.6-4H8.1L12 9.4z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1];},source:'https://www.adobe.com/',hex:'FF0000'}; |
import createElement from './exports/createElement';
import findNodeHandle from './exports/findNodeHandle';
import processColor from './exports/processColor';
import render from './exports/render';
import unmountComponentAtNode from './exports/unmountComponentAtNode';
import NativeModules from './exports/NativeModules';
import TextPropTypes from './exports/TextPropTypes';
import ViewPropTypes from './exports/ViewPropTypes'; // APIs
import AccessibilityInfo from './exports/AccessibilityInfo';
import Alert from './exports/Alert';
import Animated from './exports/Animated';
import AppRegistry from './exports/AppRegistry';
import AppState from './exports/AppState';
import AsyncStorage from './exports/AsyncStorage';
import BackHandler from './exports/BackHandler';
import Clipboard from './exports/Clipboard';
import DeviceInfo from './exports/DeviceInfo';
import Dimensions from './exports/Dimensions';
import Easing from './exports/Easing';
import I18nManager from './exports/I18nManager';
import Keyboard from './exports/Keyboard';
import InteractionManager from './exports/InteractionManager';
import LayoutAnimation from './exports/LayoutAnimation';
import Linking from './exports/Linking';
import NativeEventEmitter from './exports/NativeEventEmitter';
import NetInfo from './exports/NetInfo';
import PanResponder from './exports/PanResponder';
import PixelRatio from './exports/PixelRatio';
import Platform from './exports/Platform';
import Share from './exports/Share';
import StyleSheet from './exports/StyleSheet';
import UIManager from './exports/UIManager';
import Vibration from './exports/Vibration'; // components
import ActivityIndicator from './exports/ActivityIndicator';
import Button from './exports/Button';
import CheckBox from './exports/CheckBox';
import FlatList from './exports/FlatList';
import Image from './exports/Image';
import ImageBackground from './exports/ImageBackground';
import KeyboardAvoidingView from './exports/KeyboardAvoidingView';
import ListView from './exports/ListView';
import Modal from './exports/Modal';
import Picker from './exports/Picker';
import ProgressBar from './exports/ProgressBar';
import RefreshControl from './exports/RefreshControl';
import SafeAreaView from './exports/SafeAreaView';
import ScrollView from './exports/ScrollView';
import SectionList from './exports/SectionList';
import Slider from './exports/Slider';
import StatusBar from './exports/StatusBar';
import SwipeableFlatList from './exports/SwipeableFlatList';
import SwipeableListView from './exports/SwipeableListView';
import Switch from './exports/Switch';
import Text from './exports/Text';
import TextInput from './exports/TextInput';
import Touchable from './exports/Touchable';
import TouchableHighlight from './exports/TouchableHighlight';
import TouchableNativeFeedback from './exports/TouchableNativeFeedback';
import TouchableOpacity from './exports/TouchableOpacity';
import TouchableWithoutFeedback from './exports/TouchableWithoutFeedback';
import View from './exports/View';
import VirtualizedList from './exports/VirtualizedList';
import YellowBox from './exports/YellowBox'; // propTypes
import ColorPropType from './exports/ColorPropType';
import EdgeInsetsPropType from './exports/EdgeInsetsPropType';
import PointPropType from './exports/PointPropType'; // compat (components)
import DatePickerIOS from './exports/DatePickerIOS';
import DrawerLayoutAndroid from './exports/DrawerLayoutAndroid';
import ImageEditor from './exports/ImageEditor';
import ImageStore from './exports/ImageStore';
import InputAccessoryView from './exports/InputAccessoryView';
import MaskedViewIOS from './exports/MaskedViewIOS';
import NavigatorIOS from './exports/NavigatorIOS';
import PickerIOS from './exports/PickerIOS';
import ProgressBarAndroid from './exports/ProgressBarAndroid';
import ProgressViewIOS from './exports/ProgressViewIOS';
import SegmentedControlIOS from './exports/SegmentedControlIOS';
import SnapshotViewIOS from './exports/SnapshotViewIOS';
import TabBarIOS from './exports/TabBarIOS';
import ToastAndroid from './exports/ToastAndroid';
import ToolbarAndroid from './exports/ToolbarAndroid';
import ViewPagerAndroid from './exports/ViewPagerAndroid';
import WebView from './exports/WebView'; // compat (apis)
import ActionSheetIOS from './exports/ActionSheetIOS';
import AlertIOS from './exports/AlertIOS';
import CameraRoll from './exports/CameraRoll';
import DatePickerAndroid from './exports/DatePickerAndroid';
import ImagePickerIOS from './exports/ImagePickerIOS';
import PermissionsAndroid from './exports/PermissionsAndroid';
import PushNotificationIOS from './exports/PushNotificationIOS';
import Settings from './exports/Settings';
import StatusBarIOS from './exports/StatusBarIOS';
import Systrace from './exports/Systrace';
import TimePickerAndroid from './exports/TimePickerAndroid';
import TVEventHandler from './exports/TVEventHandler';
import VibrationIOS from './exports/VibrationIOS'; // plugins
import DeviceEventEmitter from './exports/DeviceEventEmitter';
export { // top-level API
createElement, findNodeHandle, render, unmountComponentAtNode, // modules
processColor, NativeModules, TextPropTypes, ViewPropTypes, // APIs
AccessibilityInfo, Alert, Animated, AppRegistry, AppState, AsyncStorage, BackHandler, Clipboard, DeviceInfo, Dimensions, Easing, I18nManager, InteractionManager, Keyboard, LayoutAnimation, Linking, NativeEventEmitter, NetInfo, PanResponder, PixelRatio, Platform, Share, StyleSheet, UIManager, Vibration, // components
ActivityIndicator, Button, CheckBox, FlatList, Image, ImageBackground, KeyboardAvoidingView, ListView, Modal, Picker, ProgressBar, RefreshControl, SafeAreaView, ScrollView, SectionList, Slider, StatusBar, SwipeableFlatList, SwipeableListView, Switch, Text, TextInput, Touchable, TouchableHighlight, TouchableNativeFeedback, TouchableOpacity, TouchableWithoutFeedback, View, VirtualizedList, YellowBox, // propTypes
ColorPropType, EdgeInsetsPropType, PointPropType, // compat (components)
DatePickerIOS, DrawerLayoutAndroid, ImageEditor, ImageStore, InputAccessoryView, MaskedViewIOS, NavigatorIOS, PickerIOS, ProgressBarAndroid, ProgressViewIOS, SegmentedControlIOS, SnapshotViewIOS, TabBarIOS, ToastAndroid, ToolbarAndroid, ViewPagerAndroid, WebView, // compat (apis)
ActionSheetIOS, AlertIOS, CameraRoll, DatePickerAndroid, ImagePickerIOS, PermissionsAndroid, PushNotificationIOS, Settings, StatusBarIOS, Systrace, TimePickerAndroid, TVEventHandler, VibrationIOS, // plugins
DeviceEventEmitter }; |
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import { formatMuiErrorMessage as _formatMuiErrorMessage } from "@material-ui/utils";
import * as React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import { refType } from '@material-ui/utils';
import ownerDocument from '../utils/ownerDocument';
import capitalize from '../utils/capitalize';
import Menu from '../Menu/Menu';
import { nativeSelectSelectStyles, nativeSelectIconStyles } from '../NativeSelect/NativeSelectInput';
import { isFilled } from '../InputBase/utils';
import experimentalStyled, { slotShouldForwardProp } from '../styles/experimentalStyled';
import useForkRef from '../utils/useForkRef';
import useControlled from '../utils/useControlled';
import selectClasses, { getSelectUtilityClasses } from './selectClasses';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const SelectSelect = experimentalStyled('div', {}, {
name: 'MuiSelect',
slot: 'Select',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return {
// Win specificity over the input base
[`&.${selectClasses.select}`]: _extends({}, styles.select, styles[styleProps.variant])
};
}
})(nativeSelectSelectStyles, {
// Win specificity over the input base
[`&.${selectClasses.select}`]: {
height: 'auto',
// Resets for multiple select with chips
minHeight: '1.4375em',
// Required for select\text-field height consistency
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden'
}
});
const SelectIcon = experimentalStyled('svg', {}, {
name: 'MuiSelect',
slot: 'Icon',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return _extends({}, styles.icon, styleProps.variant && styles[`icon${capitalize(styleProps.variant)}`], styleProps.open && styles.iconOpen);
}
})(nativeSelectIconStyles);
const SelectNativeInput = experimentalStyled('input', {
shouldForwardProp: prop => slotShouldForwardProp(prop) && prop !== 'classes'
}, {
name: 'MuiSelect',
slot: 'NativeInput',
overridesResolver: (props, styles) => styles.nativeInput
})({
bottom: 0,
left: 0,
position: 'absolute',
opacity: 0,
pointerEvents: 'none',
width: '100%',
boxSizing: 'border-box'
});
function areEqualValues(a, b) {
if (typeof b === 'object' && b !== null) {
return a === b;
}
return String(a) === String(b);
}
function isEmpty(display) {
return display == null || typeof display === 'string' && !display.trim();
}
const useUtilityClasses = styleProps => {
const {
classes,
variant,
disabled,
open
} = styleProps;
const slots = {
select: ['select', variant, disabled && 'disabled'],
icon: ['icon', `icon${capitalize(variant)}`, open && 'iconOpen', disabled && 'disabled'],
nativeInput: ['nativeInput']
};
return composeClasses(slots, getSelectUtilityClasses, classes);
};
/**
* @ignore - internal component.
*/
const SelectInput = /*#__PURE__*/React.forwardRef(function SelectInput(props, ref) {
const {
'aria-describedby': ariaDescribedby,
'aria-label': ariaLabel,
autoFocus,
autoWidth,
children,
className,
defaultValue,
disabled,
displayEmpty,
IconComponent,
inputRef: inputRefProp,
labelId,
MenuProps = {},
multiple,
name,
onBlur,
onChange,
onClose,
onFocus,
onOpen,
open: openProp,
readOnly,
renderValue,
SelectDisplayProps = {},
tabIndex: tabIndexProp,
value: valueProp,
variant = 'standard'
} = props,
other = _objectWithoutPropertiesLoose(props, ["aria-describedby", "aria-label", "autoFocus", "autoWidth", "children", "className", "defaultValue", "disabled", "displayEmpty", "IconComponent", "inputRef", "labelId", "MenuProps", "multiple", "name", "onBlur", "onChange", "onClose", "onFocus", "onOpen", "open", "readOnly", "renderValue", "SelectDisplayProps", "tabIndex", "type", "value", "variant"]);
const [value, setValueState] = useControlled({
controlled: valueProp,
default: defaultValue,
name: 'Select'
});
const inputRef = React.useRef(null);
const displayRef = React.useRef(null);
const [displayNode, setDisplayNode] = React.useState(null);
const {
current: isOpenControlled
} = React.useRef(openProp != null);
const [menuMinWidthState, setMenuMinWidthState] = React.useState();
const [openState, setOpenState] = React.useState(false);
const handleRef = useForkRef(ref, inputRefProp);
const handleDisplayRef = React.useCallback(node => {
displayRef.current = node;
if (node) {
setDisplayNode(node);
}
}, []);
React.useImperativeHandle(handleRef, () => ({
focus: () => {
displayRef.current.focus();
},
node: inputRef.current,
value
}), [value]);
React.useEffect(() => {
if (autoFocus) {
displayRef.current.focus();
}
}, [autoFocus]);
React.useEffect(() => {
const label = ownerDocument(displayRef.current).getElementById(labelId);
if (label) {
const handler = () => {
if (getSelection().isCollapsed) {
displayRef.current.focus();
}
};
label.addEventListener('click', handler);
return () => {
label.removeEventListener('click', handler);
};
}
return undefined;
}, [labelId]);
const update = (open, event) => {
if (open) {
if (onOpen) {
onOpen(event);
}
} else if (onClose) {
onClose(event);
}
if (!isOpenControlled) {
setMenuMinWidthState(autoWidth ? null : displayNode.clientWidth);
setOpenState(open);
}
};
const handleMouseDown = event => {
// Ignore everything but left-click
if (event.button !== 0) {
return;
} // Hijack the default focus behavior.
event.preventDefault();
displayRef.current.focus();
update(true, event);
};
const handleClose = event => {
update(false, event);
};
const childrenArray = React.Children.toArray(children); // Support autofill.
const handleChange = event => {
const index = childrenArray.map(child => child.props.value).indexOf(event.target.value);
if (index === -1) {
return;
}
const child = childrenArray[index];
setValueState(child.props.value);
if (onChange) {
onChange(event, child);
}
};
const handleItemClick = child => event => {
let newValue; // We use the tabindex attribute to signal the available options.
if (!event.currentTarget.hasAttribute('tabindex')) {
return;
}
if (multiple) {
newValue = Array.isArray(value) ? value.slice() : [];
const itemIndex = value.indexOf(child.props.value);
if (itemIndex === -1) {
newValue.push(child.props.value);
} else {
newValue.splice(itemIndex, 1);
}
} else {
newValue = child.props.value;
}
if (child.props.onClick) {
child.props.onClick(event);
}
if (value !== newValue) {
setValueState(newValue);
if (onChange) {
// Redefine target to allow name and value to be read.
// This allows seamless integration with the most popular form libraries.
// https://github.com/mui-org/material-ui/issues/13485#issuecomment-676048492
// Clone the event to not override `target` of the original event.
const nativeEvent = event.nativeEvent || event;
const clonedEvent = new nativeEvent.constructor(nativeEvent.type, nativeEvent);
Object.defineProperty(clonedEvent, 'target', {
writable: true,
value: {
value: newValue,
name
}
});
onChange(clonedEvent, child);
}
}
if (!multiple) {
update(false, event);
}
};
const handleKeyDown = event => {
if (!readOnly) {
const validKeys = [' ', 'ArrowUp', 'ArrowDown', // The native select doesn't respond to enter on MacOS, but it's recommended by
// https://www.w3.org/TR/wai-aria-practices/examples/listbox/listbox-collapsible.html
'Enter'];
if (validKeys.indexOf(event.key) !== -1) {
event.preventDefault();
update(true, event);
}
}
};
const open = displayNode !== null && (isOpenControlled ? openProp : openState);
const handleBlur = event => {
// if open event.stopImmediatePropagation
if (!open && onBlur) {
// Preact support, target is read only property on a native event.
Object.defineProperty(event, 'target', {
writable: true,
value: {
value,
name
}
});
onBlur(event);
}
};
delete other['aria-invalid'];
let display;
let displaySingle;
const displayMultiple = [];
let computeDisplay = false;
let foundMatch = false; // No need to display any value if the field is empty.
if (isFilled({
value
}) || displayEmpty) {
if (renderValue) {
display = renderValue(value);
} else {
computeDisplay = true;
}
}
const items = childrenArray.map(child => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(["Material-UI: The Select component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
let selected;
if (multiple) {
if (!Array.isArray(value)) {
throw new Error(process.env.NODE_ENV !== "production" ? `Material-UI: The \`value\` prop must be an array when using the \`Select\` component with \`multiple\`.` : _formatMuiErrorMessage(2));
}
selected = value.some(v => areEqualValues(v, child.props.value));
if (selected && computeDisplay) {
displayMultiple.push(child.props.children);
}
} else {
selected = areEqualValues(value, child.props.value);
if (selected && computeDisplay) {
displaySingle = child.props.children;
}
}
if (selected) {
foundMatch = true;
}
return /*#__PURE__*/React.cloneElement(child, {
'aria-selected': selected ? 'true' : undefined,
onClick: handleItemClick(child),
onKeyUp: event => {
if (event.key === ' ') {
// otherwise our MenuItems dispatches a click event
// it's not behavior of the native <option> and causes
// the select to close immediately since we open on space keydown
event.preventDefault();
}
if (child.props.onKeyUp) {
child.props.onKeyUp(event);
}
},
role: 'option',
selected,
value: undefined,
// The value is most likely not a valid HTML attribute.
'data-value': child.props.value // Instead, we provide it as a data attribute.
});
});
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (!foundMatch && !multiple && value !== '') {
const values = childrenArray.map(child => child.props.value);
console.warn([`Material-UI: You have provided an out-of-range value \`${value}\` for the select ${name ? `(name="${name}") ` : ''}component.`, "Consider providing a value that matches one of the available options or ''.", `The available values are ${values.filter(x => x != null).map(x => `\`${x}\``).join(', ') || '""'}.`].join('\n'));
}
}, [foundMatch, childrenArray, multiple, name, value]);
}
if (computeDisplay) {
display = multiple ? displayMultiple.join(', ') : displaySingle;
} // Avoid performing a layout computation in the render method.
let menuMinWidth = menuMinWidthState;
if (!autoWidth && isOpenControlled && displayNode) {
menuMinWidth = displayNode.clientWidth;
}
let tabIndex;
if (typeof tabIndexProp !== 'undefined') {
tabIndex = tabIndexProp;
} else {
tabIndex = disabled ? null : 0;
}
const buttonId = SelectDisplayProps.id || (name ? `mui-component-select-${name}` : undefined);
const styleProps = _extends({}, props, {
variant,
value,
open
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/_jsxs(React.Fragment, {
children: [/*#__PURE__*/_jsx(SelectSelect, _extends({
ref: handleDisplayRef,
tabIndex: tabIndex,
role: "button",
"aria-disabled": disabled ? 'true' : undefined,
"aria-expanded": open ? 'true' : 'false',
"aria-haspopup": "listbox",
"aria-label": ariaLabel,
"aria-labelledby": [labelId, buttonId].filter(Boolean).join(' ') || undefined,
"aria-describedby": ariaDescribedby,
onKeyDown: handleKeyDown,
onMouseDown: disabled || readOnly ? null : handleMouseDown,
onBlur: handleBlur,
onFocus: onFocus
}, SelectDisplayProps, {
styleProps: styleProps,
className: clsx(classes.select, className, SelectDisplayProps.className) // The id is required for proper a11y
,
id: buttonId,
children: isEmpty(display) ?
/*#__PURE__*/
// notranslate needed while Google Translate will not fix zero-width space issue
// eslint-disable-next-line react/no-danger
_jsx("span", {
className: "notranslate",
dangerouslySetInnerHTML: {
__html: '​'
}
}) : display
})), /*#__PURE__*/_jsx(SelectNativeInput, _extends({
value: Array.isArray(value) ? value.join(',') : value,
name: name,
ref: inputRef,
"aria-hidden": true,
onChange: handleChange,
tabIndex: -1,
disabled: disabled,
className: classes.nativeInput,
autoFocus: autoFocus,
styleProps: styleProps
}, other)), /*#__PURE__*/_jsx(SelectIcon, {
as: IconComponent,
className: classes.icon,
styleProps: styleProps
}), /*#__PURE__*/_jsx(Menu, _extends({
id: `menu-${name || ''}`,
anchorEl: displayNode,
open: open,
onClose: handleClose
}, MenuProps, {
MenuListProps: _extends({
'aria-labelledby': labelId,
role: 'listbox',
disableListWrap: true
}, MenuProps.MenuListProps),
PaperProps: _extends({}, MenuProps.PaperProps, {
style: _extends({
minWidth: menuMinWidth
}, MenuProps.PaperProps != null ? MenuProps.PaperProps.style : null)
}),
children: items
}))]
});
});
process.env.NODE_ENV !== "production" ? SelectInput.propTypes = {
/**
* @ignore
*/
'aria-describedby': PropTypes.string,
/**
* @ignore
*/
'aria-label': PropTypes.string,
/**
* @ignore
*/
autoFocus: PropTypes.bool,
/**
* If `true`, the width of the popover will automatically be set according to the items inside the
* menu, otherwise it will be at least the width of the select input.
*/
autoWidth: PropTypes.bool,
/**
* The option elements to populate the select with.
* Can be some `<MenuItem>` elements.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* The CSS class name of the select element.
*/
className: PropTypes.string,
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the select is disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the selected item is displayed even if its value is empty.
*/
displayEmpty: PropTypes.bool,
/**
* The icon that displays the arrow.
*/
IconComponent: PropTypes.elementType.isRequired,
/**
* Imperative handle implementing `{ value: T, node: HTMLElement, focus(): void }`
* Equivalent to `ref`
*/
inputRef: refType,
/**
* The ID of an element that acts as an additional label. The Select will
* be labelled by the additional label and the selected value.
*/
labelId: PropTypes.string,
/**
* Props applied to the [`Menu`](/api/menu/) element.
*/
MenuProps: PropTypes.object,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
*/
multiple: PropTypes.bool,
/**
* Name attribute of the `select` or hidden `input` element.
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (any).
* @param {object} [child] The react element that was selected.
*/
onChange: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* Callback fired when the component requests to be opened.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool,
/**
* @ignore
*/
readOnly: PropTypes.bool,
/**
* Render the selected value.
*
* @param {any} value The `value` provided to the component.
* @returns {ReactNode}
*/
renderValue: PropTypes.func,
/**
* Props applied to the clickable div element.
*/
SelectDisplayProps: PropTypes.object,
/**
* @ignore
*/
tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* @ignore
*/
type: PropTypes.any,
/**
* The input value.
*/
value: PropTypes.any,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} : void 0;
export default SelectInput; |
/*!
* Quantum - http levels definition
* Copyright(c) 2012 Jake Luer <jake@qualiancy.com>
* MIT Licensed
*/
/*!
* Level Definition
*/
module.exports = {
levels: {
GET: 0
, POST: 1
, PUT: 2
, HEAD: 3
, DELETE: 4
, OPTIONS: 5
, TRACE: 6
, COPY: 7
, LOCK: 8
, MKCOL: 9
, MOVE: 10
, PROPFIND: 11
, PROPPATCH: 12
, UNLOCK: 13
, REPORT: 14
, MKACTIVITY: 15
, CHECKOUT: 16
, MERGE: 17
, MSEARCH: 18
, NOTIFY: 19
}
, colors: {
GET: 'green'
, POST: 'blue'
, PUT: 'magenta'
, HEAD: 'yellow'
, DELETE: 'red'
, OPTIONS: 'yellow'
, TRACE: 'blue'
, COPY: 'cyan'
, LOCK: 'gray'
, MKCOL: 'gray'
, MOVE: 'magenta'
, PROPFIND: 'cyan'
, PROPPATCH: 'blue'
, UNLOCK: 'default'
, REPORT: 'yellow'
, MKACTIVITY: 'gray'
, CHECKOUT: 'green'
, MERGE: 'yellow'
, MSEARCH: 'blue'
, NOTIFY: 'cyan'
}
}
|
define({
"queries": "Vaicājumi",
"addNew": "Pievienot jaunu",
"newQuery": "Jauns vaicājums",
"queryLayer": "Vaicājuma slānis",
"setSource": "Iestatīt",
"setDataSource": "Iestatīt datu avotu",
"name": "Nosaukums",
"querySource": "Datu avots",
"queryName": "Uzdevuma nosaukums",
"queryDefinition": "Filtra definīcija",
"resultsSetting": "Rezultātu iestatījums",
"symbolSetting": "Simbola iestatījums",
"resultSettingTip": "Definējiet parādāmos izvades rezultātus un parādīšanas veidu.",
"resultItemTitle": "Katras rezultāta vienības virsraksts",
"resultItemContent": "Šie lauka atribūti būs redzami",
"fieldsSetTip": "Atzīmējiet laukus, kuri jārāda. Izvēlieties lauku, lai atjauninātu tā aizstājvārdu, kārtotu vai formatētu to.",
"addField": "Pievienot lauku",
"visibility": "Redzamība",
"alias": "Aizstājvārds",
"specialType": "Īpašais veids",
"actions": "Darbības",
"none": "Nav",
"link": "Saite",
"image": "Attēls",
"noField": "Nav lauka",
"operationalLayerTip": "Pievienot rezultātu kā darbības slāni",
"setLayerSymbolTip": "Iestatiet vaicājuma rezultātu simbolu: ",
"setSelectedSymbolTip": "Iestatiet izraudzītā elementa simbolu.",
"notUseFilter": "Neizmantot filtru",
"setSourceTip": "Iestatiet vaicājuma avotu.",
"setFilterTip": "Lūdzu, pareizi iestatiet filtru.",
"ok": "Labi",
"cancel": "Atcelt",
"noFilterTip": "Bez definētas filtra izteiksmes šajā vaicājuma uzdevumā būs norādīti visi elementi norādītajā datu avotā.",
"relationships": "Attiecības",
"addRelationshipLayer": "Pievienot jaunu attiecību",
"relatedTo": "Saistīts ar",
"selectOption": "Lūdzu, izvēlieties..",
"resultItemSorting": "Rezultātu vienību kārtošana",
"field": "Lauks",
"sortingOrder": "Secība",
"configureFieldsTip": "Lūdzu, konfigurējiet laukus, pēc kuriem tiks veikta vaicājuma rezultātu kārtošana.",
"setSortingFields": "Iestatiet kārtošanas laukus",
"ascending": "Pieaugoši",
"descending": "Dilstoši",
"sortBy": "Kārtot pēc",
"thenBy": "Pēc tam pēc",
"addTask": "Pievienot uzdevumu",
"noTasksTip": "Nav konfigurēts neviens vaicājums. Lai pievienotu jaunu, noklikšķiniet uz \"${newQuery}\".",
"infoText": "Informācija",
"filters": "Filtri",
"results": "Rezultāti",
"optionsText": "Opcijas",
"summaryText": "Kopsavilkums",
"attributeFilter": "Atribūtu filtrs",
"attributeFilterTip": "Definējiet atribūtu izteiksmes izmantošanai logrīkā, lai filtrētu vaicājumu slāni.",
"defineWhereClause": "Vaicājumam definējiet klauzulu Kur.",
"noExpressionDefinedTip": "Nav definēta neviena izteiksme. Visi ieraksti tiks atgriezti.",
"setExpressions": "Iestatīt izteiksmes",
"spatialFilter": "Telpiskie filtri",
"spatialFilterTip": "Izvēlieties, kuri telpiskie filtri būs pieejami lietotājiem.",
"defaultOption": "Noklusējums",
"useCurrentExtentTip": "Atgriezt elementus tikai pašreizējā kartes pārklājumā",
"useDrawGraphicTip": "Atgriezt tikai elementus, kas šķērso kartē uzzīmēto formu",
"useFeaturesTip": "Atgriezt tikai tos elementus, kuriem ir telpiskās attiecības ar elementiem citā slānī",
"noSpatialLimitTip": "Atgriezt elementus pilnā kartes pārklājumā",
"drawingTools": "Izvēlēties zīmēšanas rīkus",
"bufferSettings": "Iespējot buferzonas opciju",
"defaultDistance": "Noklusējuma attālums",
"bufferDistance": "Buferzonas attālums",
"defaultUnit": "Noklusējuma vienība",
"miles": "Jūdzes",
"kilometers": "Kilometri",
"feet": "Pēdas",
"meters": "Metri",
"yards": "Jardi",
"nauticalMiles": "Jūras jūdzes",
"availableSpatialRelationships": "Izvēlēties telpisko attiecību noteikumus",
"setSpatialRelationships": "Iestatīt telpiskās attiecības",
"availability": "Pieejamība",
"relationship": "Attiecības",
"label": "Nosaukums",
"intersect": "šķērso",
"contain": "satur",
"areContainedIn": "ietilpst",
"cross": "krustojums",
"envelopeIntersect": "aploksne šķērso",
"overlap": "pārklāj",
"areOverlapped": "ir pārklāts",
"touch": "skāriens",
"within": "ietver",
"areWithin": "ietverts",
"indexIntersect": "indekss šķērso",
"itemTitle": "Vienības virsraksts",
"displayFields": "Rādīt laukus",
"sortingFields": "Kārtot rezultāta vienības",
"setDisplayFields": "Iestatīt rādāmos laukus",
"symbol": "Simbols",
"setSymbol": "Izmantot pielāgotu simbolu",
"changeSymbolAtRuntime": "Atļaut mainīt simbolus izpildlaikā",
"serviceSymbolTip": "Izmantot slāņa definētos simbolus",
"exportTip": "Atļaut eksportēt rezultātus",
"keepResultsTip": "Pēc logrīka aizvēršanas paturēt rezultātus kartē",
"queryRelatedRecords": "Izpildīt vaicājumu saistītajos ierakstos",
"createLayerForTaskTip": "Norādīt, kā vaicājuma uzdevums izveido slāņus",
"oneLayerForTaskTip": "Pārrakstīt slāni katru reizi, kad tiek izpildīts vaicājums",
"multipleLayerForTaskTip": "Izveidot jaunu slāni katru reizi, kad tiek izpildīts uzdevums",
"makeDefault": "Padarīt par noklusējumu",
"icon": "Ikona",
"newTask": "Jauns uzdevums",
"addTaskTip": "Pievienojiet logrīkam vienu vai vairākus vaicājumus un konfigurējiet parametrus katram no tiem.",
"webMapPopupTip": "Tīmekļa kartē izmantot slāņa uznirstošā loga konfigurāciju",
"customPopupTip": "Konfigurēt pielāgotu saturu",
"showResultsSetActions": "Rādīt rezultātu kopas darbības",
"zoomTo": "Pietuvināt",
"openAttributeTable": "Skatīt atribūtu tabulā",
"content": "Saturs",
"displaySQLTip": "Parādīt SQL izteiksmi lietotājiem",
"useLayerDefaultSymbol": "Izmantot slāņa noklusējuma simbolu",
"setCustomIcon": "Iestatīt pielāgotu ikonu",
"layerDefaultSymbolTip": "Izmantot slāņa noklusējuma simbolu",
"uploadImage": "Augšupielādēt attēlu",
"attributeCriteira": "Atribūtu kritēriji",
"specifyFilterAtRuntimeTip": "Lietotājiem būs jānorāda šīs izteiksmes parametri.",
"value": "VĒRTĪBA",
"hideLayersTip": "Izslēgt vaicājumu rezultātu slāņus, kad logrīks ir aizvērts.",
"tabLabels": "Cilņu nosaukumi",
"tasks": "Uzdevumi",
"queryCriteira": "Vaicājuma kritēriji",
"allowCustomQuery": "Atļaut izveidot pielāgotu vaicājumu",
"showFilterLabelTip": "Rādīt filtra iezīmes",
"querySettings": "Vaicājumu iestatījumi",
"expandTip": "Izvērst rezultātu sarakstu pēc noklusējuma",
"customResultNameTip": "Rādīt opciju, lai konfigurētu pielāgoto <strong>rezultātu slāņa nosaukumu</strong>"
}); |
/**!
* AngularJS file upload/drop directive with http post and progress
* @author Danial <danial.farid@gmail.com>
* @version 1.3.1
*/
(function() {
var angularFileUpload = angular.module('angularFileUpload', []);
angularFileUpload.service('$upload', ['$http', '$timeout', function($http, $timeout) {
function sendHttp(config) {
config.method = config.method || 'POST';
config.headers = config.headers || {};
config.transformRequest = config.transformRequest || function(data, headersGetter) {
if (window.ArrayBuffer && data instanceof window.ArrayBuffer) {
return data;
}
return $http.defaults.transformRequest[0](data, headersGetter);
};
if (window.XMLHttpRequest.__isShim) {
config.headers['__setXHR_'] = function() {
return function(xhr) {
config.__XHR = xhr;
config.xhrFn && config.xhrFn(xhr);
xhr.upload.addEventListener('progress', function(e) {
if (config.progress) {
$timeout(function() {
if(config.progress) config.progress(e);
});
}
}, false);
//fix for firefox not firing upload progress end, also IE8-9
xhr.upload.addEventListener('load', function(e) {
if (e.lengthComputable) {
$timeout(function() {
if(config.progress) config.progress(e);
});
}
}, false);
}
};
}
var promise = $http(config);
promise.progress = function(fn) {
config.progress = fn;
return promise;
};
promise.abort = function() {
if (config.__XHR) {
$timeout(function() {
config.__XHR.abort();
});
}
return promise;
};
promise.xhr = function(fn) {
config.xhrFn = fn;
return promise;
};
promise.then = (function(promise, origThen) {
return function(s, e, p) {
config.progress = p || config.progress;
var result = origThen.apply(promise, [s, e, p]);
result.abort = promise.abort;
result.progress = promise.progress;
result.xhr = promise.xhr;
return result;
};
})(promise, promise.then);
return promise;
}
this.upload = function(config) {
config.headers = config.headers || {};
config.headers['Content-Type'] = undefined;
config.transformRequest = config.transformRequest || $http.defaults.transformRequest;
var formData = new FormData();
var origTransformRequest = config.transformRequest;
var origData = config.data;
config.transformRequest = function(formData, headerGetter) {
if (origData) {
if (config.formDataAppender) {
for (var key in origData) {
var val = origData[key];
config.formDataAppender(formData, key, val);
}
} else {
for (var key in origData) {
var val = origData[key];
if (typeof origTransformRequest == 'function') {
val = origTransformRequest(val, headerGetter);
} else {
for (var i = 0; i < origTransformRequest.length; i++) {
var transformFn = origTransformRequest[i];
if (typeof transformFn == 'function') {
val = transformFn(val, headerGetter);
}
}
}
formData.append(key, val);
}
}
}
if (config.file != null) {
var fileFormName = config.fileFormDataName || 'file';
if (Object.prototype.toString.call(config.file) === '[object Array]') {
var isFileFormNameString = Object.prototype.toString.call(fileFormName) === '[object String]';
for (var i = 0; i < config.file.length; i++) {
formData.append(isFileFormNameString ? fileFormName + i : fileFormName[i], config.file[i], config.file[i].name);
}
} else {
formData.append(fileFormName, config.file, config.file.name);
}
}
return formData;
};
config.data = formData;
return sendHttp(config);
};
this.http = function(config) {
return sendHttp(config);
}
}]);
angularFileUpload.directive('ngFileSelect', [ '$parse', '$timeout', function($parse, $timeout) {
return function(scope, elem, attr) {
var fn = $parse(attr['ngFileSelect']);
elem.bind('change', function(evt) {
var files = [], fileList, i;
fileList = evt.target.files;
if (fileList != null) {
for (i = 0; i < fileList.length; i++) {
files.push(fileList.item(i));
}
}
$timeout(function() {
fn(scope, {
$files : files,
$event : evt
});
});
});
elem.bind('click', function(){
this.value = null;
});
};
} ]);
angularFileUpload.directive('ngFileDropAvailable', [ '$parse', '$timeout', function($parse, $timeout) {
return function(scope, elem, attr) {
if ('draggable' in document.createElement('span')) {
var fn = $parse(attr['ngFileDropAvailable']);
$timeout(function() {
fn(scope);
});
}
};
} ]);
angularFileUpload.directive('ngFileDrop', [ '$parse', '$timeout', function($parse, $timeout) {
return function(scope, elem, attr) {
if ('draggable' in document.createElement('span')) {
var cancel = null;
var fn = $parse(attr['ngFileDrop']);
elem[0].addEventListener("dragover", function(evt) {
$timeout.cancel(cancel);
evt.stopPropagation();
evt.preventDefault();
elem.addClass(attr['ngFileDragOverClass'] || "dragover");
}, false);
elem[0].addEventListener("dragleave", function(evt) {
cancel = $timeout(function() {
elem.removeClass(attr['ngFileDragOverClass'] || "dragover");
});
}, false);
var processing = 0;
function traverseFileTree(files, item) {
if (item.isDirectory) {
var dirReader = item.createReader();
processing++;
dirReader.readEntries(function(entries) {
for (var i = 0; i < entries.length; i++) {
traverseFileTree(files, entries[i]);
}
processing--;
});
} else {
processing++;
item.file(function(file) {
processing--;
files.push(file);
});
}
}
elem[0].addEventListener("drop", function(evt) {
evt.stopPropagation();
evt.preventDefault();
elem.removeClass(attr['ngFileDragOverClass'] || "dragover");
var files = [], items = evt.dataTransfer.items;
if (items && items.length > 0 && items[0].webkitGetAsEntry) {
for (var i = 0; i < items.length; i++) {
traverseFileTree(files, items[i].webkitGetAsEntry());
}
} else {
var fileList = evt.dataTransfer.files;
if (fileList != null) {
for (var i = 0; i < fileList.length; i++) {
files.push(fileList.item(i));
}
}
}
(function callback(delay) {
$timeout(function() {
if (!processing) {
fn(scope, {
$files : files,
$event : evt
});
} else {
callback(10);
}
}, delay || 0)
})();
}, false);
}
};
} ]);
})();
|
/**
* @file test for rule css-in-head
* @author nighca<nighca@live.cn>
*/
var path = require('path');
var htmlcs = require('../../../../');
var parse = require('../../../../lib/parse');
var rule = path.basename(__dirname);
describe('rule ' + rule, function () {
var result = htmlcs.hintFile(path.join(__dirname, 'case.html'));
it('should return right result', function () {
expect(result.length).toBe(2);
expect(result[0].type).toBe('WARN');
expect(result[0].code).toBe('008');
expect(result[0].line).toBe(16);
expect(result[0].column).toBe(5);
expect(result[1].type).toBe('WARN');
expect(result[1].code).toBe('008');
expect(result[1].line).toBe(21);
expect(result[1].column).toBe(5);
});
});
describe('format rule ' + rule, function () {
var result = htmlcs.formatFile(path.join(__dirname, 'case.html'));
var document = parse(result);
var head = document.querySelector('head');
var styles = document.querySelectorAll('link[rel="stylesheet"], style');
it('should format well', function () {
for (var i = 0, l = styles.length; i < l; i++) {
expect(head.contains(styles[i])).toBe(true);
}
});
});
|
module.exports={A:{A:{"2":"K D G E A B iB"},B:{"1":"AB","260":"2 C d J M H I"},C:{"1":"0 1 3 4 7 8 9 y z IB BB CB DB GB","2":"2 fB FB F N K D G E A B C d J M H I O ZB YB","66":"P Q","260":"6 R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x"},D:{"1":"3 4 9 IB BB CB DB GB SB OB MB lB NB KB AB PB QB","2":"2 F N K D G E A B C d J M H I O P Q R S T U V W","260":"0 1 6 7 8 X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z"},E:{"1":"5 E A B C WB XB p aB","2":"F N K D G RB JB TB UB VB"},F:{"1":"0 1 6 J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z","2":"E B C bB cB dB eB p EB gB","132":"5"},G:{"1":"nB oB pB qB rB sB tB uB","2":"G JB hB HB jB kB LB mB"},H:{"132":"vB"},I:{"1":"4 0B 1B","2":"FB F wB xB yB zB HB"},J:{"2":"D A"},K:{"1":"L","2":"A B C p EB","132":"5"},L:{"1":"KB"},M:{"1":"3"},N:{"2":"A B"},O:{"1":"2B"},P:{"1":"F 3B 4B 5B 6B 7B"},Q:{"1":"8B"},R:{"1":"9B"},S:{"1":"AC"}},B:4,C:"CSS.supports() API"};
|
/**
* @class Autolinker
* @extends Object
*
* Utility class used to process a given string of text, and wrap the matches in
* the appropriate anchor (<a>) tags to turn them into links.
*
* Any of the configuration options may be provided in an Object (map) provided
* to the Autolinker constructor, which will configure how the {@link #link link()}
* method will process the links.
*
* For example:
*
* var autolinker = new Autolinker( {
* newWindow : false,
* truncate : 30
* } );
*
* var html = autolinker.link( "Joe went to www.yahoo.com" );
* // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>'
*
*
* The {@link #static-link static link()} method may also be used to inline
* options into a single call, which may be more convenient for one-off uses.
* For example:
*
* var html = Autolinker.link( "Joe went to www.yahoo.com", {
* newWindow : false,
* truncate : 30
* } );
* // produces: 'Joe went to <a href="http://www.yahoo.com">yahoo.com</a>'
*
*
* ## Custom Replacements of Links
*
* If the configuration options do not provide enough flexibility, a {@link #replaceFn}
* may be provided to fully customize the output of Autolinker. This function is
* called once for each URL/Email/Phone#/Twitter Handle/Hashtag match that is
* encountered.
*
* For example:
*
* var input = "..."; // string with URLs, Email Addresses, Phone #s, Twitter Handles, and Hashtags
*
* var linkedText = Autolinker.link( input, {
* replaceFn : function( autolinker, match ) {
* console.log( "href = ", match.getAnchorHref() );
* console.log( "text = ", match.getAnchorText() );
*
* switch( match.getType() ) {
* case 'url' :
* console.log( "url: ", match.getUrl() );
*
* if( match.getUrl().indexOf( 'mysite.com' ) === -1 ) {
* var tag = autolinker.getTagBuilder().build( match ); // returns an `Autolinker.HtmlTag` instance, which provides mutator methods for easy changes
* tag.setAttr( 'rel', 'nofollow' );
* tag.addClass( 'external-link' );
*
* return tag;
*
* } else {
* return true; // let Autolinker perform its normal anchor tag replacement
* }
*
* case 'email' :
* var email = match.getEmail();
* console.log( "email: ", email );
*
* if( email === "my@own.address" ) {
* return false; // don't auto-link this particular email address; leave as-is
* } else {
* return; // no return value will have Autolinker perform its normal anchor tag replacement (same as returning `true`)
* }
*
* case 'phone' :
* var phoneNumber = match.getPhoneNumber();
* console.log( phoneNumber );
*
* return '<a href="http://newplace.to.link.phone.numbers.to/">' + phoneNumber + '</a>';
*
* case 'twitter' :
* var twitterHandle = match.getTwitterHandle();
* console.log( twitterHandle );
*
* return '<a href="http://newplace.to.link.twitter.handles.to/">' + twitterHandle + '</a>';
*
* case 'hashtag' :
* var hashtag = match.getHashtag();
* console.log( hashtag );
*
* return '<a href="http://newplace.to.link.hashtag.handles.to/">' + hashtag + '</a>';
* }
* }
* } );
*
*
* The function may return the following values:
*
* - `true` (Boolean): Allow Autolinker to replace the match as it normally
* would.
* - `false` (Boolean): Do not replace the current match at all - leave as-is.
* - Any String: If a string is returned from the function, the string will be
* used directly as the replacement HTML for the match.
* - An {@link Autolinker.HtmlTag} instance, which can be used to build/modify
* an HTML tag before writing out its HTML text.
*
* @constructor
* @param {Object} [cfg] The configuration options for the Autolinker instance,
* specified in an Object (map).
*/
var Autolinker = function( cfg ) {
cfg = cfg || {};
this.version = Autolinker.version;
this.urls = this.normalizeUrlsCfg( cfg.urls );
this.email = typeof cfg.email === 'boolean' ? cfg.email : true;
this.twitter = typeof cfg.twitter === 'boolean' ? cfg.twitter : true;
this.phone = typeof cfg.phone === 'boolean' ? cfg.phone : true;
this.hashtag = cfg.hashtag || false;
this.newWindow = typeof cfg.newWindow === 'boolean' ? cfg.newWindow : true;
this.stripPrefix = typeof cfg.stripPrefix === 'boolean' ? cfg.stripPrefix : true;
// Validate the value of the `hashtag` cfg.
var hashtag = this.hashtag;
if( hashtag !== false && hashtag !== 'twitter' && hashtag !== 'facebook' && hashtag !== 'instagram' ) {
throw new Error( "invalid `hashtag` cfg - see docs" );
}
this.truncate = this.normalizeTruncateCfg( cfg.truncate );
this.className = cfg.className || '';
this.replaceFn = cfg.replaceFn || null;
this.htmlParser = null;
this.matchers = null;
this.tagBuilder = null;
};
/**
* Automatically links URLs, Email addresses, Phone Numbers, Twitter handles,
* and Hashtags found in the given chunk of HTML. Does not link URLs found
* within HTML tags.
*
* For instance, if given the text: `You should go to http://www.yahoo.com`,
* then the result will be `You should go to <a href="http://www.yahoo.com">http://www.yahoo.com</a>`
*
* Example:
*
* var linkedText = Autolinker.link( "Go to google.com", { newWindow: false } );
* // Produces: "Go to <a href="http://google.com">google.com</a>"
*
* @static
* @param {String} textOrHtml The HTML or text to find matches within (depending
* on if the {@link #urls}, {@link #email}, {@link #phone}, {@link #twitter},
* and {@link #hashtag} options are enabled).
* @param {Object} [options] Any of the configuration options for the Autolinker
* class, specified in an Object (map). See the class description for an
* example call.
* @return {String} The HTML text, with matches automatically linked.
*/
Autolinker.link = function( textOrHtml, options ) {
var autolinker = new Autolinker( options );
return autolinker.link( textOrHtml );
};
/**
* @static
* @property {String} version (readonly)
*
* The Autolinker version number in the form major.minor.patch
*
* Ex: 0.25.1
*/
Autolinker.version = '/* @echo VERSION */';
Autolinker.prototype = {
constructor : Autolinker, // fix constructor property
/**
* @cfg {Boolean/Object} [urls=true]
*
* `true` if URLs should be automatically linked, `false` if they should not
* be.
*
* This option also accepts an Object form with 3 properties, to allow for
* more customization of what exactly gets linked. All default to `true`:
*
* @param {Boolean} schemeMatches `true` to match URLs found prefixed with a
* scheme, i.e. `http://google.com`, or `other+scheme://google.com`,
* `false` to prevent these types of matches.
* @param {Boolean} wwwMatches `true` to match urls found prefixed with
* `'www.'`, i.e. `www.google.com`. `false` to prevent these types of
* matches. Note that if the URL had a prefixed scheme, and
* `schemeMatches` is true, it will still be linked.
* @param {Boolean} tldMatches `true` to match URLs with known top level
* domains (.com, .net, etc.) that are not prefixed with a scheme or
* `'www.'`. This option attempts to match anything that looks like a URL
* in the given text. Ex: `google.com`, `asdf.org/?page=1`, etc. `false`
* to prevent these types of matches.
*/
/**
* @cfg {Boolean} [email=true]
*
* `true` if email addresses should be automatically linked, `false` if they
* should not be.
*/
/**
* @cfg {Boolean} [twitter=true]
*
* `true` if Twitter handles ("@example") should be automatically linked,
* `false` if they should not be.
*/
/**
* @cfg {Boolean} [phone=true]
*
* `true` if Phone numbers ("(555)555-5555") should be automatically linked,
* `false` if they should not be.
*/
/**
* @cfg {Boolean/String} [hashtag=false]
*
* A string for the service name to have hashtags (ex: "#myHashtag")
* auto-linked to. The currently-supported values are:
*
* - 'twitter'
* - 'facebook'
* - 'instagram'
*
* Pass `false` to skip auto-linking of hashtags.
*/
/**
* @cfg {Boolean} [newWindow=true]
*
* `true` if the links should open in a new window, `false` otherwise.
*/
/**
* @cfg {Boolean} [stripPrefix=true]
*
* `true` if 'http://' or 'https://' and/or the 'www.' should be stripped
* from the beginning of URL links' text, `false` otherwise.
*/
/**
* @cfg {Number/Object} [truncate=0]
*
* ## Number Form
*
* A number for how many characters matched text should be truncated to
* inside the text of a link. If the matched text is over this number of
* characters, it will be truncated to this length by adding a two period
* ellipsis ('..') to the end of the string.
*
* For example: A url like 'http://www.yahoo.com/some/long/path/to/a/file'
* truncated to 25 characters might look something like this:
* 'yahoo.com/some/long/pat..'
*
* Example Usage:
*
* truncate: 25
*
*
* Defaults to `0` for "no truncation."
*
*
* ## Object Form
*
* An Object may also be provided with two properties: `length` (Number) and
* `location` (String). `location` may be one of the following: 'end'
* (default), 'middle', or 'smart'.
*
* Example Usage:
*
* truncate: { length: 25, location: 'middle' }
*
* @cfg {Number} [truncate.length=0] How many characters to allow before
* truncation will occur. Defaults to `0` for "no truncation."
* @cfg {"end"/"middle"/"smart"} [truncate.location="end"]
*
* - 'end' (default): will truncate up to the number of characters, and then
* add an ellipsis at the end. Ex: 'yahoo.com/some/long/pat..'
* - 'middle': will truncate and add the ellipsis in the middle. Ex:
* 'yahoo.com/s..th/to/a/file'
* - 'smart': for URLs where the algorithm attempts to strip out unnecessary
* parts first (such as the 'www.', then URL scheme, hash, etc.),
* attempting to make the URL human-readable before looking for a good
* point to insert the ellipsis if it is still too long. Ex:
* 'yahoo.com/some..to/a/file'. For more details, see
* {@link Autolinker.truncate.TruncateSmart}.
*/
/**
* @cfg {String} className
*
* A CSS class name to add to the generated links. This class will be added
* to all links, as well as this class plus match suffixes for styling
* url/email/phone/twitter/hashtag links differently.
*
* For example, if this config is provided as "myLink", then:
*
* - URL links will have the CSS classes: "myLink myLink-url"
* - Email links will have the CSS classes: "myLink myLink-email", and
* - Twitter links will have the CSS classes: "myLink myLink-twitter"
* - Phone links will have the CSS classes: "myLink myLink-phone"
* - Hashtag links will have the CSS classes: "myLink myLink-hashtag"
*/
/**
* @cfg {Function} replaceFn
*
* A function to individually process each match found in the input string.
*
* See the class's description for usage.
*
* This function is called with the following parameters:
*
* @cfg {Autolinker} replaceFn.autolinker The Autolinker instance, which may
* be used to retrieve child objects from (such as the instance's
* {@link #getTagBuilder tag builder}).
* @cfg {Autolinker.match.Match} replaceFn.match The Match instance which
* can be used to retrieve information about the match that the `replaceFn`
* is currently processing. See {@link Autolinker.match.Match} subclasses
* for details.
*/
/**
* @property {String} version (readonly)
*
* The Autolinker version number in the form major.minor.patch
*
* Ex: 0.25.1
*/
/**
* @private
* @property {Autolinker.htmlParser.HtmlParser} htmlParser
*
* The HtmlParser instance used to skip over HTML tags, while finding text
* nodes to process. This is lazily instantiated in the {@link #getHtmlParser}
* method.
*/
/**
* @private
* @property {Autolinker.matcher.Matcher[]} matchers
*
* The {@link Autolinker.matcher.Matcher} instances for this Autolinker
* instance.
*
* This is lazily created in {@link #getMatchers}.
*/
/**
* @private
* @property {Autolinker.AnchorTagBuilder} tagBuilder
*
* The AnchorTagBuilder instance used to build match replacement anchor tags.
* Note: this is lazily instantiated in the {@link #getTagBuilder} method.
*/
/**
* Normalizes the {@link #urls} config into an Object with 3 properties:
* `schemeMatches`, `wwwMatches`, and `tldMatches`, all Booleans.
*
* See {@link #urls} config for details.
*
* @private
* @param {Boolean/Object} urls
* @return {Object}
*/
normalizeUrlsCfg : function( urls ) {
if( urls == null ) urls = true; // default to `true`
if( typeof urls === 'boolean' ) {
return { schemeMatches: urls, wwwMatches: urls, tldMatches: urls };
} else { // object form
return {
schemeMatches : typeof urls.schemeMatches === 'boolean' ? urls.schemeMatches : true,
wwwMatches : typeof urls.wwwMatches === 'boolean' ? urls.wwwMatches : true,
tldMatches : typeof urls.tldMatches === 'boolean' ? urls.tldMatches : true
};
}
},
/**
* Normalizes the {@link #truncate} config into an Object with 2 properties:
* `length` (Number), and `location` (String).
*
* See {@link #truncate} config for details.
*
* @private
* @param {Number/Object} truncate
* @return {Object}
*/
normalizeTruncateCfg : function( truncate ) {
if( typeof truncate === 'number' ) {
return { length: truncate, location: 'end' };
} else { // object, or undefined/null
return Autolinker.Util.defaults( truncate || {}, {
length : Number.POSITIVE_INFINITY,
location : 'end'
} );
}
},
/**
* Parses the input `textOrHtml` looking for URLs, email addresses, phone
* numbers, username handles, and hashtags (depending on the configuration
* of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
* objects describing those matches.
*
* This method is used by the {@link #link} method, but can also be used to
* simply do parsing of the input in order to discover what kinds of links
* there are and how many.
*
* @param {String} textOrHtml The HTML or text to find matches within
* (depending on if the {@link #urls}, {@link #email}, {@link #phone},
* {@link #twitter}, and {@link #hashtag} options are enabled).
* @return {Autolinker.match.Match[]} The array of Matches found in the
* given input `textOrHtml`.
*/
parse : function( textOrHtml ) {
var htmlParser = this.getHtmlParser(),
htmlNodes = htmlParser.parse( textOrHtml ),
anchorTagStackCount = 0, // used to only process text around anchor tags, and any inner text/html they may have;
matches = [];
// Find all matches within the `textOrHtml` (but not matches that are
// already nested within <a> tags)
for( var i = 0, len = htmlNodes.length; i < len; i++ ) {
var node = htmlNodes[ i ],
nodeType = node.getType();
if( nodeType === 'element' && node.getTagName() === 'a' ) { // Process HTML anchor element nodes in the input `textOrHtml` to find out when we're within an <a> tag
if( !node.isClosing() ) { // it's the start <a> tag
anchorTagStackCount++;
} else { // it's the end </a> tag
anchorTagStackCount = Math.max( anchorTagStackCount - 1, 0 ); // attempt to handle extraneous </a> tags by making sure the stack count never goes below 0
}
} else if( nodeType === 'text' && anchorTagStackCount === 0 ) { // Process text nodes that are not within an <a> tag
var textNodeMatches = this.parseText( node.getText(), node.getOffset() );
matches.push.apply( matches, textNodeMatches );
}
}
// After we have found all matches, remove subsequent matches that
// overlap with a previous match. This can happen for instance with URLs,
// where the url 'google.com/#link' would match '#link' as a hashtag.
matches = this.compactMatches( matches );
// And finally, remove matches for match types that have been turned
// off. We needed to have all match types turned on initially so that
// things like hashtags could be filtered out if they were really just
// part of a URL match (for instance, as a named anchor).
matches = this.removeUnwantedMatches( matches );
return matches;
},
/**
* After we have found all matches, we need to remove subsequent matches
* that overlap with a previous match. This can happen for instance with
* URLs, where the url 'google.com/#link' would match '#link' as a hashtag.
*
* @private
* @param {Autolinker.match.Match[]} matches
* @return {Autolinker.match.Match[]}
*/
compactMatches : function( matches ) {
// First, the matches need to be sorted in order of offset
matches.sort( function( a, b ) { return a.getOffset() - b.getOffset(); } );
for( var i = 0; i < matches.length - 1; i++ ) {
var match = matches[ i ],
endIdx = match.getOffset() + match.getMatchedText().length;
// Remove subsequent matches that overlap with the current match
while( i + 1 < matches.length && matches[ i + 1 ].getOffset() <= endIdx ) {
matches.splice( i + 1, 1 );
}
}
return matches;
},
/**
* Removes matches for matchers that were turned off in the options. For
* example, if {@link #hashtag hashtags} were not to be matched, we'll
* remove them from the `matches` array here.
*
* @private
* @param {Autolinker.match.Match[]} matches The array of matches to remove
* the unwanted matches from. Note: this array is mutated for the
* removals.
* @return {Autolinker.match.Match[]} The mutated input `matches` array.
*/
removeUnwantedMatches : function( matches ) {
var remove = Autolinker.Util.remove;
if( !this.hashtag ) remove( matches, function( match ) { return match.getType() === 'hashtag'; } );
if( !this.email ) remove( matches, function( match ) { return match.getType() === 'email'; } );
if( !this.phone ) remove( matches, function( match ) { return match.getType() === 'phone'; } );
if( !this.twitter ) remove( matches, function( match ) { return match.getType() === 'twitter'; } );
if( !this.urls.schemeMatches ) {
remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'scheme'; } );
}
if( !this.urls.wwwMatches ) {
remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'www'; } );
}
if( !this.urls.tldMatches ) {
remove( matches, function( m ) { return m.getType() === 'url' && m.getUrlMatchType() === 'tld'; } );
}
return matches;
},
/**
* Parses the input `text` looking for URLs, email addresses, phone
* numbers, username handles, and hashtags (depending on the configuration
* of the Autolinker instance), and returns an array of {@link Autolinker.match.Match}
* objects describing those matches.
*
* This method processes a **non-HTML string**, and is used to parse and
* match within the text nodes of an HTML string. This method is used
* internally by {@link #parse}.
*
* @private
* @param {String} text The text to find matches within (depending on if the
* {@link #urls}, {@link #email}, {@link #phone}, {@link #twitter}, and
* {@link #hashtag} options are enabled). This must be a non-HTML string.
* @param {Number} [offset=0] The offset of the text node within the
* original string. This is used when parsing with the {@link #parse}
* method to generate correct offsets within the {@link Autolinker.match.Match}
* instances, but may be omitted if calling this method publicly.
* @return {Autolinker.match.Match[]} The array of Matches found in the
* given input `text`.
*/
parseText : function( text, offset ) {
offset = offset || 0;
var matchers = this.getMatchers(),
matches = [];
for( var i = 0, numMatchers = matchers.length; i < numMatchers; i++ ) {
var textMatches = matchers[ i ].parseMatches( text );
// Correct the offset of each of the matches. They are originally
// the offset of the match within the provided text node, but we
// need to correct them to be relative to the original HTML input
// string (i.e. the one provided to #parse).
for( var j = 0, numTextMatches = textMatches.length; j < numTextMatches; j++ ) {
textMatches[ j ].setOffset( offset + textMatches[ j ].getOffset() );
}
matches.push.apply( matches, textMatches );
}
return matches;
},
/**
* Automatically links URLs, Email addresses, Phone numbers, Twitter
* handles, and Hashtags found in the given chunk of HTML. Does not link
* URLs found within HTML tags.
*
* For instance, if given the text: `You should go to http://www.yahoo.com`,
* then the result will be `You should go to
* <a href="http://www.yahoo.com">http://www.yahoo.com</a>`
*
* This method finds the text around any HTML elements in the input
* `textOrHtml`, which will be the text that is processed. Any original HTML
* elements will be left as-is, as well as the text that is already wrapped
* in anchor (<a>) tags.
*
* @param {String} textOrHtml The HTML or text to autolink matches within
* (depending on if the {@link #urls}, {@link #email}, {@link #phone},
* {@link #twitter}, and {@link #hashtag} options are enabled).
* @return {String} The HTML, with matches automatically linked.
*/
link : function( textOrHtml ) {
if( !textOrHtml ) { return ""; } // handle `null` and `undefined`
var matches = this.parse( textOrHtml ),
newHtml = [],
lastIndex = 0;
for( var i = 0, len = matches.length; i < len; i++ ) {
var match = matches[ i ];
newHtml.push( textOrHtml.substring( lastIndex, match.getOffset() ) );
newHtml.push( this.createMatchReturnVal( match ) );
lastIndex = match.getOffset() + match.getMatchedText().length;
}
newHtml.push( textOrHtml.substring( lastIndex ) ); // handle the text after the last match
return newHtml.join( '' );
},
/**
* Creates the return string value for a given match in the input string.
*
* This method handles the {@link #replaceFn}, if one was provided.
*
* @private
* @param {Autolinker.match.Match} match The Match object that represents
* the match.
* @return {String} The string that the `match` should be replaced with.
* This is usually the anchor tag string, but may be the `matchStr` itself
* if the match is not to be replaced.
*/
createMatchReturnVal : function( match ) {
// Handle a custom `replaceFn` being provided
var replaceFnResult;
if( this.replaceFn ) {
replaceFnResult = this.replaceFn.call( this, this, match ); // Autolinker instance is the context, and the first arg
}
if( typeof replaceFnResult === 'string' ) {
return replaceFnResult; // `replaceFn` returned a string, use that
} else if( replaceFnResult === false ) {
return match.getMatchedText(); // no replacement for the match
} else if( replaceFnResult instanceof Autolinker.HtmlTag ) {
return replaceFnResult.toAnchorString();
} else { // replaceFnResult === true, or no/unknown return value from function
// Perform Autolinker's default anchor tag generation
var anchorTag = match.buildTag(); // returns an Autolinker.HtmlTag instance
return anchorTag.toAnchorString();
}
},
/**
* Lazily instantiates and returns the {@link #htmlParser} instance for this
* Autolinker instance.
*
* @protected
* @return {Autolinker.htmlParser.HtmlParser}
*/
getHtmlParser : function() {
var htmlParser = this.htmlParser;
if( !htmlParser ) {
htmlParser = this.htmlParser = new Autolinker.htmlParser.HtmlParser();
}
return htmlParser;
},
/**
* Lazily instantiates and returns the {@link Autolinker.matcher.Matcher}
* instances for this Autolinker instance.
*
* @protected
* @return {Autolinker.matcher.Matcher[]}
*/
getMatchers : function() {
if( !this.matchers ) {
var matchersNs = Autolinker.matcher,
tagBuilder = this.getTagBuilder();
var matchers = [
new matchersNs.Hashtag( { tagBuilder: tagBuilder, serviceName: this.hashtag } ),
new matchersNs.Email( { tagBuilder: tagBuilder } ),
new matchersNs.Phone( { tagBuilder: tagBuilder } ),
new matchersNs.Twitter( { tagBuilder: tagBuilder } ),
new matchersNs.Url( { tagBuilder: tagBuilder, stripPrefix: this.stripPrefix } )
];
return ( this.matchers = matchers );
} else {
return this.matchers;
}
},
/**
* Returns the {@link #tagBuilder} instance for this Autolinker instance, lazily instantiating it
* if it does not yet exist.
*
* This method may be used in a {@link #replaceFn} to generate the {@link Autolinker.HtmlTag HtmlTag} instance that
* Autolinker would normally generate, and then allow for modifications before returning it. For example:
*
* var html = Autolinker.link( "Test google.com", {
* replaceFn : function( autolinker, match ) {
* var tag = autolinker.getTagBuilder().build( match ); // returns an {@link Autolinker.HtmlTag} instance
* tag.setAttr( 'rel', 'nofollow' );
*
* return tag;
* }
* } );
*
* // generated html:
* // Test <a href="http://google.com" target="_blank" rel="nofollow">google.com</a>
*
* @return {Autolinker.AnchorTagBuilder}
*/
getTagBuilder : function() {
var tagBuilder = this.tagBuilder;
if( !tagBuilder ) {
tagBuilder = this.tagBuilder = new Autolinker.AnchorTagBuilder( {
newWindow : this.newWindow,
truncate : this.truncate,
className : this.className
} );
}
return tagBuilder;
}
};
// Autolinker Namespaces
Autolinker.match = {};
Autolinker.matcher = {};
Autolinker.htmlParser = {};
Autolinker.truncate = {};
|
"use strict";
/*
*
* ooiui/static/js/models/aa/AlertFilterView.js
* Validation model for Alerts and Alarms Page.
*
* Dependencies
* Partials
* - ooiui/static/js/partials/compiled/alertPage.js
* Libs
* - ooiui/static/lib/underscore/underscore.js
* - ooiui/static/lib/backbone/backbone.js
* Usage
*
*/
Backbone.Validation.configure({
forceUpdate: true
});
_.extend(Backbone.Validation.callbacks, {
valid: function (view, attr, selector) {
var $el = view.$('[name=' + attr + ']'),
$group = $el.closest('.form-group');
$group.removeClass('has-error');
$group.find('.help-block').html('').addClass('hidden');
},
invalid: function (view, attr, error, selector) {
var $el = view.$('[name=' + attr + ']'),
$group = $el.closest('.form-group');
$group.addClass('has-error');
$group.find('.help-block').html(error).removeClass('hidden');
}
});
var AlertFilterView = Backbone.View.extend({
events: {
/*'click #saveAlert': function (e) {
e.preventDefault();
this.submit();
}*/
},
// Use stickit to perform binding between
// the model and the view
bindings: {
'[name=array]': {
observe: 'array',
selectOptions: {
collection: []
},
setOptions: {
validate:false
}
},
'[name=Platform]': {
observe: 'Platform',
setOptions: {
validate: false
}
},
'[name=Instrument]': {
observe: 'Instrument',
selectOptions:{
collections: []
},
setOptions: {
validate: false
}
},
'[name=Email]': {
observe: 'Email',
setOptions: {
validate: false
}
},
'[name=Redmine]': {
observe: 'Redmine',
setOptions: {
validate: false
}
},
'[name=PhoneCall]': {
observe: 'PhoneCall',
setOptions: {
validate: true
}
},
'[name=TextMessage]': {
observe: 'TextMessage',
setOptions: {
validate: false
}
},
'[name=LogEvent]': {
observe: 'LogEvent',
setOptions: {
validate: false
}
}
},
initialRender: function() {
this.$el.html('<i class="fa fa-spinner fa-spin" style="margin-top:50px;margin-left:50%;font-size:90px;color:#337ab7;"> </i>');
},
initialize: function () {
Backbone.Validation.bind(this);
_.bindAll(this, "render","filterOptionsbyInstrument","showtypeoptions","showenabledoptions" );
var self = this;
self.modalDialog = new ModalDialogView();
//this.listenTo(this.collection, 'reset', function(){
//self.render();
//});
},
render: function () {
var self = this;
var AlertsFullCollectionPage = Backbone.PageableCollection.extend({
model: AlertModel,
url:"/api/aa/alerts",
state: {
pageSize: 15,
sortKey: "id",
order: -1
},
mode: "client",
parse: function(response, options) {
//for the response after asset query
if(response.alert_alarm_definition){
return response.alert_alarm_definition;
}
else{
return response
}
}
});
var pageablealerts = new AlertsFullCollectionPage();
self.collection = pageablealerts;
var HtmlCell = Backgrid.HtmlCell = Backgrid.Cell.extend({
className: "html-cell",
initialize: function () {
Backgrid.Cell.prototype.initialize.apply(this, arguments);
},
render: function () {
this.$el.empty();
var rawValue = this.model.get(this.column.get("name"));
var formattedValue = this.formatter.fromRaw(rawValue, this.model);
this.$el.append(formattedValue);
this.delegateEvents();
return this;
}
});
var columns = [
/* {
name: "uframe_filter_id", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
cell: "string"
},*/
{
name: "id", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
sortable: true,
cell: "string"
},
{
name: "array_name", // The key of the model attribute
label: "Array", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
cell: "string"
},
{
name: "instrument_name",
label: "Instrument",
editable: false,
cell: "string",
sortValue: function (model, colName) {
return model.attributes[colName]['instrument_name'];
}
},
{
name: "stream",
label: "Stream",
editable: false,
cell: "string"
},
{
name: "instrument_parameter",
label: "Parameter",
editable: false,
cell: "string"
},
{
name: "instrument_parameter_pdid",
label: "PDID",
editable: false,
cell: "string"
},
{
name: "severity",
label: "Severity",
editable: false,
cell: "string",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue, model) {
return rawValue;
}
})
},
/* {
name: "created_time",
label: "Created",
editable: false,
cell: "string"
},*/
{
name: "event_type",
editable: false,
label: "Type",
cell: HtmlCell,
formatter: _.extend({}, Backgrid.Cell.prototype, {
fromRaw: function (rawValue, model) {
//place holder right now for triggered events
if(rawValue =='alarm'){
return "<div style='text-align: center'>Alarm</div>";
}
else if(rawValue =='alert'){
return "<div style='text-align: center'>Alert</div>";
}
}
})
},
{
name: "active",
editable: false,
label: "Active",
cell: HtmlCell,
formatter: _.extend({}, Backgrid.Cell.prototype, {
fromRaw: function (rawValue, model) {
//console.log(rawValue);
//place holder right now for triggered events
if(rawValue == 1){
//return "Active";
return "<div style='text-align: center'><i id='active_def' style='font-size:14px;float:right;padding-right: 20px;color:#3c763d' class='fa fa-thumbs-up'>Active</i></div>";
}
else if(rawValue == 0){
//return "Disabled";
return "<div style='text-align: center'><i id='active_def' style='font-size:14px;float:right;padding-right: 20px;color:#3c763d' class='fa fa-thumbs-down'>Disabled</i></div>";
}
}
})
},
{
name: "active",
editable: false,
label: "Enable/Disable",
cell: HtmlCell,
formatter: _.extend({}, Backgrid.Cell.prototype, {
fromRaw: function (rawValue, model) {
//console.log('Active Field');
//console.log(rawValue);
//console.log(model.attributes.retired);
//place holder right now for triggered events
if (model.attributes.retired == 0) {
if (rawValue == 1) {
return "<div style='text-align: center'><button type=\"button\" id=\"toggleActiveBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-minus-square\"></i> Disable Alert/Alarm" +
"</button></div>";
}
else if (rawValue == 0) {
return "<div style='text-align: center'><button type=\"button\" id=\"toggleActiveBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-plus-square\"></i> Enable Alert/Alarm" +
"</button></div>";
}
}
else {
return "Retired";
}
}
})
},
{
name: "active",
editable: false,
label: "Notifications",
cell: HtmlCell,
formatter: _.extend({}, Backgrid.Cell.prototype, {
fromRaw: function (rawValue, model) {
//console.log('Notification Field');
//console.log(rawValue);
//console.log(model);
//console.log(model.attributes.user_event_notification.use_redmine);
//console.log(model.attributes.retired);
//place holder right now for triggered events
if (model.attributes.retired == 0) {
if (model.attributes.user_event_notification.use_redmine) {
return "<div style='text-align: center'><button type=\"button\" id=\"toggleNotificationBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-minus-square\"></i> Toggle Off" +
"</button></div>";
}
else if (!model.attributes.user_event_notification.use_redmine) {
return "<div style='text-align: center'><button type=\"button\" id=\"toggleNotificationBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-plus-square\"></i> Toggle On" +
"</button></div>";
}
}
else {
return "Retired";
}
}
})
},
{
name: "retired",
editable: false,
label: "Retire",
cell: HtmlCell,
formatter: _.extend({}, Backgrid.Cell.prototype, {
fromRaw: function (rawValue, model) {
//console.log('Retired Field');
//console.log(rawValue);
//console.log(rawValue);
//place holder right now for triggered events
if(rawValue == 1){
return "Retired";
}
else {
return "<div style='text-align: center'><button type=\"button\" id=\"toggleRetireBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-bolt\"></i> Retire" +
"</button></div>";
}
}
})
}
/*,
{
name: "active",
editable: false,
label: "Acknowledge",
cell: HtmlCell,
formatter: _.extend({}, Backgrid.Cell.prototype, {
fromRaw: function (rawValue, model) {
//.log('Active Field');
//console.log(rawValue);
//console.log(model.attributes.retired);
//place holder right now for triggered events
if (model.attributes.retired == 0) {
if (rawValue == 1) {
return "<div style='text-align: center'><button disabled type=\"button\" id=\"ackAllInstancesBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-bolt\"></i> Ack All" +
"</button></div>";
}
else if (rawValue == 0) {
return "<div style='text-align: center'><button type=\"button\" id=\"ackAllInstancesBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-bolt\"></i> Ack All" +
"</button></div>";
}
}
else {
return "Retired";
}
}
})
},
{
name: "active",
editable: false,
label: "Clear",
cell: HtmlCell,
formatter: _.extend({}, Backgrid.Cell.prototype, {
fromRaw: function (rawValue, model) {
//console.log('Active Field');
//console.log(rawValue);
//console.log(model.attributes.retired);
//place holder right now for triggered events
if (model.attributes.retired == 0) {
if (rawValue == 1) {
return "<div style='text-align: center'><button disabled type=\"button\" id=\"clearAllInstancesBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-bolt\"></i> Clear All" +
"</button></div>";
}
else if (rawValue == 0) {
return "<div style='text-align: center'><button type=\"button\" id=\"clearAllInstancesBtn\" class=\"btn btn-primary\">" +
"<i class=\"fa fa-bolt\"></i> Clear All" +
"</button></div>";
}
}
else {
return "Retired";
}
}
})
}*/
];
//add click event
var ClickableRow = Backgrid.Row.extend({
highlightColor: "#eee",
events: {
"click": "onClick",
mouseover: "rowFocused",
mouseout: "rowLostFocus"
},
onClick: function (e) {
if ($(e.target).is('td')){
ooi.trigger("deployrowclicked", this.model);
}
this.el.style.backgroundColor = this.highlightColor;
// Clicked the toggle active/inactive button
if (e.target.id=='toggleActiveBtn') {
//console.log('clicked toggle active btn for def id: ' + this.model.attributes.id);
ooi.trigger('alertToggleActiveFormViewTrigger:onClick',
{
model: this.model,
active: this.model.attributes.active
}
);
}
// Clicked the toggle notification button
if (e.target.id=='toggleNotificationBtn') {
//console.log('clicked toggle notification btn for def id: ' + this.model.attributes.id);
ooi.trigger('alertToggleNotificationFormViewTrigger:onClick',
{
model: this.model
}
);
}
// Clicked the toggle notification button
if (e.target.id=='toggleRetireBtn') {
//console.log('clicked toggle notification btn for def id: ' + this.model.attributes.id);
ooi.trigger('alertToggleRetireFormViewTrigger:onClick',
{
model: this.model
}
);
}
/* // Clicked the ack all instances button
if (e.target.id=='ackAllInstancesBtn') {
//console.log('clicked ack all instances btn for def id: ' + this.model.attributes.id);
ooi.trigger('alertAckAllFormViewTrigger:onClick',
{
model: this.model
}
);
}
// Clicked the clear all instances button
if (e.target.id=='clearAllInstancesBtn') {
//console.log('clicked clear all instances btn for def id: ' + this.model.attributes.id);
ooi.trigger('alertClearAllFormViewTrigger:onClick',
{
model: this.model
}
);
}*/
//check to see if the condition met item has ben clicked and open triggered events
if(e.target.id=='condition_met'){
this.triggeredalertView = new TriggeredAlertDialogView();
$('.container-fluid').first().append(this.triggeredalertView.el);
this.triggeredalertView.show({
instrument: "Instrument Name: " + this.model.attributes.Instrument,
recent: "<i>None at this time</i>",
history: "<i style='color:#337ab7;' class='fa fa-spinner fa-spin fa-5x'></i>",
variable: this.model.attributes.reference_designator,
//ctype: "alert",
//title: this.model.attributes.display_name,
ack: function() { console.log("Closed");}
});
}
},
rowFocused: function() {
this.el.style.backgroundColor = this.highlightColor;
},
rowLostFocus: function() {
this.el.style.backgroundColor = '#FFF';
//document.getElementById('toggleActiveBtn').style.display = "none";
}
});
// Set up a grid to use the pageable collection
var pageableGrid = new Backgrid.Grid({
columns: columns,
collection: pageablealerts,
row: ClickableRow
});
// Render the grid and attach the root to your HTML document
$("#alertslist").append(pageableGrid.render().el);
// Initialize the paginator
var paginator = new Backgrid.Extension.Paginator({
goBackFirstOnSort: false, // Default is true
collection: pageablealerts
});
// Render the paginator
$("#alertslist").after(paginator.render().el);
var AssetFilter = Backgrid.Extension.ClientSideFilter.extend({
placeholder: "Search Alerts and Alarms",
makeMatcher: function(query){
var q = '';
if(query!=""){
q = String(query).toUpperCase();
}
return function (model) {
var queryhit= false;
if(model.attributes['instrument_name']){
if(String(model.attributes['instrument_name']).toUpperCase().search(q)>-1){
queryhit= true;
}
}
if(model.attributes['description']){
if(String(model.attributes['description']).toUpperCase().search(q)>-1){
queryhit= true;
}
}
if(model.attributes['array_name']){
if(String(model.attributes['array_name']).toUpperCase().search(q)>-1){
queryhit= true;
}
}
if(model.attributes['priority']){
if(String(model.attributes['priority']).toUpperCase().search(q)>-1){
queryhit= true;
}
}
return queryhit;
};
}
});
var filter = new AssetFilter({
collection: pageablealerts
});
self.filter = filter;
// Render the filter
$("#alertslist").before(filter.render().el);
// Add some space to the filter and move it to the right
$(filter.el).css({float: "left", margin: "0px 10px 25px 0px"});
$(filter.el).find("input").attr('id', 'alert_search_box');
pageablealerts.fetch({reset: true,
error: (function (e) {
alert(' Service request failure: ' + e);
}),
complete: (function (e) {
$('#loading_alerts').html('');
})
});
self.rownum = 1;
//remove row
$("#delete_row").click(function(){
if(self.rownum == 2){
$("#delete_row").hide();
}
if(self.rownum>1){
$("#addr"+(self.rownum-1)).html('');
self.rownum--;
}
});
//needs model to stickit not using right now
//this.stickit();
},
filterOptionsbyInstrument: function(instru_id,name){
var self = this;
return "<select class='form-control' data-container='body' id='conditions_dd"+this.rownum+"'><option value='m_lon'>Longitude</option><option value='m_lat'>Latitude</option><option value='sci_salinity'>Salinity</option><option value='sci_water_temp'>Temperature</option><option value='sci_water_cond'>Water Speed</option><option value='sci_wave_height'>Wave Height</option><option value='sci_water_pressure'>Water Pressure</option></select>";
},
showtypeoptions:function(){
return "<select data-show-icon='true' data-container='body' class='form-control' id='type_dd"+this.rownum+"'><option data-icon='glyphicon-flag' value='alert'>Alert</option><option data-icon='glyphicon-exclamation-sign' value='alarm'> Alarm</option></select>";
},
showenabledoptions:function(){
return "<select data-show-icon='true' data-container='body' class='form-control' id='enabled_dd"+this.rownum+"'><option data-icon='glyphicon-ok-sign' value='true'>True</option><option data-icon='glyphicon-minus-sign' value='false'> False</option></select>";
},
showenabledoperators:function(){
return "<select data-show-icon='true' data-container='body' class='form-control' id='operator_dd"+this.rownum+"'><option value='>'>></option><option value='<'> <</option><option value='='> =</option><option value='<>'> <></option><option value='>='> >=</option><option value='<='> <=</option><option value='outside'> outside</option><option value='inside'> inside</option></select>";
}
});
|
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define([
'dojo/_base/lang',
'dojo/Deferred',
'dojo/_base/html',
'dojo/_base/array',
'dojo/_base/declare',
'dojo/Evented',
// 'dojo/on',
'dojo/query',
'./ValueProvider',
'./EditTable',
'./AdvancedListValueSelect',
'dijit/_TemplatedMixin',
'dijit/_WidgetsInTemplateMixin',
'dojo/text!./PredefinedValuePopup.html',
'dojo/store/Memory',
'jimu/utils',
'jimu/dijit/Popup',
'jimu/dijit/_filter/pageControlForQuery',
'dojox/form/CheckedMultiSelect'
],
function(lang, Deferred, html, array, declare, Evented, query, ValueProvider,
EditTable, AdvancedListValueSelect, _TemplatedMixin,
_WidgetsInTemplateMixin,template, Memory, jimuUtils, Popup, pageControlForQuery, CheckedMultiSelect) {
return declare([ValueProvider, _TemplatedMixin, _WidgetsInTemplateMixin, Evented], {
templateString: template,
codedValues: null,//[{value,label}] for coded values and sub types
staticValues: null,//[{value,label}]
showNullValues: false,//show null values
cbxPopup: null,
pageSize: 1000, //page size
pageIndex:1, //current page
//optional
selectUI: null, //dropdown, expanded
postMixInProperties:function(){
this.inherited(arguments);
this.CommonNls = window.jimuNls.common;
this.Nls = window.jimuNls.filterBuilder;
this.emptyStr = window.apiNls.widgets.FeatureTable.empty;
},
postCreate: function(){
this.inherited(arguments);
this.selectUI = this.selectUI ? this.selectUI : 'dropdown';
html.addClass(this.domNode, 'jimu-filter-mutcheck-list-value-provider');
// this.layerName.innerText = this.layerDefinition.name;
this.controlType = 'unique'; //unique, multiple
if(this.providerType === 'MULTIPLE_PREDEFINED_VALUE_PROVIDER'){
this.controlType = 'multiple';
}
this.isNumberField = jimuUtils.isNumberField(this.fieldInfo.type);
if(!this.editTable){
this.editTable = new EditTable({
tableType: this.controlType,
dataList: [],
codedValues: this.codedValues,
emptyStr: this.emptyStr,
customValue: this.Nls.addValuePlaceHolder,
customLabel: this.Nls.addLabelPlaceHolder,
isNumberField: this.isNumberField
});
this.editTable.placeAt(this.tableContent);
this.editTable.on("editTable_openListSelectByName", lang.hitch(this, this._showListSelectByTable));
this.editTable.on("editTable_itemChanged", lang.hitch(this, this._editTableItemChanged));
this.editTable.on("editTable_getValLabelsArrayForNumber",
lang.hitch(this, this._getValLabelsArrayForNumber));
}
this.supportPaing = true;
if(!this.pageControlForQuery){
this.pageControlForQuery = new pageControlForQuery({
pageSize: this.pageSize,
pageIndex: 1,
layerUrl: this.url,
// layerInfo: this.layerInfo,
fieldInfo: this.fieldInfo,
queryWhere: '1=1',
layerDefinition: this.layerDefinition,
fieldPopupInfo: this.fieldPopupInfo,
// spatialReference: this.layerInfo.map.spatialReference,
isNumberField: this.isNumberField
});
}
if(!this.listSelect){
// this._initAdvancedListValueSelect();
this.listSelect = new AdvancedListValueSelect({
emptyStr: this.emptyStr,
runtime: this.runtime,
pageSize: this.pageSize,
// selectType: 'multiple',// when it's in header
selectType: 'unique',//when it's for single item
controlType: 'predefined',
dataList:[],
selectedDataList:[],
isNumberField: this.isNumberField
});
// this.listSelect.placeAt(this.listSelectStore);
// this.own(topic.subscribe("AdvancedListValueSelect/itemChecked", lang.hitch(this, this._createTarget)));
this.listSelect.on("advancedListValueSelect_itemChecked", lang.hitch(this, this._createTarget));
this.listSelect.on("advancedListValueSelect_itemUnChecked", lang.hitch(this, this._destoryTarget));
this.listSelect.on("advancedListValueSelect_addNextPage", lang.hitch(this, this._addNextPage));
this.listSelect.on("advancedListValueSelect_searchKey", lang.hitch(this, this._searchKey));
this.listSelect.on("advancedListValueSelect_searchKeyLocal", lang.hitch(this, this._searchKeyLocal));
this.listSelect.on("advancedListValueSelect_itemCheckedForPredefined",
lang.hitch(this, this._createTargetForPredefined));
}
if(!this.mutiValuesSelect){
this.mutiValuesSelect = new CheckedMultiSelect({
multiple: true,
required: false,
intermediateChanges: true, //Fires onChange for each value change or only on demand
style: {'width':'100%'}
});
}
//event
this._multipleSelectProviderEventHandler = lang.hitch(this, this._multipleSelectProviderEvent);
document.addEventListener('click', this._multipleSelectProviderEventHandler);
/*
this.own(on(document, 'click', lang.hitch(this, function(evt){
var target = event.target || event.srcElement;
if((this.editTable && target !== this.editTable.searchTarget) &&
(this.cbxPopup && this.cbxPopup.domNode && !html.isDescendant(target, this.cbxPopup.domNode))){
this._createTargetForPredefined();
evt.stopPropagation();
return;
}
if(this.editTable && target === this.editTable.searchTarget &&
(this.cbxPopup && this.cbxPopup.domNode)){ //click search
if(html.getStyle(this.cbxPopup.domNode, 'display') === 'block'){
html.setStyle(this.cbxPopup.domNode, 'display', 'none');
}else{
html.setStyle(this.cbxPopup.domNode, 'display', 'block');
}
return;
}
var isIn = this._isInSelectPopup(target);
if(isIn || this.runtime){ //always displaying on runtime page
evt.stopPropagation();
return;
}else{
html.setStyle(this.valuesPopupNode, 'display', 'none');
}
})));
*/
// this.own(on(this.valuesPopupNode, 'click', lang.hitch(this, function(evt){
// evt.stopPropagation();
// })));
//[{id,value,label}]
var store = new Memory({idProperty:'id', data: []});
this.listSelect.set('store', store);
},
_multipleSelectProviderEvent: function(event){
var target = event.target || event.srcElement;
var isSearchBtn = html.isDescendant(target, this.editTable.searchBtn);
if(this.editTable && this.cbxPopup && this.cbxPopup.domNode){
if(isSearchBtn){ //click search btn
if(html.getStyle(this.cbxPopup.domNode, 'display') === 'block'){
html.setStyle(this.cbxPopup.domNode, 'display', 'none');
}else{
html.setStyle(this.cbxPopup.domNode, 'display', 'block');
}
}else if(!html.isDescendant(target, this.cbxPopup.domNode)){ //other space
this._createTargetForPredefined();
}
event.stopPropagation();
return;
}
var isIn = this._isInSelectPopup(target);
if(isIn || this.runtime){ //always displaying on runtime page
event.stopPropagation();
return;
}else{
html.setStyle(this.valuesPopupNode, 'display', 'none');
}
},
_initAdvancedListValueSelect: function(){
this.pageControlForQuery.pageIndex = 1;
this.pageControlForQuery.isKeyQueryLoader = false;
this.listSelect = new AdvancedListValueSelect({
emptyStr: this.emptyStr,
runtime: this.runtime,
pageSize: this.pageSize,
isCacheFinish: this.pageControlForQuery._isUniqueValueCacheFinish,
// selectType: 'multiple',// when it's in header
selectType: 'unique',//when it's for single item
controlType: 'predefined',
dataList:[],
selectedDataList:[],
isNumberField: this.isNumberField
});
// this.listSelect.placeAt(this.listSelectStore);
// this.own(topic.subscribe("AdvancedListValueSelect/itemChecked", lang.hitch(this, this._createTarget)));
this.listSelect.on("advancedListValueSelect_itemChecked", lang.hitch(this, this._createTarget));
this.listSelect.on("advancedListValueSelect_itemUnChecked", lang.hitch(this, this._destoryTarget));
this.listSelect.on("advancedListValueSelect_addNextPage", lang.hitch(this, this._addNextPage));
this.listSelect.on("advancedListValueSelect_searchKey", lang.hitch(this, this._searchKey));
this.listSelect.on("advancedListValueSelect_searchKeyLocal", lang.hitch(this, this._searchKeyLocal));
this.listSelect.on("advancedListValueSelect_itemCheckedForPredefined",
lang.hitch(this, this._createTargetForPredefined));
},
_isInSelectPopup:function(target){
var classList = ['dijitCheckBoxInput', 'dojoxMultiSelectItemLabel', 'dojoxMultiSelectItemBox',
'dojoxMultiSelectItem', 'dojoxCheckedMultiSelectWrapper', 'dojoxCheckedMultiSelect',
'value-type-popup', 'popupOper', 'pageItem'];
var isIn = false;
for(var key = 0;key <= classList.length; key ++ ){
if(html.hasClass(target, classList[key])){
isIn = true;
break;
}
}
return isIn;
},
//for list select popup
// _createTarget: function(name){
// this.editTable._createTarget(name);
// },
//for editTable
_createTarget: function(){
this.editTable._createTarget('', '', '', '', true);
this._editTableItemChanged();
},
_createTargetForPredefined: function(value, name){
this.editTable._setNewLabel(value, name);
this.cbxPopup.close();
this._editTableItemChanged();
},
_destoryTarget:function(name){
this.editTable._destroyTarget(name);
this._editTableItemChanged();
},
_editTableItemChanged: function(){
if(!this.runtime){
var valueObj = this.getValueObject();
this._setApplyState(valueObj.value.length);
}
},
_setApplyState: function(state){
this.emit("predefinedValuePopup_setApplyBtnState", state);
},
_cbxWidth: 245,
_cbxHeight: 340,
isPopupLoading: false,
_showListSelectByTable: function(name){
if(this.isPopupLoading){
return;
}
this._initAdvancedListValueSelect();//init select & pagecontrol
this.valueList = [name];
this.getCheckedList(this.valueList);
var rPosition = html.position(this.editTable.searchBtn);
var popupPosition = {
left: rPosition.x - 226,
top: rPosition.y + 30
};
if(window.isRTL){
popupPosition.left = rPosition.x;
}
this.cbxPopup = new Popup({
width: this._cbxWidth,
height: this._cbxHeight,
content: this.listSelect.domNode,
enableMoveable: false,
hasTitle: false,
hasOverlay: false,
contentHasNoMargin: true,
moveToCenter: false,
customPosition: {left: popupPosition.left, top: popupPosition.top},
useFocusLogic: false,
buttons: []
});
//update popup UI for this dijit
this.cbxPopup.setDomNodeStyls({'border-radius': 0, 'border': '1px solid #999'});
this.cbxPopup.on("popupHasInitedSuccessfully", lang.hitch(this, function(){
var rPosition = html.position(this.editTable.searchBtn);
var popupPosition = {
left: rPosition.x - 226,
top: rPosition.y + 30
};
if(window.isRTL){
popupPosition.left = rPosition.x;
}
this.cbxPopup.setCustomPosition(popupPosition.left, popupPosition.top);
}));
if(this.listSelect.valueInput){
this.listSelect.valueInput.focus();
}
this._showLoadingIcon();
this.isPopupLoading = true;
this._valueLabels().then(lang.hitch(this, function(valueLabels) {
this.isPopupLoading = false;
this._hideLoadingIcon();
if(valueLabels === true){
}else{
var ifCheck = false;
if(this.valueList && this.valueList.length !== 0){
ifCheck = true;
}
this.listSelect.setCBXData(valueLabels,ifCheck);
}
}));
},
_valueLabels: function(){
var def = new Deferred();
this.listSelect.codedValues = false;
this.listSelect.disPlayLabel = 'label';
if(this.staticValues){
this._setValueForStaticValues(this.staticValues);
def.resolve(true);
return def;
} else if(this.codedValues){
if(this.filterCodedValue){
this.listSelect.codedValues = true;
}else{
this._setValueForStaticValues(this.codedValues);
def.resolve(true);
return def;
}
}
this.pageControlForQuery.queryByPage(true).then(lang.hitch(this, function(valueLabels){ //for multiple
def.resolve(valueLabels);
}), lang.hitch(this, function(err){
console.log(err);
this._hideLoadingIcon();
def.reject(err);
}));
return def;
},
_setValueForStaticValues: function(valueLabels){
this.listSelect.codedValues = true;
if(valueLabels){
this.pageControlForQuery._codedvalueCache = valueLabels;
valueLabels = valueLabels.length > 0 ? valueLabels : [];
// this.listSelect.disPlayLabel = 'label';
this.listSelect.setCBXData(valueLabels, true, true);
}
},
//types: dropdown, expanded
_changeDisplayType: function(evt){
var target = evt.target || evt.srcElement;
var option;
if(html.hasClass(target, 'option')){
option = target;
}else{
option = jimuUtils.getAncestorDom(target, function(dom){
return html.hasClass(dom, 'option');
}, 2);
}
if(!html.hasClass(option, 'checked')){
html.addClass(option, 'checked');
var otherOption = query('.' + this.selectUI + 'Option ', this.displayTypes)[0];
html.removeClass(otherOption, 'checked');
// this.selectUI = html.hasClass(option, 'dropdownOption') ? 'dropdown' : 'expanded';
this.selectUI = this.selectUI === 'expanded' ? 'dropdown' : 'expanded';
}
},
_setDisplayTypeStyle: function(){
var titleDom = query('.title', this.displayTypes)[0];
var labelDoms = query('.label', this.displayTypes);
var w = (html.getStyle(this.displayTypes, 'width') - html.getStyle(titleDom, 'width') - 2 * 40) / 2;
var leftLabelW = html.getStyle(labelDoms[0], 'width');
leftLabelW = leftLabelW < w ? leftLabelW : w;
var rightLabelW = html.getStyle(labelDoms[1], 'width');
rightLabelW = rightLabelW < w ? rightLabelW : w;
html.setStyle(labelDoms[0], 'width', leftLabelW + 'px');
html.setStyle(labelDoms[1], 'width', rightLabelW + 'px');
},
_addNextPage: function(){
if(!this.listSelect){
return;
}
this._showLoadingIcon();
var def = this.pageControlForQuery.queryByPage(this.listSelect.ifFristPage);
def.then(lang.hitch(this, function(valueLabels){
this.listSelect.isCacheFinish = this.pageControlForQuery._isUniqueValueCacheFinish;
this.listSelect.setCBXData(valueLabels, true);
this._hideLoadingIcon();
}), lang.hitch(this, function(err){
console.log(err);
this._hideLoadingIcon();
}));
},
//this.allFeatures = [];
_searchKey: function(name){
if(!this.listSelect){
return;
}
this._showLoadingIcon();
this.pageControlForQuery._searchKey(name).then(lang.hitch(this, function(result) {
this.listSelect.setCBXContentBySearch(result);
this._hideLoadingIcon();
}), lang.hitch(this, function(err){
console.log(err);
this._hideLoadingIcon();
}));
},
_searchKeyLocal: function(name){
if(!this.listSelect){
return;
}
this._showLoadingIcon();
var result = this.pageControlForQuery._searchKeyLocal(name);
this.listSelect.setCBXContentBySearch(result);
this._hideLoadingIcon();
},
_handlerPageValues: function(){
},
getCheckedList: function(valueList){
this.listSelect.checkedList = [];
if(this.isNumberField){
array.forEach(valueList, lang.hitch(this, function(item) {
this.listSelect.checkedList.push(parseFloat(item));
}));
}else{
this.listSelect.checkedList = valueList;
}
},
_showPopup:function(){
// this._showLoadingIcon();
//refresh values
var valueList = this.getValueObject().valueList;
this.valueList = valueList === null ? undefined : valueList;
// this.listSelect.checkedList = this.valueList;
// if(this.listSelect.vallueInput === undefined){
// this.cbxPopup = null;
// }
this.getCheckedList(this.valueList);
if(this.cbxPopup){
// this.getCheckedList(this.valueList);
this.listSelect.checkCBXItems(false);
// this.listSelect.setCBXData(valueLabels,true);
this.cbxPopup.show();
// this._hideLoadingIcon();
return;
}
var popupName = this.layerDefinition.name + '(' + this.fieldName + ')';
this.cbxPopup = new Popup({
width: 355,
height: 596,
content: this.listSelect.domNode, //need a dom, not html string
titleLabel: popupName,
isResize: false,
useFocusLogic: false,
// onClose: function(){return false},
onClose: lang.hitch(this, function () {
//save dom
// this.cbxPopup.content = null;
// html.place(this.listSelect.domNode, this.listSelectStore);
//continue
this.cbxPopup.hide();
return false;
}),
buttons: []
});
this._showLoadingIcon();
this.pageControlForQuery.queryByPage().then(lang.hitch(this, function(valueLabels) {
this._hideLoadingIcon();
var ifCheck = false;
if(this.valueList && this.valueList.length !== 0){
ifCheck = true;
}
// var cbxData = this.listSelect.setCBXData(valueLabels,ifCheck);
this.listSelect.setCBXData(valueLabels,ifCheck);
}));
},
getDijits: function(){
return [this.mutiValuesSelect];
},
setValueObject: function(valueObj){//, isFromConfig
valueObj.value = valueObj.value? valueObj.value: [];
var selectUI = valueObj.selectUI ? valueObj.selectUI : this.selectUI;
var typeOption = query('.' + selectUI + 'Option ', this.displayTypes)[0];
html.addClass(typeOption, 'checked');
var newValueLabels = null;//get values' format datas on the first colum in table
if(this.isNumberField){
var valsArray = [];
for(var key = 0; key < valueObj.value.length; key ++){
valsArray.push(valueObj.value[key].value);
}
newValueLabels = this._getValLabelsArrayForNumber(false, valsArray);
}
this.editTable.emptyLabel = valueObj.emptyLabel;
this.editTable.enableEmpty = valueObj.enableEmpty;
this.editTable.setListValues(valueObj.value, newValueLabels);
},
_getValLabelsArrayForNumber: function(isTrigger, valsArray){
var valueLabels = jimuUtils._getValues(this.layerDefinition, this.fieldPopupInfo, this.fieldName, valsArray);
if(isTrigger){
this.editTable.currentValLabel = valueLabels[0].label;
}
return valueLabels;
},
tryGetValueObject: function(){
if(this.isValidValue()){
return this.getValueObject();
}else if(this.isEmptyValue()){
return {
"isValid": true,
"selectUI": this.selectUI,
"type": this.partObj.valueObj.type,
"value": [],
"valueList": []
};
}
return null;
},
getValueObject: function(){
if(this.isValidValue()){
var valsObj = this.editTable.getListValues();
var result = {
"isValid": true,
"selectUI": this.selectUI,
"type": this.partObj.valueObj.type,
"value": valsObj.list, //valueObj list
"valueList": valsObj.valueList //value list
};
if(this.controlType === 'unique'){
result.emptyLabel = valsObj.emptyLabel;
result.enableEmpty = valsObj.enableEmpty;
}
return result;
}
return null;
},
setRequired: function(required){
this.mutiValuesSelect.set("required", required);
},
queryByPage: function(){
var def = this.pageControlForQuery.queryByPage(this.listSelect.ifFristPage);
def.then(lang.hitch(this, function(features){
def.resolve(features);
}), lang.hitch(this, function(err){
console.log(err);
def.reject(err);
}));
},
_showLoadingIcon: function(){
if(this.listSelect && this.listSelect.listContainer){
html.addClass(this.listSelect.listContainer, 'jimu-circle-loading');
}
},
_hideLoadingIcon: function(){
if(this.listSelect && this.listSelect.listContainer){
html.removeClass(this.listSelect.listContainer, 'jimu-circle-loading');
}
},
destroy: function() {
if(this._multipleSelectProviderEventHandler){
document.removeEventListener('click', this._multipleSelectProviderEventHandler);
}
this.inherited(arguments);
},
destroyProvider:function(){
if(this.editTable){
this.editTable.destroy();
}
// this.editTable = null;
if(this.listSelect){
this.listSelect.destroy();
}
this.listSelect = null;
this.destroy();
html.destroy(this.domNode);
// this.inherited(arguments);
}
});
}); |
var $askFor = require('ask-for');
module.exports = function(grunt){
grunt.registerMultiTask(
'confirm',
'ask for confirm',
function(){
var done = this.async();
var conf = this.options();
var data = this.data;
var ask = '[y/n]';
var doAsk = function(){
grunt.log.writeln();
grunt.log.writeln(data.msg);
$askFor([ask], function(spec) {
var ans = spec[ask].toLowerCase();
if(ans === 'y'){
grunt.log.ok('tasks continue ...');
done();
}else if(ans === 'n'){
grunt.task.clearQueue();
grunt.log.ok('tasks cleared!');
done();
}else{
doAsk();
}
});
};
doAsk();
}
);
};
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* This class returns information about the partition that the user-induced
* operation acted upon.
*
*/
class SelectedPartition {
/**
* Create a SelectedPartition.
* @member {string} [serviceName]
* @member {uuid} [partitionId]
*/
constructor() {
}
/**
* Defines the metadata of SelectedPartition
*
* @returns {object} metadata of SelectedPartition
*
*/
mapper() {
return {
required: false,
serializedName: 'SelectedPartition',
type: {
name: 'Composite',
className: 'SelectedPartition',
modelProperties: {
serviceName: {
required: false,
serializedName: 'ServiceName',
type: {
name: 'String'
}
},
partitionId: {
required: false,
serializedName: 'PartitionId',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = SelectedPartition;
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2015 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* This is the core internal game clock.
*
* It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens,
* and also handles the standard Timer pool.
*
* To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}.
*
* There are different *types* of time in Phaser:
*
* - ***Game time*** always runs at the speed of time in real life.
*
* Unlike wall-clock time, *game time stops when Phaser is paused*.
*
* Game time is used for {@link Phaser.Timer timer events}.
*
* - ***Physics time*** represents the amount of time given to physics calculations.
*
* *When {@link #slowMotion} is in effect physics time runs slower than game time.*
* Like game time, physics time stops when Phaser is paused.
*
* Physics time is used for physics calculations and {@link Phaser.Tween tweens}.
*
* - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time.
*
* This time is independent of Phaser and always progresses, regardless of if Phaser is paused.
*
* @class Phaser.Time
* @constructor
* @param {Phaser.Game} game A reference to the currently running game.
*/
Phaser.Time = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
* @protected
*/
this.game = game;
/**
* The `Date.now()` value when the time was last updated.
* @property {integer} time
* @protected
*/
this.time = 0;
/**
* The `now` when the previous update occurred.
* @property {number} prevTime
* @protected
*/
this.prevTime = 0;
/**
* An increasing value representing cumulative milliseconds since an undisclosed epoch.
*
* While this value is in milliseconds and can be used to compute time deltas,
* it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference.
*
* The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now;
* the value can only be relied upon within a particular game instance.
*
* @property {number} now
* @protected
*/
this.now = 0;
/**
* Elapsed time since the last time update, in milliseconds, based on `now`.
*
* This value _may_ include time that the game is paused/inactive.
*
* _Note:_ This is updated only once per game loop - even if multiple logic update steps are done.
* Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
*
* @property {number} elapsed
* @see Phaser.Time.time
* @protected
*/
this.elapsed = 0;
/**
* The time in ms since the last time update, in milliseconds, based on `time`.
*
* This value is corrected for game pauses and will be "about zero" after a game is resumed.
*
* _Note:_ This is updated once per game loop - even if multiple logic update steps are done.
* Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
*
* @property {integer} elapsedMS
* @protected
*/
this.elapsedMS = 0;
/**
* The physics update delta, in fractional seconds.
*
* This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`)
* to ensure consistent game timing. Game/logic timing can drift from real-world time if the system
* is unable to consistently maintain the desired FPS.
*
* With fixed-step updates this is normally equivalent to `1.0 / desiredFps`.
*
* @property {number} physicsElapsed
*/
this.physicsElapsed = 1 / 60;
/**
* The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`.
*
* @property {number} physicsElapsedMS
*/
this.physicsElapsedMS = (1 / 60) * 1000;
/**
* The desiredFps multiplier as used by Game.update.
* @property {integer} desiredFpsMult
* @protected
*/
this.desiredFpsMult = 1.0 / 60;
/**
* The desired frame rate of the game.
*
* This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates.
*
* @property {number} _desiredFps
* @private
* @default
*/
this._desiredFps = 60;
/**
* The suggested frame rate for your game, based on an averaged real frame rate.
* This value is only populated if `Time.advancedTiming` is enabled.
*
* _Note:_ This is not available until after a few frames have passed; until then
* it's set to the same value as desiredFps.
*
* @property {number} suggestedFps
* @default
*/
this.suggestedFps = this.desiredFps;
/**
* Scaling factor to make the game move smoothly in slow motion
* - 1.0 = normal speed
* - 2.0 = half speed
* @property {number} slowMotion
* @default
*/
this.slowMotion = 1.0;
/**
* If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated.
* @property {boolean} advancedTiming
* @default
*/
this.advancedTiming = false;
/**
* Advanced timing result: The number of render frames record in the last second.
*
* Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
* @property {integer} frames
* @readonly
*/
this.frames = 0;
/**
* Advanced timing result: Frames per second.
*
* Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
* @property {number} fps
* @readonly
*/
this.fps = 0;
/**
* Advanced timing result: The lowest rate the fps has dropped to.
*
* Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
* This value can be manually reset.
* @property {number} fpsMin
*/
this.fpsMin = 1000;
/**
* Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps).
*
* Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
* This value can be manually reset.
* @property {number} fpsMax
*/
this.fpsMax = 0;
/**
* Advanced timing result: The minimum amount of time the game has taken between consecutive frames.
*
* Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
* This value can be manually reset.
* @property {number} msMin
* @default
*/
this.msMin = 1000;
/**
* Advanced timing result: The maximum amount of time the game has taken between consecutive frames.
*
* Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
* This value can be manually reset.
* @property {number} msMax
*/
this.msMax = 0;
/**
* Records how long the game was last paused, in milliseconds.
* (This is not updated until the game is resumed.)
* @property {number} pauseDuration
*/
this.pauseDuration = 0;
/**
* @property {number} timeToCall - The value that setTimeout needs to work out when to next update
* @protected
*/
this.timeToCall = 0;
/**
* @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop
* @protected
*/
this.timeExpected = 0;
/**
* A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to.
* @property {Phaser.Timer} events
*/
this.events = new Phaser.Timer(this.game, false);
/**
* @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated
* @private
*/
this._frameCount = 0;
/**
* @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated
* @private
*/
this._elapsedAccumulator = 0;
/**
* @property {number} _started - The time at which the Game instance started.
* @private
*/
this._started = 0;
/**
* @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over.
* @private
*/
this._timeLastSecond = 0;
/**
* @property {number} _pauseStarted - The time the game started being paused.
* @private
*/
this._pauseStarted = 0;
/**
* @property {boolean} _justResumed - Internal value used to recover from the game pause state.
* @private
*/
this._justResumed = false;
/**
* @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects.
* @private
*/
this._timers = [];
};
Phaser.Time.prototype = {
/**
* Called automatically by Phaser.Game after boot. Should not be called directly.
*
* @method Phaser.Time#boot
* @protected
*/
boot: function () {
this._started = Date.now();
this.time = Date.now();
this.events.start();
this.timeExpected = this.time;
},
/**
* Adds an existing Phaser.Timer object to the Timer pool.
*
* @method Phaser.Time#add
* @param {Phaser.Timer} timer - An existing Phaser.Timer object.
* @return {Phaser.Timer} The given Phaser.Timer object.
*/
add: function (timer) {
this._timers.push(timer);
return timer;
},
/**
* Creates a new stand-alone Phaser.Timer object.
*
* @method Phaser.Time#create
* @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
* @return {Phaser.Timer} The Timer object that was created.
*/
create: function (autoDestroy) {
if (autoDestroy === undefined) { autoDestroy = true; }
var timer = new Phaser.Timer(this.game, autoDestroy);
this._timers.push(timer);
return timer;
},
/**
* Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer.
*
* @method Phaser.Time#removeAll
*/
removeAll: function () {
for (var i = 0; i < this._timers.length; i++)
{
this._timers[i].destroy();
}
this._timers = [];
this.events.removeAll();
},
/**
* Refreshes the Time.time and Time.elapsedMS properties from the system clock.
*
* @method Phaser.Time#refresh
*/
refresh: function () {
// Set to the old Date.now value
var previousDateNow = this.time;
// this.time always holds a Date.now value
this.time = Date.now();
// Adjust accordingly.
this.elapsedMS = this.time - previousDateNow;
},
/**
* Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game.
*
* @method Phaser.Time#update
* @protected
* @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}.
*/
update: function (time) {
// Set to the old Date.now value
var previousDateNow = this.time;
// this.time always holds a Date.now value
this.time = Date.now();
// Adjust accordingly.
this.elapsedMS = this.time - previousDateNow;
// 'now' is currently still holding the time of the last call, move it into prevTime
this.prevTime = this.now;
// update 'now' to hold the current time
// this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now)
this.now = time;
// elapsed time between previous call and now - this could be a high resolution value
this.elapsed = this.now - this.prevTime;
if (this.game.raf._isSetTimeOut)
{
// console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time);
// time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game
this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time)));
// time when the next call is expected if using timers
this.timeExpected = time + this.timeToCall;
// console.log('Time expect', this.timeExpected);
}
if (this.advancedTiming)
{
this.updateAdvancedTiming();
}
// Paused but still running?
if (!this.game.paused)
{
// Our internal Phaser.Timer
this.events.update(this.time);
if (this._timers.length)
{
this.updateTimers();
}
}
},
/**
* Handles the updating of the Phaser.Timers (if any)
* Called automatically by Time.update.
*
* @method Phaser.Time#updateTimers
* @private
*/
updateTimers: function () {
// Any game level timers
var i = 0;
var len = this._timers.length;
while (i < len)
{
if (this._timers[i].update(this.time))
{
i++;
}
else
{
// Timer requests to be removed
this._timers.splice(i, 1);
len--;
}
}
},
/**
* Handles the updating of the advanced timing values (if enabled)
* Called automatically by Time.update.
*
* @method Phaser.Time#updateAdvancedTiming
* @private
*/
updateAdvancedTiming: function () {
// count the number of time.update calls
this._frameCount++;
this._elapsedAccumulator += this.elapsed;
// occasionally recalculate the suggestedFps based on the accumulated elapsed time
if (this._frameCount >= this._desiredFps * 2)
{
// this formula calculates suggestedFps in multiples of 5 fps
this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5;
this._frameCount = 0;
this._elapsedAccumulator = 0;
}
this.msMin = Math.min(this.msMin, this.elapsed);
this.msMax = Math.max(this.msMax, this.elapsed);
this.frames++;
if (this.now > this._timeLastSecond + 1000)
{
this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
this.fpsMin = Math.min(this.fpsMin, this.fps);
this.fpsMax = Math.max(this.fpsMax, this.fps);
this._timeLastSecond = this.now;
this.frames = 0;
}
},
/**
* Called when the game enters a paused state.
*
* @method Phaser.Time#gamePaused
* @private
*/
gamePaused: function () {
this._pauseStarted = Date.now();
this.events.pause();
var i = this._timers.length;
while (i--)
{
this._timers[i]._pause();
}
},
/**
* Called when the game resumes from a paused state.
*
* @method Phaser.Time#gameResumed
* @private
*/
gameResumed: function () {
// Set the parameter which stores Date.now() to make sure it's correct on resume
this.time = Date.now();
this.pauseDuration = this.time - this._pauseStarted;
this.events.resume();
var i = this._timers.length;
while (i--)
{
this._timers[i]._resume();
}
},
/**
* The number of seconds that have elapsed since the game was started.
*
* @method Phaser.Time#totalElapsedSeconds
* @return {number} The number of seconds that have elapsed since the game was started.
*/
totalElapsedSeconds: function() {
return (this.time - this._started) * 0.001;
},
/**
* How long has passed since the given time.
*
* @method Phaser.Time#elapsedSince
* @param {number} since - The time you want to measure against.
* @return {number} The difference between the given time and now.
*/
elapsedSince: function (since) {
return this.time - since;
},
/**
* How long has passed since the given time (in seconds).
*
* @method Phaser.Time#elapsedSecondsSince
* @param {number} since - The time you want to measure (in seconds).
* @return {number} Duration between given time and now (in seconds).
*/
elapsedSecondsSince: function (since) {
return (this.time - since) * 0.001;
},
/**
* Resets the private _started value to now and removes all currently running Timers.
*
* @method Phaser.Time#reset
*/
reset: function () {
this._started = this.time;
this.removeAll();
}
};
/**
* The desired frame rate of the game.
*
* This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates.
*
* @name Phaser.Time#desiredFps
* @property {integer} desiredFps - The desired frame rate of the game. Defaults to 60.
*/
Object.defineProperty(Phaser.Time.prototype, "desiredFps", {
get: function () {
return this._desiredFps;
},
set: function (value) {
this._desiredFps = value;
// Set the physics elapsed time... this will always be 1 / this.desiredFps
// because we're using fixed time steps in game.update
this.physicsElapsed = 1 / value;
this.physicsElapsedMS = this.physicsElapsed * 1000;
this.desiredFpsMult = 1.0 / value;
}
});
Phaser.Time.prototype.constructor = Phaser.Time;
|
function Deck(){
this.cards = []
this.build()
this.shuffle()
}
Deck.prototype={
shuffle: function(){
var arr = this.cards
for (var i = 0; i < arr.length; i++) {
var rand = Math.floor(Math.random()*52)
var temp = arr[i]
arr[i] = arr[rand]
arr[rand] = temp
}
},
//places card on top of cards
addCard: function(card){
this.cards.push(card)
return this
},
//fills cards deck with all cards in order
build: function(){
this.cards = []
addSuite = (suite) => {
hex = "1F0" + suite + 0
dec = parseInt(hex,16)
for (let i = 1; i <= 13; i++){
var card = String.fromCodePoint(dec + i)
this.cards.push(card)
}
}
["A","B","C","D"].forEach(addSuite)
},
deal: function(){
return this.cards.pop()
}
}
// Player Constructor
function Player(name="johndoe"){
this.name = name
this.hand = []
}
Player.prototype = {
drawCard: function(deckObj,n=1){
for (let i = 0; i < n; i++) {
this.hand.push(deckObj.deal())
}
},
discardCard: function(cardIndex=0){
this.hand = this.hand.slice(0,cardIndex).concat(this.hand.slice(cardIndex+1))
}
}
// deck = new Deck()
// player = new Player("fred")
//
// console.log(deck.cards.length);
// exports.Player = Player
// exports.Deck = Deck
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'public/js/app.min.js': ['public/js/app.js']
}
}
},
jshint: {
files: ['Gruntfile.js', 'public/js/app.js'],
options: {
globals: {
jQuery: true,
console: true,
module: true,
document: true,
},
multistr: true
}
},
cssmin: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'public/css/app.min.css': ['public/css/app.css']
}
}
},
csslint: {
src: ['public/css/app.css'],
options: {
"important": false,
"box-model": false,
"known-properties": false,
"overqualified-elements":false
}
},
watch: {
files: ['public/js/app.js', 'public/css/app.css'],
tasks: ['uglify', 'jshint', 'cssmin', 'csslint']
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.registerTask('default', ['uglify', 'jshint', 'cssmin', 'csslint']);
};
|
module.exports = function (wallaby) {
var config = require('../../etc/wallaby/wallaby.base')(wallaby)
return Object.assign(config,{
// Extended options go here
});
};
|
MSG.title = "Webduino Blockly 課程 3-5:超音波傳感器控制 Youtube 音量";
MSG.subTitle = "課程 3-5:超音波傳感器控制 youtube 的音量";
MSG.demoDescription = "使用超音波傳感器,控制 youtube 的音量變化,越靠近越小聲,越遠越大聲。";
|
/*! jQuery UI - v1.10.4 - 2014-03-23
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function(t){t.effects.effect.pulsate=function(e,i){var s,n=t(this),a=t.effects.setMode(n,e.mode||"show"),o="show"===a,r="hide"===a,l=o||"hide"===a,h=2*(e.times||5)+(l?1:0),c=e.duration/h,u=0,d=n.queue(),p=d.length;for((o||!n.is(":visible"))&&(n.css("opacity",0).show(),u=1),s=1;h>s;s++)n.animate({opacity:u},c,e.easing),u=1-u;n.animate({opacity:u},c,e.easing),n.queue(function(){r&&n.hide(),i()}),p>1&&d.splice.apply(d,[1,0].concat(d.splice(p,h+1))),n.dequeue()}})(jQuery); |
'use strict';
var split = String.prototype.split;
function compareNatural(value, other) {
var index = -1,
valParts = split.call(value, '.'),
valLength = valParts.length,
othParts = split.call(other, '.'),
othLength = othParts.length,
length = Math.min(valLength, othLength);
while (++index < length) {
var valPart = valParts[index],
othPart = othParts[index];
if (valPart > othPart && othPart != 'prototype') {
return 1;
} else if (valPart < othPart && valPart != 'prototype') {
return -1;
}
}
return valLength > othLength ? 1 : (valLength < othLength ? -1 : 0);
}
exports.compareNatural = compareNatural;
|
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
} |
/*
* routes/api/index.js
*/
var BASE_PATH = '../../lib/';
var email = require(BASE_PATH + 'email')
, InviteCode = require(BASE_PATH + 'models').InviteCode
module.exports = {
config: require('./config'),
require_param: require_param,
invite_new: invite_new
}
/*
* Require a request parameter is present or return a 400 response.
*/
function require_param(key, req, res) {
var val = req.param(key);
if (val === undefined) {
res.statusCode = 400;
var r = {
status: "error",
errors: ["you must supply parameter " + key]
};
return res.end(JSON.stringify(r), null, '\t');
}
return val;
}
/*
* POST /api/invite/new
*
* Create & email a new Strider invite. Only core@beyondfog.com may use this.
*
* <invite_code> - Invite token string to set.
* <email> - Email to send to.
*
*/
function invite_new(req, res) {
var invite_code, email_addr;
invite_code = require_param("invite_code", req, res);
email_addr = require_param("email", req, res);
if (invite_code === undefined ||
email_addr === undefined) {
return;
}
var invite = new InviteCode();
invite.code = invite_code;
invite.created_timestamp = new Date();
invite.emailed_to = email_addr;
invite.save(function(err, invite) {
email.send_invite(invite.code, email_addr)
res.redirect('/admin/invites')
});
}
|
/*jslint plusplus: true */
(function () {
"use strict";
var sID,
iIterator,
oRedmond = [
{
title: {
"#text": "Engineering Development Manager"
}
}, {
title: {
"#text": "Programmer Analyst"
}
}, {
title: {
"#text": "Localization Program Manager"
}
}, {
title: {
"#text": "Program Manager"
}
}, {
title: {
"#text": "Content Editor"
}
}, {
title: {
"#text": "Web Application Developer"
}
}, {
title: {
"#text": "Software Development Engineer in Test"
}
}, {
title: {
"#text": "Software Test Engineer"
}
}, {
title: {
"#text": "Systems Engineer"
}
}
],
oNewsData = null,
oJobPostSection,
sTemplate = '<div class="BorderBottom"><p class="SemiBold pTagLine Pointer" onclick="showJobPage(\'@location\',@id,\'@title\');">@title</p><p class="FloatRight MarginUp BackLink" onclick="showJobPage(\'@location\',@id,\'@title\');">View Description</p></div>',
sJobServiceIssue = '<p class="DataSubContent Color595959">Issue in connecting to job-post service.<br />Try loading the section again.</p>',
sNoJobMessage = '<p class="DataSubContent Color595959">No job openings available at this location.<br />Please come back and check again soon.</p>';
function renderTitle(oData) {
var oCurrentPost;
oJobPostSection.html("").removeClass("Loading").removeClass("LoadingHeight");
for (iIterator = 0; iIterator < oData.length; iIterator++) {
oCurrentPost = oData.item(iIterator);
oJobPostSection.append(sTemplate.replace(/@title/g, oCurrentPost.getElementsByTagName("title")[0].childNodes[0].nodeValue).replace(/@location/g, sID).replace(/@id/g, iIterator));
}
}
function renderTitleRedmond(oData) {
var oCurrentPost;
oJobPostSection.html("").removeClass("Loading").removeClass("LoadingHeight");
for (iIterator = 0; iIterator < oData.length; iIterator++) {
oCurrentPost = oData[iIterator];
oJobPostSection.append(sTemplate.replace(/@title/g, oCurrentPost.title['#text']).replace(/@location/g, sID).replace(/@id/g, iIterator));
}
}
function loadNews(sNewsData) {
var oTempData = [], parser;
try {
parser = new DOMParser();
oNewsData = parser.parseFromString(sNewsData, "text/xml");
if (sID) {
if (oNewsData.getElementsByTagName('feed') && !oNewsData.getElementsByTagName('entry').length) {
oTempData[0] = oNewsData.getElementsByTagName('entry');
//oNewsData.feed.entry = oTempData;
}
renderTitle(oNewsData.getElementsByTagName('entry'));
}
} catch (exception) {
oJobPostSection.html(sNoJobMessage).removeClass("Loading").removeClass("LoadingHeight");
}
}
function loadPanel() {
if (!sID || sID === "Redmond") {
sID = "Redmond";
setTimeout(function () {
renderTitleRedmond(oRedmond);
}, 800);
} else {
var feedUrl = "http://www.blogger.com/feeds/2523158019509365490/posts/default/-/Openings - Hyderabad";
if ("mumbai" === sID.toLowerCase()) {
feedUrl = "http://www.blogger.com/feeds/2523158019509365490/posts/default/-/Openings - Mumbai";
}
$.ajax({
url: feedUrl,
type: 'GET',
dataType: "jsonp",
success: function (msg) {
if (msg) {
loadNews(msg);
} else {
oJobPostSection.html(sNoJobMessage).removeClass("Loading").removeClass("LoadingHeight");
}
},
error: function () {
oJobPostSection.html(sJobServiceIssue).removeClass("Loading").removeClass("LoadingHeight");
}
});
}
$("#CareerLinks > a").removeClass("tabActive");
$("#CareerLinks > a[data-link=" + sID + "]").addClass("tabActive");
}
$(document).ready(function () {
var sCurrentDate = new Date().format();
$("#RedMail").attr("href", "mailto:RedmondJobs@MAQSoftware.com?Subject=Application%20for%20job%20posted%20on%20MAQSoftware.com%20(" + sCurrentDate + ")").html("RedmondJobs@MAQSoftware.com");
$("#MumMail").attr("href", "mailto:MumbaiJobs@MAQSoftware.com?Subject=Application%20for%20job%20posted%20on%20MAQSoftware.com%20(" + sCurrentDate + ")").html("MumbaiJobs@MAQSoftware.com");
$("#HydMail").attr("href", "mailto:HydJobs@MAQSoftware.com?Subject=Application%20for%20job%20posted%20on%20MAQSoftware.com%20(" + sCurrentDate + ")").html("HydJobs@MAQSoftware.com");
oJobPostSection = $("#CareerLinkHolder");
sID = getParameterByName("q");
loadPanel();
$("#CareerLinks > a").click(function () {
var sTabClicked = $(this).attr("data-link");
oJobPostSection.html("").addClass("Loading").addClass("LoadingHeight");
sID = sTabClicked;
loadPanel();
});
});
}());
function showJobPage(sJobLocation, iJobID, sjobPost) {
"use strict";
sJobLocation = sJobLocation.toLowerCase();
switch (sJobLocation) {
case "redmond":
window.location.href = "#CareerinUS?q=" + iJobID + "&pn=" + sjobPost;
break;
case "hyderabad":
window.location.href = "#CareersinHyd?q=" + iJobID + "&pn=" + sjobPost;
break;
case "mumbai":
window.location.href = "#CareersinMumbai?q=" + iJobID + "&pn=" + sjobPost;
break;
}
} |
var absURLRegEx = /^[^\/]+:\/\//;
function readMemberExpression(p, value) {
var pParts = p.split('.');
while (pParts.length)
value = value[pParts.shift()];
return value;
}
var baseURLCache = {};
function getBaseURLObj() {
if (baseURLCache[this.baseURL])
return baseURLCache[this.baseURL];
// normalize baseURL if not already
if (this.baseURL[this.baseURL.length - 1] != '/')
this.baseURL += '/';
var baseURL = new URL(this.baseURL, baseURI);
this.baseURL = baseURL.href;
return (baseURLCache[this.baseURL] = baseURL);
}
var baseURIObj = new URL(baseURI);
(function() {
hookConstructor(function(constructor) {
return function() {
constructor.call(this);
// support baseURL
this.baseURL = baseURI.substr(0, baseURI.lastIndexOf('/') + 1);
// support the empty module, as a concept
this.set('@empty', this.newModule({}));
};
});
/*
Normalization
If a name is relative, we apply URL normalization to the page
If a name is an absolute URL, we leave it as-is
Plain names (neither of the above) run through the map and package
normalization phases (applying before and after this one).
The paths normalization phase applies last (paths extension), which
defines the `normalizeSync` function and normalizes everything into
a URL.
The final normalization
*/
hook('normalize', function() {
return function(name, parentName) {
// relative URL-normalization
if (name[0] == '.' || name[0] == '/')
return new URL(name, parentName || baseURIObj).href;
return name;
};
});
/*
__useDefault
When a module object looks like:
newModule(
__useDefault: true,
default: 'some-module'
})
Then importing that module provides the 'some-module'
result directly instead of the full module.
Useful for eg module.exports = function() {}
*/
hook('import', function(systemImport) {
return function(name, parentName, parentAddress) {
return systemImport.call(this, name, parentName, parentAddress).then(function(module) {
return module.__useDefault ? module['default'] : module;
});
};
});
/*
Extend config merging one deep only
loader.config({
some: 'random',
config: 'here',
deep: {
config: { too: 'too' }
}
});
<=>
loader.some = 'random';
loader.config = 'here'
loader.deep = loader.deep || {};
loader.deep.config = { too: 'too' };
Normalizes meta and package configs allowing for:
System.config({
meta: {
'./index.js': {}
}
});
To become
System.meta['https://thissite.com/index.js'] = {};
For easy normalization canonicalization with latest URL support.
*/
var packageProperties = ['main', 'format', 'defaultExtension', 'meta', 'map', 'basePath'];
SystemJSLoader.prototype.config = function(cfg) {
// always configure baseURL first
if (cfg.baseURL) {
var hasConfig = false;
function checkHasConfig(obj) {
for (var p in obj)
return true;
}
if (checkHasConfig(this.packages) || checkHasConfig(this.meta) || checkHasConfig(this.depCache) || checkHasConfig(this.bundles))
throw new TypeError('baseURL should only be configured once and must be configured first.');
this.baseURL = cfg.baseURL;
// sanitize baseURL
getBaseURLObj.call(this);
}
if (cfg.defaultJSExtensions)
this.defaultJSExtensions = cfg.defaultJSExtensions;
if (cfg.pluginFirst)
this.pluginFirst = cfg.pluginFirst;
if (cfg.paths) {
for (var p in cfg.paths)
this.paths[p] = cfg.paths[p];
}
if (cfg.map) {
for (var p in cfg.map) {
var v = cfg.map[p];
// object map backwards-compat into packages configuration
if (typeof v !== 'string') {
var normalized = this.normalizeSync(p);
// if doing default js extensions, undo to get package name
if (this.defaultJSExtensions && p.substr(p.length - 3, 3) != '.js')
normalized = normalized.substr(0, normalized.length - 3);
// if a package main, revert it
var pkgMatch = '';
for (var pkg in this.packages) {
if (normalized.substr(0, pkg.length) == pkg
&& (!normalized[pkg.length] || normalized[pkg.length] == '/')
&& pkgMatch.split('/').length < pkg.split('/').length)
pkgMatch = pkg;
}
if (pkgMatch && this.packages[pkgMatch].main)
normalized = normalized.substr(0, normalized.length - this.packages[pkgMatch].main.length - 1);
var pkg = this.packages[normalized] = this.packages[normalized] || {};
pkg.map = v;
}
else {
this.map[p] = v;
}
}
}
if (cfg.packagePaths) {
for (var i = 0; i < cfg.packagePaths.length; i++) {
var path = cfg.packagePaths[i];
var normalized = this.normalizeSync(path);
if (this.defaultJSExtensions && path.substr(path.length - 3, 3) != '.js')
normalized = normalized.substr(0, normalized.length - 3);
cfg.packagePaths[i] = normalized;
}
}
if (cfg.packages) {
for (var p in cfg.packages) {
if (p.match(/^([^\/]+:)?\/\/$/))
throw new TypeError('"' + p + '" is not a valid package name.');
// request with trailing "/" to get package name exactly
var prop = this.normalizeSync(p + (p[p.length - 1] != '/' ? '/' : ''));
prop = prop.substr(0, prop.length - 1);
// if doing default js extensions, undo to get package name
if (this.defaultJSExtensions && p.substr(p.length - 3, 3) != '.js')
prop = prop.substr(0, prop.length - 3);
this.packages[prop]= this.packages[prop] || {};
for (var q in cfg.packages[p])
if (indexOf.call(packageProperties, q) == -1 && typeof console != 'undefined' && console.warn)
console.warn('"' + q + '" is not a valid package configuration option in package ' + p);
extendMeta(this.packages[prop], cfg.packages[p]);
}
}
if (cfg.bundles) {
for (var p in cfg.bundles) {
var bundle = [];
for (var i = 0; i < cfg.bundles[p].length; i++)
bundle.push(this.normalizeSync(cfg.bundles[p][i]));
this.bundles[p] = bundle;
}
}
for (var c in cfg) {
var v = cfg[c];
var normalizeProp = false, normalizeValArray = false;
if (c == 'baseURL' || c == 'map' || c == 'packages' || c == 'bundles' || c == 'paths')
continue;
if (typeof v != 'object' || v instanceof Array) {
this[c] = v;
}
else {
this[c] = this[c] || {};
if (c == 'meta' || c == 'depCache')
normalizeProp = true;
for (var p in v) {
if (c == 'meta' && p[0] == '*')
this[c][p] = v[p];
else if (normalizeProp)
this[c][this.normalizeSync(p)] = v[p];
else
this[c][p] = v[p];
}
}
}
};
})(); |
/* global moment */
var parseDateFormats = ['DD MMM YY @ HH:mm', 'DD MMM YY HH:mm',
'DD MMM YYYY @ HH:mm', 'DD MMM YYYY HH:mm',
'DD/MM/YY @ HH:mm', 'DD/MM/YY HH:mm',
'DD/MM/YYYY @ HH:mm', 'DD/MM/YYYY HH:mm',
'DD-MM-YY @ HH:mm', 'DD-MM-YY HH:mm',
'DD-MM-YYYY @ HH:mm', 'DD-MM-YYYY HH:mm',
'YYYY-MM-DD @ HH:mm', 'YYYY-MM-DD HH:mm'],
displayDateFormat = 'DD MMM YY @ HH:mm';
/**
* Add missing timestamps
*/
var verifyTimeStamp = function (dateString) {
if (dateString && !dateString.slice(-5).match(/\d+:\d\d/)) {
dateString += ' 12:00';
}
return dateString;
};
//Parses a string to a Moment
var parseDateString = function (value) {
return value ? moment(verifyTimeStamp(value), parseDateFormats, true) : undefined;
};
//Formats a Date or Moment
var formatDate = function (value) {
return verifyTimeStamp(value ? moment(value).format(displayDateFormat) : '');
};
export {parseDateString, formatDate}; |
var sampleApp = angular.module('sampleApp', []); |
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import {camelise} from 'nodes/processors/uibuilder/utils';
import { actionCreators as canvasActions, selector } from '../..';
import { connect } from 'react-redux';
@connect(selector, (dispatch) => {
return{
actions: bindActionCreators(canvasActions, dispatch)
}
})
export default class Path extends Component {
shouldComponentUpdate(nextProps, nextState){
return this.props.template != nextProps.template || this.props.selected != nextProps.selected;
}
render(){
const {id,template,selected} = this.props;
const {d,style} = template;
const amSelected = selected.indexOf(id) !== -1;
let _style = camelise(style);
if (amSelected){
_style = {
..._style,
stroke:"#3f51b5",
strokeWidth:2,
fill:"#3f51b5",
fillOpacity: 0.8,
}
}
return <path d={d} style={_style} />
}
} |
(function (controllers, undefined) {
/**
* @ngdoc controller
* @name Merchello.Dashboards.Settings.Shipping.Dialogs.ShippingMethodController
* @function
*
* @description
* The controller for the adding / editing shipping methods on the Shipping page
*/
controllers.ChaseGatewayProviderController = function ($scope) {
/**
* @ngdoc method
* @name init
* @function
*
* @description
* Method called on intial page load. Loads in data from server and sets up scope.
*/
$scope.init = function () {
//$scope.dialogData.provider.extendedData
// on initial load extendedData will be empty but we need to populate with key values
//
if ($scope.dialogData.provider.extendedData.length > 0) {
var settingsString = $scope.dialogData.provider.extendedData[0].value;
$scope.chaseSettings = JSON.parse(settingsString);
// Watch with object equality to convert back to a string for the submit() call on the Save button
$scope.$watch(function () {
return $scope.chaseSettings;
}, function (newValue, oldValue) {
$scope.dialogData.provider.extendedData[0].value = angular.toJson(newValue);
},true);
}
};
$scope.init();
};
angular.module("umbraco").controller("Merchello.Plugin.GatewayProviders.Payments.Dialogs.ChaseGatewayProviderController", ['$scope', merchello.Controllers.ChaseGatewayProviderController]);
}(window.merchello.Controllers = window.merchello.Controllers || {}));
|
/**!
*
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
*/
'use strict';
var AmpState = require('ampersand-state');
var FeatureCollection = require('./feature-collection');
var FeaturesModel = AmpState.extend({
collections: {
developer: FeatureCollection,
entitlement: FeatureCollection,
user: FeatureCollection
},
_emitDeveloperChange: function emitDeveloperChange() {
this.trigger('change:developer', this.developer);
},
_emitEntitlementChange: function emitEntitlementChange() {
this.trigger('change:entitlement', this.entitlement);
},
_emitUserChange: function emitUserChange() {
this.trigger('change:user', this.user);
},
initialize: function initialize() {
this.developer.on('change:value', this._emitDeveloperChange.bind(this));
this.developer.on('add', this._emitDeveloperChange.bind(this));
this.developer.on('remove', this._emitDeveloperChange.bind(this));
this.entitlement.on('change:value', this._emitEntitlementChange.bind(this));
this.entitlement.on('add', this._emitEntitlementChange.bind(this));
this.entitlement.on('remove', this._emitEntitlementChange.bind(this));
this.user.on('change:value', this._emitUserChange.bind(this));
this.user.on('add', this._emitUserChange.bind(this));
this.user.on('remove', this._emitUserChange.bind(this));
}
});
module.exports = FeaturesModel;
|
/**
* This module is responsible for drawing an image to an enabled elements canvas element
*/
(function ($, cornerstone) {
"use strict";
/**
* Internal API function to draw an image to a given enabled element
* @param enabledElement
* @param invalidated - true if pixel data has been invalidated and cached rendering should not be used
*/
function drawImage(enabledElement, invalidated) {
var start = new Date();
enabledElement.image.render(enabledElement, invalidated);
var context = enabledElement.canvas.getContext('2d');
var end = new Date();
var diff = end - start;
//console.log(diff + ' ms');
var eventData = {
viewport : enabledElement.viewport,
element : enabledElement.element,
image : enabledElement.image,
enabledElement : enabledElement,
canvasContext: context,
renderTimeInMs : diff
};
$(enabledElement.element).trigger("CornerstoneImageRendered", eventData);
enabledElement.invalid = false;
}
// Module exports
cornerstone.internal.drawImage = drawImage;
cornerstone.drawImage = drawImage;
}($, cornerstone)); |
require('dotenv').load();
module.exports = {
development: {
client: 'pg',
connection: 'postgres://localhost/noobish'
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL + '?ssl=true'
}
};
|
describe("module:ngSanitize.service:$sanitize", function() {
beforeEach(function() {
browser.get("./examples/example-example67/index-jquery.html");
});
it('should sanitize the html snippet by default', function() {
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should inline raw snippet if bound to a trusted value', function() {
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should escape snippet without any filter', function() {
expect(element(by.css('#bind-default div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('new <b>text</b>');
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
'new <b onclick="alert(1)">text</b>');
expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
"new <b onclick=\"alert(1)\">text</b>");
});
});
|
var Promise = require('es6-promise').Promise;
describe('Helpers Misc.', function () {
// TODO test afterFlush
describe.skip('Built in Tracker helpers', function () {
var server = meteor();
var client = browser(server);
it('afterFlush should schedule function for next flush', function () {
return client
.afterFlush()
});
});
describe('Built in server connections helpers', function () {
var server = meteor();
var client = browser(server);
it('start in connected state.', function () {
return client
.wait(3000,'until connected',function(){
return Meteor.status().connected===true;
})
});
it('disconnect client from the server.', function () {
return client
.disconnect()
.execute(function () {
return Meteor.status();
})
.then(function(res) {
expect(res.connected).to.be.false;
})
});
it('reconnect client to the server.', function () {
return client
.reconnect()
.execute(function () {
return Meteor.status();
})
.then(function(res) {
expect(res.status).to.eql('connected');
expect(res.connected).to.be.true;
})
});
});
//TODO where to put screenshot file for this test ?
describe.skip('screenshot', function () {
var server = meteor();
var client = browser(server);
it('should save a screenshot to file.', function () {
return client
.screenshot()
.then(function(res) {
//assert file exists and is named by today's date and has some bytes
})
});
});
describe('Custom user-defined helpers', function () {
var server = meteor({
helpers: {
sleepFor100ms: function () {
return this.then(function () {
return new Promise(function (resolve) {
setTimeout(resolve, 100);
});
});
},
},
});
var client = browser(server, {
helpers: {
sleepFor100ms: function () {
return this.then(function () {
return new Promise(function (resolve) {
setTimeout(resolve, 100);
});
});
},
},
});
it('should be able to use a custom helper on the server', function () {
return server.sleepFor100ms();
});
it('should be able to use a custom helper on the client', function () {
return client.sleepFor100ms();
});
});
});
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/*
* This probably should live in plugman/cli world
* Transoforms old require calls to new node-style require calls
* the whole thing is fucking bullshit and needs to disappear ASAP
*/
var fs = require('fs');
var path = require('path');
var util = require('util');
var through = require('through');
var UglifyJS = require('uglify-js');
var root = fs.realpathSync(path.join(__dirname, '..', '..'));
var requireTr = {
transform: function(file) {
var data = '';
function write(buf) {
data += buf;
}
function end() {
// SOME BS pre-transforms
if(file.match(/android\/platform.js$/)) {
data = data.replace(/modulemapper\.clobbers.*\n/,
util.format('navigator.app = require("%s/src/android/plugin/android/app")', root));
}
if(file.match(/FileReader.js$/)) {
data = data.replace(/getOriginalSymbol\(this/,
'getOriginalSymbol(window');
}
this.queue(_updateRequires(data));
this.queue(null);
}
return through(write, end);
},
getModules: function() {
return this.modules;
},
addModule: function(module) {
if(!module || !module.symbol || !module.path) {
throw new Error("Can't add module without a symbol and a path");
}
this.modules.push(module);
},
platform: null,
modules: []
}
/*
* visits AST and modifies all the require('cordova/*') and require('org.apache.cordova.*')
*/
function _updateRequires(code) {
var ast = UglifyJS.parse(code);
var before = new UglifyJS.TreeTransformer(function(node, descend) {
// check all function calls
if(node instanceof UglifyJS.AST_Call) {
// check if function call is a require('module') call
if(node.expression.name === "require" && node.args.length === 1) {
var module = node.args[0].value;
// make sure require only has one argument and that it starts with cordova (old style require.js)
if(module !== undefined &&
module.indexOf("cordova") === 0) {
// adding symbolList bullcrap
if(requireTr.symbolList && requireTr.symbolList.indexOf(module) === -1) {
requireTr.symbolList.push(module);
}
// require('cordova') -> cordova.js
if(module === "cordova") {
node.args[0].value = path.join(root, "src", "cordova_b");
// require('cordova/init') -> common/init
} else if(module.match(/cordova\/init/)) {
node.args[0].value = module.replace(/cordova\/init/,
path.join(root, "src", "common", "init_b"));
// android and amazon-fireos have some special require's
} else if(module.match(/cordova\/(android|amazon-fireos)\/(.+)/)) {
node.args[0].value = module.replace(/cordova\/(android|amazon-fireos)\/(.+)/,
path.join(root, "src", "$1", "android", "$2"));
// require('cordova/exec') and require('cordova/platform') -> platform's exec/platform
} else if(module.match(/cordova\/(platform|exec)$/)) {
node.args[0].value = module.replace(/cordova\/(platform|exec)/,
path.join(root, "src", requireTr.platform, "$1"));
// require('cordova/anything') should be under common/
} else if(module.match(/cordova\/(.+)/)) {
node.args[0].value = module.replace(/cordova\/(.+)/,
path.join(root, "src", "common", "$1"));
}
}
else if(module !== undefined && ( module.indexOf("org.apache.cordova") !== -1 ||
module.indexOf("./") === 0 || module.indexOf("../") === 0 ) ) {
var modules = requireTr.getModules();
if(module.indexOf("../") === 0){
module = module.replace('../', '');
}
if(module.indexOf("./") === 0 ) {
module = module.replace('./', '');
}
for(var i = 0, j = modules.length ; i < j ; i++) {
var regx = new RegExp ("\\."+ module + "$");
if(module === modules[i].symbol || modules[i].symbol.search(regx) != -1) {
node.args[0].value = modules[i].path;
break;
}
}
}
descend(node, this);
return node;
}
}
});
ast.transform(before, null);
var stream = UglifyJS.OutputStream({beautify:true});
ast.print(stream);
return stream.toString();
}
module.exports = requireTr;
|
// This file serves as a common location for all your action constants
export const SOMETHING_HAPPENED_SUCCESSFULLY = "SOMETHING_HAPPENED_SUCCESSFULLY";
export const SOMETHING_FAILED = "SOMETHING_FAILED"; |
/*
Helper class that will increase build version of the app on each build.
This way we will forse main plugin to install www folder from the assets.
Otherwise - it will use the cached version.
*/
var path = require('path');
var plist = require('simple-plist');
var fs = require('fs');
var xmlHelper = require('./xmlHelper.js');
var logger = require('./logger.js');
var IOS_PLATFORM = 'ios';
var ANDROID_PLATFORM = 'android';
var BUILD_CONFIG = '.build_config';
var _iosPlistFile;
module.exports = {
increaseBuildVersion: increaseBuildVersion
};
// region Public API
/**
* Increase build version of the app.
*
* @param {Object} cordovaContext - cordova's context
*/
function increaseBuildVersion(cordovaContext) {
var platforms = cordovaContext.opts.platforms,
buildConfig = readBuildVersionsConfig(cordovaContext);
// increase only for the platforms we are building for right now
platforms.forEach(function(platform) {
switch (platform) {
case IOS_PLATFORM:
{
increaseBuildVersionForIos(cordovaContext, buildConfig);
break;
}
case ANDROID_PLATFORM:
{
increaseBuildVersionForAndroid(cordovaContext, buildConfig);
break;
}
default:
{
break;
}
}
});
saveBuildVersionsConfig(cordovaContext, buildConfig);
}
// endregion
// region Android update
/**
* Increase value of the android:versionCode of the app.
*
* @param {Object} cordovaContext - cordova's context
*/
function increaseBuildVersionForAndroid(cordovaContext, buildConfig) {
var androidManifestFilePath = path.join(cordovaContext.opts.projectRoot, 'platforms', ANDROID_PLATFORM, 'AndroidManifest.xml'),
manifestFileContent = xmlHelper.readXmlAsJson(androidManifestFilePath);
if (!manifestFileContent) {
logger.error('AndroidManifest.xml file is not found! Can\'t increase build version for android.');
return;
}
var currentVersion = parseInt(manifestFileContent['manifest']['$']['android:versionCode']),
newVersion = generateNewBuildVersion(currentVersion, buildConfig.android);
manifestFileContent['manifest']['$']['android:versionCode'] = newVersion.toString();
var isUpdated = xmlHelper.writeJsonAsXml(manifestFileContent, androidManifestFilePath);
if (isUpdated) {
logger.info('Android version code is set to ' + newVersion);
}
buildConfig.android = newVersion;
}
// endregion
// region iOS update
/**
* Increase CFBundleVersion of the app.
*
* @param {Object} cordovaContext - cordova context
*/
function increaseBuildVersionForIos(cordovaContext, buildConfig) {
var plistContent = readIosPlist(cordovaContext);
if (!plistContent) {
logger.error('Failed to read iOS project\'s plist file. Can\'t increase build version for iOS.');
return;
}
var currentVersion = parseInt(plistContent['CFBundleVersion']),
newVersion = generateNewBuildVersion(currentVersion, buildConfig.ios);
plistContent['CFBundleVersion'] = newVersion.toString();
plistContent['CFBundleShortVersionString'] = newVersion.toString();
var isUpdated = updateIosPlist(cordovaContext, plistContent);
if (isUpdated) {
logger.info('iOS bundle version set to ' + newVersion);
}
buildConfig.ios = newVersion;
}
/**
* Read iOS project's plist file.
* We need it to set new bundle version of the app.
*
* @param {Object} cordovaContext - cordova context
* @return {Object} plist file content as JSON object
*/
function readIosPlist(cordovaContext) {
var pathToIosConfigPlist = pathToIosPlistFile(cordovaContext),
plistFileContent;
try {
plistFileContent = fs.readFileSync(pathToIosConfigPlist, 'utf8');
} catch (err) {
logger.error(err);
return null;
}
return plist.parse(plistFileContent);
}
/**
* Save new data to the plist file.
*
* @param {Object} cordovaContext - cordova context
* @param {Object} plistContent - new plist data
* @return {Boolean} true - if content is saved; otherwise - false
*/
function updateIosPlist(cordovaContext, plistContent) {
var newPlist = plist.stringify(plistContent);
var pathToPlistFile = pathToIosPlistFile(cordovaContext);
try {
fs.writeFileSync(pathToPlistFile, newPlist, 'utf8');
} catch (err) {
logger.error(err);
return false;
}
return true;
}
/**
* Get file path to iOS plist.
*
* @param {Object} cordovaContext - cordova context
* @return {String} path to plist
*/
function pathToIosPlistFile(cordovaContext) {
if (_iosPlistFile) {
return _iosPlistFile;
}
var projectName = getProjectName(cordovaContext);
if (!projectName) {
logger.error('Project\'s name is unknown. Can\'t increase build version for iOS.');
return null;
}
_iosPlistFile = path.join(cordovaContext.opts.projectRoot, 'platforms', IOS_PLATFORM, projectName, projectName + '-Info.plist');
return _iosPlistFile;
}
/**
* Get name of the project from the config.xml.
*
* @param {Object} cordovaContext - cordova context
* @return {String} name of the project
*/
function getProjectName(cordovaContext) {
var projectsConfigXmlFilePath = path.join(cordovaContext.opts.projectRoot, 'config.xml'),
projectsConfigXml = xmlHelper.readXmlAsJson(projectsConfigXmlFilePath);
if (!projectsConfigXml) {
logger.error('Project\'s config.xml file is not found!');
return null;
}
return projectsConfigXml['widget']['name'][0];
}
// endregion
/**
* Generate new build version number of the app.
*
* @param {Integer} currentVersion - current version of the app
* @param {Integer} lastVersion - last versions of the app
* @return {Integer} new build version number
*/
function generateNewBuildVersion(currentVersion, lastVersion) {
if (currentVersion > lastVersion) {
return currentVersion + 1;
}
return lastVersion + 1;
}
/**
* Read cached config of the build versions.
*
* @param {Object} cordovaContext
* @return {Object} build config
*/
function readBuildVersionsConfig(cordovaContext) {
var pathToConfig = pathToBuildVersionsConfig(cordovaContext),
config;
try {
config = fs.readFileSync(pathToConfig, 'utf8');
} catch (err) {
return {
ios: 0,
android: 0
};
}
return JSON.parse(config);
}
/**
* Save new version of the build config.
*
* @param {Object} cordovaContext - cordova context
* @param {Object} newConfig - config to save
*/
function saveBuildVersionsConfig(cordovaContext, newConfig) {
var pathToConfig = pathToBuildVersionsConfig(cordovaContext),
newConfigAsString = JSON.stringify(newConfig, null, 2);
try {
fs.writeFileSync(pathToConfig, newConfigAsString, {
encoding: 'utf8',
flag: 'w+'
});
} catch (err) {
return false;
}
return true;
}
/**
* Path to the build config.
*
* @param {Object} cordovaContext - cordova context
* @return {String} path to the build config
*/
function pathToBuildVersionsConfig(cordovaContext) {
return path.join(cordovaContext.opts.projectRoot, 'plugins', cordovaContext.opts.plugin.id, BUILD_CONFIG);
}
|
"use strict";
// Git operations backed by shelling out.
let a = require("atom");
let BufferedProcess = a.BufferedProcess;
let Directory = a.Directory;
let fs = require("fs");
let path = require("path");
let common = require("./common");
exports.getContext = function (filePath) {
return Promise.all([locateGit(), common.getActiveGitRepo(filePath)])
.then((results) => {
const gitCmd = results[0];
const repoDetails = results[1];
if (!gitCmd || !repoDetails) return null;
const repository = repoDetails.repository;
const priority = repoDetails.priority;
let wd = repository.getWorkingDirectory();
return new GitContext(repository, gitCmd, wd, priority);
});
};
function GitContext(repository, gitCmd, workingDirPath, priority) {
this.repository = repository;
this.gitCmd = gitCmd;
this.workingDirPath = workingDirPath;
this.workingDirectory = new Directory(workingDirPath, false);
this.runProcess = (args) => new BufferedProcess(args);
this.priority = priority;
this.resolveText = "Stage";
};
GitContext.prototype.readConflicts = function () {
let conflicts = [];
let errMessage = [];
return new Promise((resolve, reject) => {
let stdoutHandler = (chunk) => {
statusCodesFrom(chunk, (index, work, p) => {
if (index === "U" && work === "U") {
conflicts.push({
path: path.normalize(p),
message: "both modified",
});
}
if (index === "A" && work === "A") {
conflicts.push({
path: path.normalize(p),
message: "both added",
});
}
});
};
let stderrHandler = (line) => errMessage.push(line);
let exitHandler = (code) => {
if (code === 0) {
return resolve(conflicts);
}
return reject(new Error(`abnormal git exit: ${code}\n${errMessage.join("\n")}`));
};
let proc = this.runProcess({
command: this.gitCmd,
args: ['status', '--porcelain'],
options: { cwd: this.workingDirPath },
stdout: stdoutHandler,
stderr: stderrHandler,
exit: exitHandler
});
proc.process.on("error", reject);
});
};
GitContext.prototype.isResolvedFile = function (filePath) {
let staged = true;
return new Promise((resolve, reject) => {
let stdoutHandler = (chunk) => {
statusCodesFrom(chunk, (index, work, p) => {
if (path.normalize(p) === filePath) {
staged = index === "M" && work === " ";
}
});
};
let stderrHandler = console.error;
let exitHandler = (code) => {
if (code === 0) {
resolve(staged);
} else {
reject(new Error(`git status exit: ${code}`));
}
};
let proc = this.runProcess({
command: this.gitCmd,
args: ["status", "--porcelain", filePath],
options: { cwd: this.workingDirPath },
stdout: stdoutHandler,
stderr: stderrHandler,
exit: exitHandler
});
proc.process.on("error", reject);
});
};
GitContext.prototype.checkoutSide = function (sideName, filePath) {
return new Promise((resolve, reject) => {
let proc = this.runProcess({
command: this.gitCmd,
args: ["checkout", `--${sideName}`, filePath],
options: { cwd: this.workingDirPath },
stdout: console.log,
stderr: console.error,
exit: (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`git checkout exit: ${code}`));
}
}
});
proc.process.on("error", reject);
});
};
GitContext.prototype.resolveFile = function (filePath) {
// git-utils wants paths with forward slashes. relativize takes care of that.
this.repository.repo.add(this.repository.repo.relativize(filePath));
return Promise.resolve();
};
GitContext.prototype.isRebasing = function () {
let root = this.repository.getPath();
if (!root) return false;
let hasDotGitDirectory = (dirName) => {
let fullPath = path.join(root, dirName);
let stat = fs.statSyncNoException(fullPath);
return stat && stat.isDirectory;
};
if (hasDotGitDirectory('rebase-apply')) return true;
if (hasDotGitDirectory('rebase-merge')) return true;
return false;
};
GitContext.prototype.mockProcess = function (handler) {
this.runProcess = handler;
};
let locateGit = function () {
// Use an explicitly provided path if one is available.
let possiblePath = atom.config.get("merge-conflicts.gitPath");
if (possiblePath) {
return Promise.resolve(possiblePath);
}
let search = [
'git', // Search the inherited execution PATH. Unreliable on Macs.
'/usr/local/bin/git', // Homebrew
'"%PROGRAMFILES%\\Git\\bin\\git"', // Reasonable Windows default
'"%LOCALAPPDATA%\\Programs\\Git\\bin\\git"' // Contributed Windows path
];
possiblePath = search.shift();
return new Promise((resolve, reject) => {
let exitHandler = (code) => {
if (code === 0) {
return resolve(possiblePath);
}
errorHandler();
};
let errorHandler = (err) => {
if (err) {
err.handle();
// Suppress the default ENOENT handler.
err.error.code = "NOTENOENT";
}
possiblePath = search.shift();
if (!possiblePath) {
let message = "Please set 'Git Path' correctly in the Atom settings for the Merge Conflicts"
message += " package.";
return reject(new Error(message));
}
tryPath();
};
let tryPath = () => {
new BufferedProcess({
command: possiblePath,
args: ["--version"],
exit: exitHandler
}).onWillThrowError(errorHandler);
};
tryPath();
});
};
let statusCodesFrom = function (chunk, handler) {
chunk.split("\n").forEach((line) => {
let m = line.match(/^(.)(.) (.+)$/);
if (m) {
let indexCode = m[1];
let workCode = m[2];
let p = m[3];
handler(indexCode, workCode, p);
}
});
};
GitContext.prototype.joinPath = function(relativePath) {
return path.join(this.workingDirPath, relativePath);
}
GitContext.prototype.quit = function(wasRebasing) {
common.quitContext(wasRebasing);
}
GitContext.prototype.complete = function(wasRebasing) {
common.completeContext(wasRebasing);
}
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load({ id = 0, ...rest }) {
return [
{ id: id + 1, name: '1' },
{ id: id + 2, name: '2' },
{ id: id + 3, name: '3' },
rest.user,
];
}
export default class RestParameters extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load({ id: 0, user: { id: 42, name: '42' } });
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-rest-parameters">
{this.state.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
}
|
run_spec(__dirname, ["typescript", "babel"], { arrowParens: "always" });
run_spec(__dirname, ["typescript", "babel"], { arrowParens: "avoid" });
|
import Ember from "ember-metal/core";
import {reduceComputed, ReduceComputedProperty } from "ember-runtime/computed/reduce_computed";
import EnumerableUtils from "ember-metal/enumerable_utils";
import {create} from "ember-metal/platform";
import {addObserver} from "ember-metal/observer";
import EmberError from "ember-metal/error";
var a_slice = [].slice,
o_create = create,
forEach = EnumerableUtils.forEach;
function ArrayComputedProperty() {
var cp = this;
ReduceComputedProperty.apply(this, arguments);
this.func = (function(reduceFunc) {
return function (propertyName) {
if (!cp._hasInstanceMeta(this, propertyName)) {
// When we recompute an array computed property, we need already
// retrieved arrays to be updated; we can't simply empty the cache and
// hope the array is re-retrieved.
forEach(cp._dependentKeys, function(dependentKey) {
addObserver(this, dependentKey, function() {
cp.recomputeOnce.call(this, propertyName);
});
}, this);
}
return reduceFunc.apply(this, arguments);
};
})(this.func);
return this;
}
ArrayComputedProperty.prototype = o_create(ReduceComputedProperty.prototype);
ArrayComputedProperty.prototype.initialValue = function () {
return Ember.A();
};
ArrayComputedProperty.prototype.resetValue = function (array) {
array.clear();
return array;
};
// This is a stopgap to keep the reference counts correct with lazy CPs.
ArrayComputedProperty.prototype.didChange = function (obj, keyName) {
return;
};
/**
Creates a computed property which operates on dependent arrays and
is updated with "one at a time" semantics. When items are added or
removed from the dependent array(s) an array computed only operates
on the change instead of re-evaluating the entire array. This should
return an array, if you'd like to use "one at a time" semantics and
compute some value other then an array look at
`Ember.reduceComputed`.
If there are more than one arguments the first arguments are
considered to be dependent property keys. The last argument is
required to be an options object. The options object can have the
following three properties.
`initialize` - An optional initialize function. Typically this will be used
to set up state on the instanceMeta object.
`removedItem` - A function that is called each time an element is
removed from the array.
`addedItem` - A function that is called each time an element is
added to the array.
The `initialize` function has the following signature:
```javascript
function (array, changeMeta, instanceMeta)
```
`array` - The initial value of the arrayComputed, an empty array.
`changeMeta` - An object which contains meta information about the
computed. It contains the following properties:
- `property` the computed property
- `propertyName` the name of the property on the object
`instanceMeta` - An object that can be used to store meta
information needed for calculating your computed. For example a
unique computed might use this to store the number of times a given
element is found in the dependent array.
The `removedItem` and `addedItem` functions both have the following signature:
```javascript
function (accumulatedValue, item, changeMeta, instanceMeta)
```
`accumulatedValue` - The value returned from the last time
`removedItem` or `addedItem` was called or an empty array.
`item` - the element added or removed from the array
`changeMeta` - An object which contains meta information about the
change. It contains the following properties:
- `property` the computed property
- `propertyName` the name of the property on the object
- `index` the index of the added or removed item
- `item` the added or removed item: this is exactly the same as
the second arg
- `arrayChanged` the array that triggered the change. Can be
useful when depending on multiple arrays.
For property changes triggered on an item property change (when
depKey is something like `someArray.@each.someProperty`),
`changeMeta` will also contain the following property:
- `previousValues` an object whose keys are the properties that changed on
the item, and whose values are the item's previous values.
`previousValues` is important Ember coalesces item property changes via
Ember.run.once. This means that by the time removedItem gets called, item has
the new values, but you may need the previous value (eg for sorting &
filtering).
`instanceMeta` - An object that can be used to store meta
information needed for calculating your computed. For example a
unique computed might use this to store the number of times a given
element is found in the dependent array.
The `removedItem` and `addedItem` functions should return the accumulated
value. It is acceptable to not return anything (ie return undefined)
to invalidate the computation. This is generally not a good idea for
arrayComputed but it's used in eg max and min.
Example
```javascript
Ember.computed.map = function(dependentKey, callback) {
var options = {
addedItem: function(array, item, changeMeta, instanceMeta) {
var mapped = callback(item);
array.insertAt(changeMeta.index, mapped);
return array;
},
removedItem: function(array, item, changeMeta, instanceMeta) {
array.removeAt(changeMeta.index, 1);
return array;
}
};
return Ember.arrayComputed(dependentKey, options);
};
```
@method arrayComputed
@for Ember
@param {String} [dependentKeys*]
@param {Object} options
@return {Ember.ComputedProperty}
*/
function arrayComputed (options) {
var args;
if (arguments.length > 1) {
args = a_slice.call(arguments, 0, -1);
options = a_slice.call(arguments, -1)[0];
}
if (typeof options !== "object") {
throw new EmberError("Array Computed Property declared without an options hash");
}
var cp = new ArrayComputedProperty(options);
if (args) {
cp.property.apply(cp, args);
}
return cp;
};
export {arrayComputed, ArrayComputedProperty}
|
'use strict';
var pathUtil = require('path');
var fs = require('fs');
var Q = require('q');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
var modeUtil = require('./utils/mode');
var getCriteriaDefaults = function (passedCriteria) {
var criteria = passedCriteria || {};
if (typeof criteria.empty !== 'boolean') {
criteria.empty = false;
}
if (criteria.mode !== undefined) {
criteria.mode = modeUtil.normalizeFileMode(criteria.mode);
}
return criteria;
};
var generatePathOccupiedByNotDirectoryError = function (path) {
return new Error('Path ' + path + ' exists but is not a directory.' +
' Halting jetpack.dir() call for safety reasons.');
};
// ---------------------------------------------------------
// Sync
// ---------------------------------------------------------
var checkWhatAlreadyOccupiesPathSync = function (path) {
var stat;
try {
stat = fs.statSync(path);
} catch (err) {
// Detection if path already exists
if (err.code !== 'ENOENT') {
throw err;
}
}
if (stat && !stat.isDirectory()) {
throw generatePathOccupiedByNotDirectoryError(path);
}
return stat;
};
var createBrandNewDirectorySync = function (path, criteria) {
mkdirp.sync(path, { mode: criteria.mode });
};
var checkExistingDirectoryFulfillsCriteriaSync = function (path, stat, criteria) {
var checkMode = function () {
var mode = modeUtil.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
fs.chmodSync(path, criteria.mode);
}
};
var checkEmptiness = function () {
var list;
if (criteria.empty) {
// Delete everything inside this directory
list = fs.readdirSync(path);
list.forEach(function (filename) {
rimraf.sync(pathUtil.resolve(path, filename));
});
}
};
checkMode();
checkEmptiness();
};
var dirSync = function (path, passedCriteria) {
var criteria = getCriteriaDefaults(passedCriteria);
var stat = checkWhatAlreadyOccupiesPathSync(path);
if (stat) {
checkExistingDirectoryFulfillsCriteriaSync(path, stat, criteria);
} else {
createBrandNewDirectorySync(path, criteria);
}
};
// ---------------------------------------------------------
// Async
// ---------------------------------------------------------
var promisedStat = Q.denodeify(fs.stat);
var promisedChmod = Q.denodeify(fs.chmod);
var promisedReaddir = Q.denodeify(fs.readdir);
var promisedRimraf = Q.denodeify(rimraf);
var promisedMkdirp = Q.denodeify(mkdirp);
var checkWhatAlreadyOccupiesPathAsync = function (path) {
var deferred = Q.defer();
promisedStat(path)
.then(function (stat) {
if (stat.isDirectory()) {
deferred.resolve(stat);
} else {
deferred.reject(generatePathOccupiedByNotDirectoryError(path));
}
})
.catch(function (err) {
if (err.code === 'ENOENT') {
// Path doesn't exist
deferred.resolve(undefined);
} else {
// This is other error that nonexistent path, so end here.
deferred.reject(err);
}
});
return deferred.promise;
};
// Delete all files and directores inside given directory
var emptyAsync = function (path) {
var deferred = Q.defer();
promisedReaddir(path)
.then(function (list) {
var doOne = function (index) {
var subPath;
if (index === list.length) {
deferred.resolve();
} else {
subPath = pathUtil.resolve(path, list[index]);
promisedRimraf(subPath).then(function () {
doOne(index + 1);
});
}
};
doOne(0);
})
.catch(deferred.reject);
return deferred.promise;
};
var checkExistingDirectoryFulfillsCriteriaAsync = function (path, stat, criteria) {
var deferred = Q.defer();
var checkMode = function () {
var mode = modeUtil.normalizeFileMode(stat.mode);
if (criteria.mode !== undefined && criteria.mode !== mode) {
return promisedChmod(path, criteria.mode);
}
return new Q();
};
var checkEmptiness = function () {
if (criteria.empty) {
return emptyAsync(path);
}
return new Q();
};
checkMode()
.then(checkEmptiness)
.then(deferred.resolve, deferred.reject);
return deferred.promise;
};
var createBrandNewDirectoryAsync = function (path, criteria) {
return promisedMkdirp(path, { mode: criteria.mode });
};
var dirAsync = function (path, passedCriteria) {
var deferred = Q.defer();
var criteria = getCriteriaDefaults(passedCriteria);
checkWhatAlreadyOccupiesPathAsync(path)
.then(function (stat) {
if (stat !== undefined) {
return checkExistingDirectoryFulfillsCriteriaAsync(path, stat, criteria);
}
return createBrandNewDirectoryAsync(path, criteria);
})
.then(deferred.resolve, deferred.reject);
return deferred.promise;
};
// ---------------------------------------------------------
// API
// ---------------------------------------------------------
module.exports.sync = dirSync;
module.exports.async = dirAsync;
|
'use strict';
var Promise = require('../../ext/promise');
var path = require('path');
var fs = require('fs');
var Task = require('../../models/task');
var SilentError = require('silent-error');
function createServer(options) {
var instance;
var Server = (require('tiny-lr')).Server;
Server.prototype.error = function() {
instance.error.apply(instance, arguments);
};
instance = new Server(options);
return instance;
}
module.exports = Task.extend({
liveReloadServer: function(options) {
if (this._liveReloadServer) {
return this._liveReloadServer;
}
this._liveReloadServer = createServer(options);
return this._liveReloadServer;
},
listen: function(options) {
var server = this.liveReloadServer(options);
return new Promise(function(resolve, reject) {
server.error = reject;
server.listen(options.port, options.host, resolve);
});
},
start: function(options) {
var tlroptions = {};
tlroptions.ssl = options.ssl;
tlroptions.host = options.liveReloadHost || options.host;
tlroptions.port = options.liveReloadPort;
if (options.liveReload !== true) {
return Promise.resolve('Livereload server manually disabled.');
}
if (options.ssl) {
tlroptions.key = fs.readFileSync(options.sslKey);
tlroptions.cert = fs.readFileSync(options.sslCert);
}
// Reload on file changes
this.watcher.on('change', this.didChange.bind(this));
this.watcher.on('error', this.didChange.bind(this));
// Reload on express server restarts
this.expressServer.on('restart', this.didRestart.bind(this));
var url = 'http' + (options.ssl ? 's' : '') + '://' + this.displayHost(tlroptions.host) + ':' + tlroptions.port;
// Start LiveReload server
return this.listen(tlroptions)
.then(this.writeBanner.bind(this, url))
.catch(this.writeErrorBanner.bind(this, url));
},
displayHost: function(specifiedHost) {
return specifiedHost === '0.0.0.0' ? 'localhost' : specifiedHost;
},
writeBanner: function(url) {
this.ui.writeLine('Livereload server on ' + url);
},
writeErrorBanner: function(url) {
throw new SilentError('Livereload failed on ' + url + '. It is either in use or you do not have permission.');
},
didChange: function(results) {
var filePath = path.relative(this.project.root, results.filePath || '');
var canTrigger = this.project.liveReloadFilterPatterns.reduce(function(bool, pattern) {
bool = bool && !filePath.match(pattern);
return bool;
}, true);
if (canTrigger) {
this.liveReloadServer().changed({
body: {
files: ['LiveReload files']
}
});
this.analytics.track({
name: 'broccoli watcher',
message: 'live-reload'
});
}
},
didRestart: function() {
this.liveReloadServer().changed({
body: {
files: ['LiveReload files']
}
});
this.analytics.track({
name: 'express server',
message: 'live-reload'
});
}
});
|
"use strict";
var fs = require ("fs");
var http = require ("http");
var tftp = require ("../../lib");
/*
This example demonstrates the usefulness of the streams. When the client
requests a file named "node.exe", it obtains the data from a remote location, in
this case via http.
*/
var handleError = function (error){
console.error (error);
};
var server = tftp.createServer ({
port: 1234
}, function (req, tftpRes){
req.on ("error", function (error){
//Error from the request
gs.abort ();
handleError (error);
});
if (req.file === "node.exe"){
//Prevent from uploading a file named "node.exe"
if (req.method === "PUT") return req.abort (tftp.ENOPUT);
//Get the file from internet
var gs = http.get ("http://nodejs.org/dist/latest/node.exe",
function (httpRes){
//Set the response size, this is mandatory
tftpRes.setSize (parseInt (httpRes.headers["content-length"]));
//As soon as the data chunks are received from the remote location via
//http, send them back to client via tftp
httpRes.pipe (tftpRes);
}).on ("error", function (error){
req.on ("abort", function (){
handleError (error);
});
req.abort (tftp.EIO);
});
}else{
//Call the default request listener for the rest of the files
this.requestListener (req, res);
}
});
server.on ("error", function (error){
//Errors from the main socket
console.error (error);
});
server.on ("listening", doRequest);
server.listen ();
function doRequest (){
tftp.createClient ({ port: 1234 }).get ("node.exe", function (error){
server.close ();
try{ fs.unlinkSync ("node.exe"); }catch (error){}
if (error) console.error (error);
});
} |
/*======================================================
************ Views ************
======================================================*/
app.views = [];
var View = function (selector, params) {
var defaults = {
dynamicNavbar: false,
domCache: false,
linksView: undefined,
swipeBackPage: app.params.swipeBackPage,
swipeBackPageBoxShadow: app.params.swipeBackPageBoxShadow,
swipeBackPageActiveArea: app.params.swipeBackPageActiveArea,
swipeBackPageThreshold: app.params.swipeBackPageThreshold,
animatePages: app.params.animatePages
};
params = params || {};
for (var def in defaults) {
if (typeof params[def] === 'undefined') {
params[def] = defaults[def];
}
}
// View
var view = this;
view.params = params;
// Selector
view.selector = selector;
// Container
var container = $(selector);
view.container = container[0];
// Location
var docLocation = document.location.href;
// History
view.history = [];
var viewURL = docLocation;
var pushStateSeparator = app.params.pushStateSeparator;
var pushStateRoot = app.params.pushStateRoot;
if (app.params.pushState) {
if (pushStateRoot) {
viewURL = pushStateRoot;
}
else {
if (viewURL.indexOf(pushStateSeparator) >= 0 && viewURL.indexOf(pushStateSeparator + '#') < 0) viewURL = viewURL.split(pushStateSeparator)[0];
}
}
view.url = container.attr('data-url') || view.params.url || viewURL;
// Store to history main view's url
if (view.url) {
view.history.push(view.url);
}
// Content cache
view.contentCache = {};
// Store View in element for easy access
container[0].f7View = view;
// Pages
view.pagesContainer = container.find('.pages')[0];
view.allowPageChange = true;
// Active Page
if (!view.activePage) {
var currentPage = $(view.pagesContainer).find('.page-on-center');
var currentPageData;
if (currentPage.length === 0) {
currentPage = $(view.pagesContainer).find('.page');
currentPage = currentPage.eq(currentPage.length - 1);
}
if (currentPage.length > 0) {
currentPageData = currentPage[0].f7PageData;
}
if (currentPageData) {
currentPageData.view = view;
if (view.url) currentPageData.url = view.url;
view.activePage = currentPageData;
currentPage[0].f7PageData = currentPageData;
}
}
// Is main
view.main = container.hasClass(app.params.viewMainClass);
// Touch events
var isTouched = false,
isMoved = false,
touchesStart = {},
isScrolling,
activePage,
previousPage,
viewContainerWidth,
touchesDiff,
allowViewTouchMove = true,
touchStartTime,
activeNavbar,
previousNavbar,
activeNavElements,
previousNavElements,
activeNavBackIcon,
previousNavBackIcon,
dynamicNavbar,
el;
view.handleTouchStart = function (e) {
if (!allowViewTouchMove || !view.params.swipeBackPage || isTouched || app.swipeoutOpenedEl) return;
isMoved = false;
isTouched = true;
isScrolling = undefined;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchStartTime = (new Date()).getTime();
dynamicNavbar = view.params.dynamicNavbar && container.find('.navbar-inner').length > 1;
};
view.handleTouchMove = function (e) {
if (!isTouched) return;
var pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
var pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
if (isScrolling || e.f7PreventSwipeBack) {
isTouched = false;
return;
}
e.f7PreventPanelSwipe = true;
if (!isMoved) {
var cancel = false;
// Calc values during first move fired
viewContainerWidth = container.width();
var target = $(e.target);
activePage = target.is('.page') ? target : target.parents('.page');
if (activePage.hasClass('no-swipeback')) cancel = true;
previousPage = container.find('.page-on-left:not(.cached)');
var notFromBorder = touchesStart.x - container.offset().left > view.params.swipeBackPageActiveArea;
if (app.rtl) {
notFromBorder = touchesStart.x < container.offset().left - container[0].scrollLeft + viewContainerWidth - view.params.swipeBackPageActiveArea;
}
else {
notFromBorder = touchesStart.x - container.offset().left > view.params.swipeBackPageActiveArea;
}
if (notFromBorder) cancel = true;
if (previousPage.length === 0 || activePage.length === 0) cancel = true;
if (cancel) {
isTouched = false;
return;
}
if (dynamicNavbar) {
activeNavbar = container.find('.navbar-on-center:not(.cached)');
previousNavbar = container.find('.navbar-on-left:not(.cached)');
activeNavElements = activeNavbar.find('.left, .center, .right');
previousNavElements = previousNavbar.find('.left, .center, .right');
if (app.params.animateNavBackIcon) {
activeNavBackIcon = activeNavbar.find('.left.sliding .back .icon');
previousNavBackIcon = previousNavbar.find('.left.sliding .back .icon');
}
}
}
isMoved = true;
e.preventDefault();
// RTL inverter
var inverter = app.rtl ? -1 : 1;
// Touches diff
touchesDiff = (pageX - touchesStart.x - view.params.swipeBackPageThreshold) * inverter;
if (touchesDiff < 0) touchesDiff = 0;
var percentage = touchesDiff / viewContainerWidth;
// Swipe Back Callback
var callbackData = {
percentage: percentage,
activePage: activePage[0],
previousPage: previousPage[0],
activeNavbar: activeNavbar[0],
previousNavbar: previousNavbar[0]
};
if (view.params.onSwipeBackMove) {
view.params.onSwipeBackMove(callbackData);
}
container.trigger('swipebackmove', callbackData);
// Transform pages
var activePageTranslate = touchesDiff * inverter;
var previousPageTranslate = (touchesDiff / 5 - viewContainerWidth / 5) * inverter;
if (app.device.pixelRatio === 1) {
activePageTranslate = Math.round(activePageTranslate);
previousPageTranslate = Math.round(previousPageTranslate);
}
activePage.transform('translate3d(' + activePageTranslate + 'px,0,0)');
if (view.params.swipeBackPageBoxShadow && app.device.os !== 'android') activePage[0].style.boxShadow = '0px 0px 12px rgba(0,0,0,' + (0.5 - 0.5 * percentage) + ')';
previousPage.transform('translate3d(' + previousPageTranslate + 'px,0,0)');
previousPage[0].style.opacity = 0.9 + 0.1 * percentage;
// Dynamic Navbars Animation
if (dynamicNavbar) {
var i;
for (i = 0; i < activeNavElements.length; i++) {
el = $(activeNavElements[i]);
el[0].style.opacity = (1 - percentage * 1.3);
if (el[0].className.indexOf('sliding') >= 0) {
var activeNavTranslate = percentage * el[0].f7NavbarRightOffset;
if (app.device.pixelRatio === 1) activeNavTranslate = Math.round(activeNavTranslate);
el.transform('translate3d(' + activeNavTranslate + 'px,0,0)');
if (app.params.animateNavBackIcon) {
if (el[0].className.indexOf('left') >= 0 && activeNavBackIcon.length > 0) {
activeNavBackIcon.transform('translate3d(' + -activeNavTranslate + 'px,0,0)');
}
}
}
}
for (i = 0; i < previousNavElements.length; i++) {
el = $(previousNavElements[i]);
el[0].style.opacity = percentage * 1.3 - 0.3;
if (el[0].className.indexOf('sliding') >= 0) {
var previousNavTranslate = el[0].f7NavbarLeftOffset * (1 - percentage);
if (app.device.pixelRatio === 1) previousNavTranslate = Math.round(previousNavTranslate);
el.transform('translate3d(' + previousNavTranslate + 'px,0,0)');
if (app.params.animateNavBackIcon) {
if (el[0].className.indexOf('left') >= 0 && previousNavBackIcon.length > 0) {
previousNavBackIcon.transform('translate3d(' + -previousNavTranslate + 'px,0,0)');
}
}
}
}
}
};
view.handleTouchEnd = function (e) {
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
isTouched = false;
isMoved = false;
if (touchesDiff === 0) {
$([activePage[0], previousPage[0]]).transform('').css({opacity: '', boxShadow: ''});
if (dynamicNavbar) {
activeNavElements.transform('').css({opacity: ''});
previousNavElements.transform('').css({opacity: ''});
if (activeNavBackIcon && activeNavBackIcon.length > 0) activeNavBackIcon.transform('');
if (previousNavBackIcon && activeNavBackIcon.length > 0) previousNavBackIcon.transform('');
}
return;
}
var timeDiff = (new Date()).getTime() - touchStartTime;
var pageChanged = false;
// Swipe back to previous page
if (
timeDiff < 300 && touchesDiff > 10 ||
timeDiff >= 300 && touchesDiff > viewContainerWidth / 2
) {
activePage.removeClass('page-on-center').addClass('page-on-right');
previousPage.removeClass('page-on-left').addClass('page-on-center');
if (dynamicNavbar) {
activeNavbar.removeClass('navbar-on-center').addClass('navbar-on-right');
previousNavbar.removeClass('navbar-on-left').addClass('navbar-on-center');
}
pageChanged = true;
}
// Reset custom styles
// Add transitioning class for transition-duration
$([activePage[0], previousPage[0]]).transform('').css({opacity: '', boxShadow: ''}).addClass('page-transitioning');
if (dynamicNavbar) {
activeNavElements.css({opacity: ''})
.each(function () {
var translate = pageChanged ? this.f7NavbarRightOffset : 0;
var sliding = $(this);
sliding.transform('translate3d(' + translate + 'px,0,0)');
if (app.params.animateNavBackIcon) {
if (sliding.hasClass('left') && activeNavBackIcon.length > 0) {
activeNavBackIcon.addClass('page-transitioning').transform('translate3d(' + -translate + 'px,0,0)');
}
}
}).addClass('page-transitioning');
previousNavElements.transform('').css({opacity: ''}).each(function () {
var translate = pageChanged ? 0 : this.f7NavbarLeftOffset;
var sliding = $(this);
sliding.transform('translate3d(' + translate + 'px,0,0)');
if (app.params.animateNavBackIcon) {
if (sliding.hasClass('left') && previousNavBackIcon.length > 0) {
previousNavBackIcon.addClass('page-transitioning').transform('translate3d(' + -translate + 'px,0,0)');
}
}
}).addClass('page-transitioning');
}
allowViewTouchMove = false;
view.allowPageChange = false;
if (pageChanged) {
// Update View's URL
var url = view.history[view.history.length - 2];
view.url = url;
// Page before animation callback
app.pageAnimCallbacks('before', view, {pageContainer: previousPage[0], url: url, position: 'left', newPage: previousPage, oldPage: activePage, swipeBack: true});
}
activePage.transitionEnd(function () {
$([activePage[0], previousPage[0]]).removeClass('page-transitioning');
if (dynamicNavbar) {
activeNavElements.removeClass('page-transitioning').css({opacity: ''});
previousNavElements.removeClass('page-transitioning').css({opacity: ''});
if (activeNavBackIcon && activeNavBackIcon.length > 0) activeNavBackIcon.removeClass('page-transitioning');
if (previousNavBackIcon && previousNavBackIcon.length > 0) previousNavBackIcon.removeClass('page-transitioning');
}
allowViewTouchMove = true;
view.allowPageChange = true;
if (pageChanged) {
if (app.params.pushState) history.back();
// Page after animation callback
app.pageAnimCallbacks('after', view, {pageContainer: previousPage[0], url: url, position: 'left', newPage: previousPage, oldPage: activePage, swipeBack: true});
app.afterGoBack(view, activePage, previousPage);
}
});
};
view.attachEvents = function (detach) {
var action = detach ? 'off' : 'on';
container[action](app.touchEvents.start, view.handleTouchStart);
container[action](app.touchEvents.move, view.handleTouchMove);
container[action](app.touchEvents.end, view.handleTouchEnd);
};
view.detachEvents = function () {
view.attachEvents(true);
};
// Init
if (view.params.swipeBackPage) {
view.attachEvents();
}
// Add view to app
app.views.push(view);
if (view.main) app.mainView = view;
// Load methods
view.loadPage = function (url, animatePages) {
return app.loadPage(view, url, animatePages);
};
view.loadContent = function (content, animatePages) {
return app.loadContent(view, content, animatePages);
};
view.goBack = function (url, animatePages) {
return app.goBack(view, url, animatePages);
};
// Bars methods
view.hideNavbar = function () {
return app.hideNavbar(container);
};
view.showNavbar = function () {
return app.showNavbar(container);
};
view.hideToolbar = function () {
return app.hideToolbar(container);
};
view.showToolbar = function () {
return app.showToolbar(container);
};
// Push State on load
if (app.params.pushState && view.main) {
var pushStateUrl;
if (pushStateRoot) {
pushStateUrl = docLocation.split(app.params.pushStateRoot + pushStateSeparator)[1];
}
else if (docLocation.indexOf(pushStateSeparator) >= 0 && docLocation.indexOf(pushStateSeparator + '#') < 0) {
pushStateUrl = docLocation.split(pushStateSeparator)[1];
}
var pushStateAnimatePages;
if (app.params.pushStateNoAnimation === true) pushStateAnimatePages = false;
if (pushStateUrl) {
app.loadPage(view, pushStateUrl, pushStateAnimatePages, false);
}
}
// Destroy
view.destroy = function () {
view.detachEvents();
view = undefined;
};
// Plugin hook
app.pluginHook('addView', view);
// Return view
return view;
};
app.addView = function (selector, params) {
return new View(selector, params);
}; |
'use strict';
var Utils = require('./utils')
, uuid = require('node-uuid');
/**
* The transaction object is used to identify a running transaction. It is created by calling `Sequelize.transaction()`.
*
* To run a query under a transaction, you should pass the transaction in the options object.
* @class Transaction
* @constructor
*
* @param {Sequelize} sequelize A configured sequelize Instance
* @param {Object} options An object with options
* @param {Boolean} options.autocommit Sets the autocommit property of the transaction.
* @param {String} options.type=true Sets the type of the transaction.
* @param {String} options.isolationLevel=true Sets the isolation level of the transaction.
* @param {String} options.deferrable Sets the constraints to be deferred or immediately checked.
*/
var Transaction = module.exports = function(sequelize, options) {
this.sequelize = sequelize;
this.savepoints = [];
// get dialect specific transaction options
var transactionOptions = sequelize.dialect.supports.transactionOptions || {};
this.options = Utils._.extend({
autocommit: transactionOptions.autocommit || null,
type: sequelize.options.transactionType,
isolationLevel: sequelize.options.isolationLevel
}, options || {});
this.parent = this.options.transaction;
this.id = this.parent ? this.parent.id : uuid.v4();
if (this.parent) {
this.id = this.parent.id;
this.parent.savepoints.push(this);
this.name = this.id + '-savepoint-' + this.parent.savepoints.length;
} else {
this.id = this.name = uuid.v4();
}
delete this.options.transaction;
};
/**
* Types can be set per-transaction by passing `options.type` to `sequelize.transaction`.
* Default to `DEFERRED` but you can override the default type by passing `options.transactionType` in `new Sequelize`.
* Sqlite only.
*
* The possible types to use when starting a transaction:
*
* ```js
* {
* DEFERRED: "DEFERRED",
* IMMEDIATE: "IMMEDIATE",
* EXCLUSIVE: "EXCLUSIVE"
* }
* ```
*
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({
* type: Sequelize.Transaction.EXCLUSIVE
* }, function (t) {
*
* // your transactions
*
* }).then(function(result) {
* // transaction has been committed. Do something after the commit if required.
* }).catch(function(err) {
* // do something with the err.
* });
* ```
*
* @property TYPES
*/
Transaction.TYPES = {
DEFERRED: 'DEFERRED',
IMMEDIATE: 'IMMEDIATE',
EXCLUSIVE: 'EXCLUSIVE'
};
/**
* Isolations levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`.
* Default to `REPEATABLE_READ` but you can override the default isolation level by passing `options.isolationLevel` in `new Sequelize`.
*
* The possible isolations levels to use when starting a transaction:
*
* ```js
* {
* READ_UNCOMMITTED: "READ UNCOMMITTED",
* READ_COMMITTED: "READ COMMITTED",
* REPEATABLE_READ: "REPEATABLE READ",
* SERIALIZABLE: "SERIALIZABLE"
* }
* ```
*
* Pass in the desired level as the first argument:
*
* ```js
* return sequelize.transaction({
* isolationLevel: Sequelize.Transaction.SERIALIZABLE
* }, function (t) {
*
* // your transactions
*
* }).then(function(result) {
* // transaction has been committed. Do something after the commit if required.
* }).catch(function(err) {
* // do something with the err.
* });
* ```
*
* @property ISOLATION_LEVELS
*/
Transaction.ISOLATION_LEVELS = {
READ_UNCOMMITTED: 'READ UNCOMMITTED',
READ_COMMITTED: 'READ COMMITTED',
REPEATABLE_READ: 'REPEATABLE READ',
SERIALIZABLE: 'SERIALIZABLE'
};
/**
* Possible options for row locking. Used in conjunction with `find` calls:
*
* ```js
* t1 // is a transaction
* t1.LOCK.UPDATE,
* t1.LOCK.SHARE,
* t1.LOCK.KEY_SHARE, // Postgres 9.3+ only
* t1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ only
* ```
*
* Usage:
* ```js
* t1 // is a transaction
* Model.findAll({
* where: ...,
* transaction: t1,
* lock: t1.LOCK...
* });
* ```
*
* Postgres also supports specific locks while eager loading by using OF:
* ```js
* UserModel.findAll({
* where: ...,
* include: [TaskModel, ...],
* transaction: t1,
* lock: {
* level: t1.LOCK...,
* of: UserModel
* }
* });
* ```
* UserModel will be locked but TaskModel won't!
*
* @property LOCK
*/
Transaction.LOCK = Transaction.prototype.LOCK = {
UPDATE: 'UPDATE',
SHARE: 'SHARE',
KEY_SHARE: 'KEY SHARE',
NO_KEY_UPDATE: 'NO KEY UPDATE'
};
/**
* Commit the transaction
*
* @return {Promise}
*/
Transaction.prototype.commit = function() {
var self = this;
if (this.finished) {
throw new Error('Transaction cannot be committed because it has been finished with state: ' + self.finished);
}
this.$clearCls();
return this
.sequelize
.getQueryInterface()
.commitTransaction(this, this.options)
.finally(function() {
self.finished = 'commit';
if (!self.parent) {
return self.cleanup();
}
return null;
});
};
/**
* Rollback (abort) the transaction
*
* @return {Promise}
*/
Transaction.prototype.rollback = function() {
var self = this;
if (this.finished) {
throw new Error('Transaction cannot be rolled back because it has been finished with state: ' + self.finished);
}
this.$clearCls();
return this
.sequelize
.getQueryInterface()
.rollbackTransaction(this, this.options)
.finally(function() {
if (!self.parent) {
return self.cleanup();
}
return self;
});
};
Transaction.prototype.prepareEnvironment = function() {
var self = this;
return Utils.Promise.resolve(
self.parent ? self.parent.connection : self.sequelize.connectionManager.getConnection({ uuid: self.id })
).then(function (connection) {
self.connection = connection;
self.connection.uuid = self.id;
}).then(function () {
return self.begin();
}).then(function () {
return self.setDeferrable();
}).then(function () {
return self.setIsolationLevel();
}).then(function () {
return self.setAutocommit();
}).catch(function (setupErr) {
return self.rollback().finally(function () {
throw setupErr;
});
}).tap(function () {
if (self.sequelize.constructor.cls) {
self.sequelize.constructor.cls.set('transaction', self);
}
return null;
});
};
Transaction.prototype.begin = function() {
return this
.sequelize
.getQueryInterface()
.startTransaction(this, this.options);
};
Transaction.prototype.setDeferrable = function () {
if (this.options.deferrable) {
return this
.sequelize
.getQueryInterface()
.deferConstraints(this, this.options);
}
};
Transaction.prototype.setAutocommit = function() {
return this
.sequelize
.getQueryInterface()
.setAutocommit(this, this.options.autocommit, this.options);
};
Transaction.prototype.setIsolationLevel = function() {
return this
.sequelize
.getQueryInterface()
.setIsolationLevel(this, this.options.isolationLevel, this.options);
};
Transaction.prototype.cleanup = function() {
var res = this.sequelize.connectionManager.releaseConnection(this.connection);
this.connection.uuid = undefined;
return res;
};
Transaction.prototype.$clearCls = function () {
var cls = this.sequelize.constructor.cls;
if (cls) {
if (cls.get('transaction') === this) {
cls.set('transaction', null);
}
}
};
|
//>>built
define("dijit/_editor/nls/zh-hk/LinkDialog",{createLinkTitle:"\u93c8\u7d50\u5167\u5bb9",insertImageTitle:"\u5f71\u50cf\u5167\u5bb9",url:"URL\uff1a",text:"\u8aaa\u660e\uff1a",target:"\u76ee\u6a19\uff1a",set:"\u8a2d\u5b9a",currentWindow:"\u73fe\u884c\u8996\u7a97",parentWindow:"\u4e0a\u5c64\u8996\u7a97",topWindow:"\u6700\u4e0a\u9762\u7684\u8996\u7a97",newWindow:"\u65b0\u8996\u7a97"}); |
var utils = require('../utils'),
nodes = require('../nodes');
/**
* This is a helper function for the slice method
*
* @param {String|Ident} vals
* @param {Unit} start [0]
* @param {Unit} end [vals.length]
* @return {String|Literal|Null}
* @api public
*/
(module.exports = function slice(val, start, end) {
start = start && start.nodes[0].val;
end = end && end.nodes[0].val;
val = utils.unwrap(val).nodes;
if (val.length > 1) {
return utils.coerce(val.slice(start, end), true);
}
var result = val[0].string.slice(start, end);
return val[0] instanceof nodes.Ident
? new nodes.Ident(result)
: new nodes.String(result);
}).raw = true;
|
/*
* @name Triangle Strip
* @description 由 Ira Greenberg 提供的范例。使用 vertex() 函数和 beginShape(TRIANGLE_STRIP) 模式生成闭环。
* 这个 outsideRadius 和 insideRadius 变量分别控制环的内外半径。
*/
let x;
let y;
let outsideRadius = 150;
let insideRadius = 100;
function setup() {
createCanvas(720, 400);
background(204);
x = width / 2;
y = height / 2;
}
function draw() {
background(204);
let numPoints = int(map(mouseX, 0, width, 6, 60));
let angle = 0;
let angleStep = 180.0 / numPoints;
beginShape(TRIANGLE_STRIP);
for (let i = 0; i <= numPoints; i++) {
let px = x + cos(radians(angle)) * outsideRadius;
let py = y + sin(radians(angle)) * outsideRadius;
angle += angleStep;
vertex(px, py);
px = x + cos(radians(angle)) * insideRadius;
py = y + sin(radians(angle)) * insideRadius;
vertex(px, py);
angle += angleStep;
}
endShape();
}
|
/*
* https://github.com/davidchambers/Base64.js
*/
;(function () {
var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
// encoder
// [https://gist.github.com/999166] by [https://github.com/nignag]
object.btoa || (
object.btoa = function (input) {
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next input index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
input.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = input.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
});
// decoder
// [https://gist.github.com/1020396] by [https://github.com/atk]
object.atob || (
object.atob = function (input) {
input = input.replace(/=+$/, '')
if (input.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = input.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
});
}());
|
var express = require('express');
var router = express.Router();
var util = require('util');
var constants = require('../util/constants');
var utils = require('../util/utils')
var string = function(coverage) {
router.put('/:scenario', function(req, res, next) {
if (req.params.scenario === 'null') {
if (req.body !== null) {
utils.send400(res, next, "Did not like null req '" + util.inspect(req) + "'");
} else {
coverage['putStringNull']++;
res.status(200).end();
}
} else if (req.params.scenario === 'empty') {
if (req.body !== '') {
utils.send400(res, next, "Did not like empty req '" + util.inspect(req.body) + "'");
} else {
coverage['putStringEmpty']++;
res.status(200).end();
}
} else if (req.params.scenario === 'mbcs') {
if (req.body !== constants.MULTIBYTE_BUFFER_BODY) {
utils.send400(res, next, "Did not like mbcs req '" + util.inspect(req.body) + "'");
} else {
coverage['putStringMultiByteCharacters']++;
res.status(200).end();
}
} else if (req.params.scenario === 'whitespace') {
if (req.body !== ' Now is the time for all good men to come to the aid of their country ') {
utils.send400(res, next, "Did not like whitespace req '" + util.inspect(req.body) + "'");
} else {
coverage['putStringWithLeadingAndTrailingWhitespace']++;
res.status(200).end();
}
} else {
utils.send400(res, next, 'Request path must contain true or false');
}
});
router.get('/:scenario', function(req, res, next) {
if (req.params.scenario === 'null') {
coverage['getStringNull']++;
res.status(200).end();
} else if (req.params.scenario === 'notProvided') {
coverage['getStringNotProvided']++;
res.status(200).end();
} else if (req.params.scenario === 'empty') {
coverage['getStringEmpty']++;
res.status(200).end('\"\"');
} else if (req.params.scenario === 'mbcs') {
coverage['getStringMultiByteCharacters']++;
res.status(200).end('"' + constants.MULTIBYTE_BUFFER_BODY + '"');
} else if (req.params.scenario === 'whitespace') {
coverage['getStringWithLeadingAndTrailingWhitespace']++;
res.status(200).end('\" Now is the time for all good men to come to the aid of their country \"');
} else {
res.status(400).end('Request path must contain null or empty or mbcs or whitespace');
}
});
router.get('/enum/notExpandable', function (req, res, next) {
coverage['getEnumNotExpandable']++;
res.status(200).end('"red color"');
});
router.put('/enum/notExpandable', function (req, res, next) {
if (req.body === 'red color') {
coverage['putEnumNotExpandable']++;
res.status(200).end();
} else {
utils.send400(res, next, "Did not like enum in the req '" + util.inspect(req.body) + "'");
}
});
}
string.prototype.router = router;
module.exports = string; |
"use strict";
var app = {
initialize: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function () {
app.receivedEvent('deviceready');
if (!window.device) {
window.device = {
platform: 'Browser'
};
}
},
receivedEvent: function (id) {
console.log('Received Event: ' + id);
},
goHome: function () {
var topic = '';
var defaultAudioItem = 0;
showLoadingSpinner(true);
Data.ChooseTopic(topic, renderMediaListView);
setActiveListItem(defaultAudioItem);
setTimeout(function () { showLoadingSpinner(false); }, 500);
},
showMore: function () {
showNavPanel();
},
};
$(document).ready(function () {
app.initialize();
setActiveListItem(0);
$('.navlink').click(function (e) {
$('.navlink').each(function (i) {
$(this).css('color', 'black');
});
$(this).css('color', 'red');
var topic = $(this).attr('data');
Data.ChooseTopic(topic, renderMediaListView);
setTimeout(function () { hideNavPanel() }, 2000);
});
setHoverEffectOnListItems();
$('.navlink').first().trigger('click');
});
function setActiveListItem(index) {
$('.navlink').each(function (i) {
$(this).css('color', i === index ? 'red' : 'black');
});
}
var renderMediaListView = function (topic, data, isRefreshing) {
imageSlider.hide();
var isHomePage = topic == '';
var items = data.Items;
if (isRefreshing && isHomePage) {
imageSlider.slick();
}
var imageCounter = 0;
var output = '';
$.each(items, function (i, data) {
output += '<li data-icon="audio"><a href="#" id="' + data.id + '" onClick=playAudio(' + data.id + ')>' + data.title;
if (data.detail != null && data.detail.length > 0) {
output += '<span class="small">' + data.detail + '</span></li>';
}
output += '</a></li>';
if (data.imageUrl != null && data.imageUrl.length > 0 && isHomePage) {
imageCounter++;
if (isRefreshing) {
imageSlider.add(data.imageUrl, data.id);
}
}
});
if (imageCounter > 0) {
imageSlider.goTo(0);
imageSlider.show();
}
$('#listitems').html(output);
$('#listitems').listview('refresh');
}
var playAudio = function (id) {
var wasVisible = $('#player').is(':hidden');
Audio.Play(id);
if (wasVisible) {
$('#listitems').listview('refresh');
}
}
function showLoadingSpinner(show) {
$.mobile.loading(show ? "show" : "hide");
}
function showNavPanel() {
$("#navPanel").panel("open");
}
function hideNavPanel() {
$("#navPanel").panel("close");
}
function setHoverEffectOnListItems() {
// style the list item when it is clicked!
$('#listitems').on('mousedown touchstart', 'li', function () {
$(this).addClass('activeLI');
});
$('#listitems').on('mouseup touchend', 'li', function () {
$(this).removeClass('activeLI');
});
$('#listitems').on('mouseleave touchend', 'li', function () {
$(this).removeClass('activeLI');
});
}
function openLink(url) {
if (typeof device != 'undefined' &&
device.platform.toUpperCase() === 'ANDROID') {
navigator.app.loadUrl(url, {
openExternal: true
});
e.preventDefault();
} else if (typeof device != 'undefined' &&
device.platform.toUpperCase() === 'IOS') {
window.open(url, '_system');
e.preventDefault();
} else {
window.location.href = url;
window.location.replace(url);
}
}
var imageSlider = {
slick: function () {
var slick = $('.images_slider');
slick.unslick();
slick.html('');
slick.slick({
infinite: true,
autoplay: true,
autoplaySpeed: 20000,
dots: true,
slidesToShow: 1,
slidesToScroll: 1,
});
},
show: function () {
var slick = $('.images_slider');
slick.show();
},
hide: function () {
var slick = $('.images_slider');
slick.hide();
},
goTo: function (id) {
var slick = $('.images_slider');
slick.slickGoTo(id);
},
add: function (url, audioIndex) {
var w = Math.min($(document).width(), 500);
var h = (w * 200 / 300);
$('.images_slider').slickAdd('<div><a onClick=playAudio(' + audioIndex + ')><img src="' + url + '?w=' + w + '&h=' + h + '"/></a></div>');
}
}; |
/**
* @fileOverview Encapsulates data and logic for 2d points.
* @author <a href="http://benjaminbojko.com">Benjamin Bojko</a>
* Copyright (c) 2015 Big Spaceship; Licensed MIT
*/
'use strict';
/**
* @constructor
* @param {number=} x
* @param {number=} y
*/
shinejs.Point = function(x, y) {
/** @type {number} */
this.x = x || 0;
/** @type {number} */
this.y = y || 0;
};
/**
* A point representing the x and y distance to a point <code>p</code>
* @param {shinejs.Point} p
* @return {shinejs.Point} A new instance of shinejs.Point
*/
shinejs.Point.prototype.delta = function(p) {
return new shinejs.Point(p.x - this.x, p.y - this.y);
};
|
//目次
//ブラウザ判定、body,formのid,class付与
//ConfigManagerからid取得
//ID付与(IDがない場合)(nameが被った場合、単にiを付与する方が処理が軽い)
//事前コンバート
//ConfigManagerからclass取得
//ConfigManagerからvalidation取得
//new
//action
// window.onunload = function(){}
// if(window.name != "xyz"){
// location.reload();
// window.name = "xyz";
// }
jQuery.noConflict();
jQuery('html').hide();
jQuery(document).ready(function($){
jQuery('html').show();
//ブラウザ判定、body,formのid,class付与―――――――――――――――――――――――――――――――――――
var userAgent = window.navigator.userAgent.toLowerCase();
/*new*/ var appVersion = window.navigator.appVersion.toLowerCase();
if (userAgent.indexOf("msie") != -1) {
if (appVersion.indexOf("msie 10.") != -1) {
$('html').addClass('elseBL ie10');
} else if (appVersion.indexOf("msie 9.") != -1) {
$('html').addClass('ie');
// $('html').addClass('ie9');
// $('html').addClass('ie ie9');
} else if (appVersion.indexOf("msie 8.") != -1) {
$('html').addClass('ie');
} else if (appVersion.indexOf("msie 11.") != -1) {
$('html').addClass('elseBL ie10');
} else {
return false;
}
} else {
$('html').addClass('elseBL');
}
var tokenVal = $('form').find('input[type="hidden"][name="token"]').val() !== undefined ? $('form').find('input[type="hidden"][name="token"]').val() : 'complete';
$('body').addClass('pc');
if($('body').attr('id') === undefined){//css point用
$('body').attr('id','bodyID')
}
if($('form').attr('id') === undefined){//css point用
$('form').attr('id','formID')
}
//―――――――――――――――――――――――――――――――――――
//ConfigManagerからid取得―――――――――――――――――――――――――――――――――――
var ConfigManager = new MYNAMESPACE.model.ConfigManagerYokohama();
var arrid = ConfigManager.getIdname();
for (var i=0,len=arrid.length; i<len; i++) {
arrid[i]['Selecter'].attr('id',arrid[i]['id']);
}
//ID付与(nameが被った場合、単にiを付与する方が処理が軽い)
$('input,select').not('input[type="radio"],input[name="col_34"],select[name="col_33"],select[name="col_41"],select[name="col_42"]').each(function(i) {//ok
if($(this).attr('id') === undefined){
if($(this).attr('name') !== undefined){//nameと同名をつける
/*有楽仕様*/ var thisname = $(this).attr('name').replace('[]','')
var sameIDlength = $('input[id='+thisname+'],select[id='+thisname+']').length
if(sameIDlength === 0){
$(this).attr('id', thisname);
} else {
for (var j=0,len=5; j<len; j++) {
sameIDlength = $('input[id='+thisname+'_'+(j+2)+'],select[id='+thisname+'_'+(j+2)+']').length
if(sameIDlength === 0){
$(this).attr('id', thisname+'_'+(j+2));
break;
}
}
}
} else {//nameを持っていない場合、id=AddID+i
$(this).attr('id', 'AddID'+i);
}
}
})
//事前コンバート―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
//backgroundColorを削除―――――――――――――――――――――――――――――――――――
// $('#RadioID_3').remove()
$('#RadioID_3>td').attr('bgcolor','')
//Radio,Checkをlabelで囲む。―――――――――――――――――――――――――――――――――――
//追加 入会のリンクを有効化―――――――――――――――――――――――――
var wellithTd = $('#wellith').closest('td')
wellithTd.closest('tr').attr('id','wellithTr')
wellithTd.html($('<label>').addClass('labelClass').append(wellithTd.clone().html()))
var wellithTdClone = wellithTd.clone()
wellithTd.remove()
//追加 入会のリンクを有効化―――――――――――――――――――――――――
var colHPOTHER = $('#col_HP_OTHER').clone()
var formtable = $('form>table>tbody>tr>td>table')
var tempradioNode = $('<div>')
$('input[name="col_18"]').each(function(i){
var gendertxt = $('<span>').html($(this).val() + ' ');
var genderlabelNode = $('<label>').addClass('labelClass').append($(this).clone()).append(gendertxt)
tempradioNode.append(genderlabelNode)
})
$('input[name="col_18"]').eq(0).closest('td').html('').addClass('labeltd').append(tempradioNode.html())
$('input[type="radio"],input[type="checkbox"]').not('input[name="col_18"]').each(function(i){
var radiotd = $(this).closest('td')
var radiotxt = $('<span>').html(radiotd.text())
var radiolabelNode = $('<label>').addClass('labelClass').append($(this).clone()).append(radiotxt)
radiotd.html(radiolabelNode)
})
$('input[type="radio"]').not('input[name="col_18"]').closest('table').closest('td').addClass('labeltd')
$('input[name="col_HP"]:last').closest('label').after(colHPOTHER)
//同意文
// var doibuncheck = formtable.eq(6).find('>tbody>tr:eq(1)>td').add(formtable.eq(7).find('>tbody>tr:eq(0)>td:eq(1)')).add(formtable.eq(7).find('>tbody>tr:eq(1)>td')).add(formtable.eq(7).find('>tbody>tr:eq(2)>td:eq(1)'))
// doibuncheck.addClass('labeltd')
//追加 入会のリンクを有効化―――――――――――――――――――――――――
$('#wellithTr').append(wellithTdClone)
$('#wellithTr').closest('td').addClass('labeltd')
//追加 入会のリンクを有効化―――――――――――――――――――――――――
//フォーム依存――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
//submit
$('#task').closest('td').find('a').attr('onclick','')
// $j('input[name="task"]').closest('td').click(function(){
// $j('form').submit();
// })
//――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
//a移動無効――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
$('a[href=#]').click(function(e){//#に""はいらないのかどうか
e.preventDefault();
})
//―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
//デフォルト記入例の削除―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
$('#AutoAddressText2').closest('td').html($('#AutoAddressText2').closest('td').find('input'))
$('#AutoAddressText3').closest('td').html($('#AutoAddressText3').closest('td').find('input'))
$('#col_23').closest('td').html($('#col_23').closest('td').find('input'))
$('#col_24').closest('td').html($('#col_24').closest('td').find('input'))
//事前コンバートここまで―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
//ConfigManagerからclass取得―――――――――――――――――――――――――――――――――――
$(ConfigManager).on('onSetClassname', function(event) {
var arr = ConfigManager.getClassname();
for (var i=0,len=arr.length; i<len; i++) {
arr[i]['Selecter'].addClass(arr[i]['classname']);
}
})
ConfigManager.SetClassname();
//ConfigManagerからリアルタイムで取得。―――――――――――――――――――――――――
// ConfigManager.SetClassname();
// $(ConfigManager).on('onSetIdname', function(event) {
// })
// ConfigManager.SetIdname();
//―――――――――――――――――――――――――――――――――――
/*――――――――――――――――――――――――――*/
/* AddID&Name from Class */
/*――――――――――――――――――――――――――*/
//住所自動入力は任意のidが必須(なかったら自動付与、というようにしてもよい)
// var arrname = [
// {'Selecter' : $('input[name="col_4"]') ,'name': 'kanaEx_firstName'}
// ,{'Selecter' : $('input[name="col_5"]') ,'name': 'kanaEx_lastName'}
// ,{'Selecter' : $('input[name="col_14"]') ,'name': 'kanaEx_firstNameKatakana'}
// // ,{'Selecter' : $('input[name="col_14"]') ,'name': 'kanaEx_firstNameHiragana'}
// ,{'Selecter' : $('input[name="col_15"]') ,'name': 'kanaEx_lastNameKatakana'}
// // ,{'Selecter' : $('input[name="col_15"]') ,'name': 'kanaEx_lastNameHiragana'}
// ]
// for (var i=0,len=arrname.length; i<len; i++) {
// arrname[i]['Selecter'].attr('name',arrname[i]['name']);
// }
//validation
var ExValidationObj = ConfigManager.getValidation();
//new――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
//initialvalidateじゃない? // var InitialBlankManager = new MYNAMESPACE.view.InitialBlankManager($j);
var FocusEventManager = new MYNAMESPACE.view.FocusEventManager();
var AutoEmManager = new MYNAMESPACE.view.AutoEmManager();
// var AutoKanaManager = new MYNAMESPACE.view.AutoKanaManager();⇒プラグインで実装
// var TextNumberManager = new MYNAMESPACE.view.TextNumberManager($j);
var RemainingItemsManager = new MYNAMESPACE.view.RemainingItemsManager();
var RealtimeCheckManager = new MYNAMESPACE.view.RealtimeCheckManager(ExValidationObj);
var SubmitCheckManager = new MYNAMESPACE.view.SubmitCheckManager();
var PlaceholderManager = new MYNAMESPACE.view.PlaceholderManager();
// if($('html').hasClass('ie') === true){
// var PlaceholderManagerForIE = new MYNAMESPACE.view.PlaceholderManagerForIE();
// }
/*new*/ if(($('html').hasClass('ie') === true)||($('html').hasClass('ie9') === true)){
// /*new*/ if(($('html').hasClass('ie') === true)||($('html').hasClass('ie9') === true)||($('html').hasClass('ie10') === true)){
var AutoAddressManager = new MYNAMESPACE.view.AutoAddressManagerForIE();
} else {
var AutoAddressManager = new MYNAMESPACE.view.AutoAddressManager();
}
var TimerSolutionManager = new MYNAMESPACE.view.TimerSolutionManager();
var MouseEventManager = new MYNAMESPACE.view.MouseEventManager();
var Mediator = new MYNAMESPACE.view.Mediator(RemainingItemsManager,RealtimeCheckManager,TimerSolutionManager);
//ConfigManagerからSubmit時のエラーコメント取得―――――――――――――――――――――――――――――――――――
$(ConfigManager).on('onSetSubmitComment', function(event) {
var SubmitCommentObj = ConfigManager.getSubmitComment();
SubmitCheckManager.getSubmitComment(SubmitCommentObj)
})
ConfigManager.setSubmitComment();
//action――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
Mediator .setEvent()
// InitialBlankManager .initialBlank()
FocusEventManager .focusEvent()
AutoEmManager .autoEm()
// AutoKanaManager .autoKana()⇒プラグインで実装
// TextNumberManager .textNumber()
RealtimeCheckManager.realtimeCheck()
PlaceholderManager .placeholder()
/*new*/ if(($('html').hasClass('ie') === true)||($('html').hasClass('ie9') === true)){
PlaceholderManager .placeholderForIE()
}
SubmitCheckManager.submitCheck()
AutoAddressManager .autoAddress()
TimerSolutionManager .timerSolutionKanaAndPlaceholder()
TimerSolutionManager .timerSolutionAddressAndPlaceholder()
RemainingItemsManager .insertdiv()
RemainingItemsManager .setEvent()
MouseEventManager .mouseEvent()
if($jk('html').hasClass('ie') === true) {
$jk('#float').exFixed();
}
}); |
/**
* The Route class is for defining a route
*
* @class Route
* @constructor
* @module Router
* @author Emilio Mariscal (emi420 [at] gmail.com)
* @author Martin Szyszlican (martinsz [at] gmail.com)
*/
(function ($, Mootor) {
"use strict";
var Route;
// Private constructors
Route = Mootor.Route = function(regex, view) {
this.regex = regex;
this.view = view;
};
// Private static methods and properties
$.extend(Route, {
// code here
});
// Public methods
$.extend(Route.prototype, {
/**
* The URL regex referenced by this route
*
* @property regex
* @type String
* @example
* url_regex = m.app.route("index.html").regex;
*/
regex: "",
/**
* The view that implements this route
* If called with no parameters, it returns the currently set view in this route.
*
* @method view
* @param {View} [view] - The view that implements this route
* @return view
* @example
* url_view = m.app.route("index.html").view;
*/
view: {}
});
}(window.$, window.Mootor));
|
//////////////////////////////////////////////////////////////////////////
// //
// This is a generated file. You can view the original //
// source in your browser if your browser supports source maps. //
// Source maps are supported by all recent versions of Chrome, Safari, //
// and Firefox, and by Internet Explorer 11. //
// //
//////////////////////////////////////////////////////////////////////////
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var _ = Package.underscore._;
var Tracker = Package.tracker.Tracker;
var Deps = Package.tracker.Deps;
var ReactiveDict = Package['reactive-dict'].ReactiveDict;
var Template = Package.templating.Template;
var Iron = Package['iron:core'].Iron;
var Blaze = Package.blaze.Blaze;
var UI = Package.blaze.UI;
var Handlebars = Package.blaze.Handlebars;
var Spacebars = Package.spacebars.Spacebars;
var HTML = Package.htmljs.HTML;
/* Package-scope variables */
var WaitList, Controller;
(function(){
/////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/iron_controller/lib/wait_list.js //
// //
/////////////////////////////////////////////////////////////////////////////////////////////
//
/*****************************************************************************/ // 1
/* Imports */ // 2
/*****************************************************************************/ // 3
var assert = Iron.utils.assert; // 4
// 5
/*****************************************************************************/ // 6
/* Private */ // 7
/*****************************************************************************/ // 8
// 9
/** // 10
* Returns an object of computation ids starting with // 11
* the current computation and including all ancestor // 12
* computations. The data structure is an object // 13
* so we can index by id and do quick checks. // 14
*/ // 15
var parentComputations = function () { // 16
var list = {}; // 17
var c = Deps.currentComputation; // 18
// 19
while (c) { // 20
list[String(c._id)] = true; // 21
c = c._parent; // 22
} // 23
// 24
return list; // 25
}; // 26
// 27
/** // 28
* Check whether the user has called ready() and then called wait(). This // 29
* can cause a condition that can be simplified to this: // 30
* // 31
* dep = new Deps.Dependency; // 32
* // 33
* Deps.autorun(function () { // 34
* dep.depend(); // 35
* dep.changed(); // 36
* }); // 37
*/ // 38
var assertNoInvalidationLoop = function (dependency) { // 39
var parentComps = parentComputations(); // 40
var depCompIds = _.keys(dependency._dependentsById); // 41
// 42
_.each(depCompIds, function (id) { // 43
assert(!parentComps[id], "\n\n\
You called wait() after calling ready() inside the same computation tree.\
\n\n\
You can fix this problem in two possible ways:\n\n\
1) Put all of your wait() calls before any ready() calls.\n\
2) Put your ready() call in its own computation with Deps.autorun." // 49
); // 50
}); // 51
}; // 52
// 53
// 54
/*****************************************************************************/ // 55
/* WaitList */ // 56
/*****************************************************************************/ // 57
/** // 58
* A WaitList tracks a list of reactive functions, each in its own computation. // 59
* The list is ready() when all of the functions return true. This list is not // 60
* ready (i.e. this.ready() === false) if at least one function returns false. // 61
* // 62
* You add functions by calling the wait(fn) method. Each function is run its // 63
* own computation. The ready() method is a reactive method but only calls the // 64
* deps changed function if the overall state of the list changes from true to // 65
* false or from false to true. // 66
*/ // 67
WaitList = function () { // 68
this._readyDep = new Deps.Dependency; // 69
this._comps = []; // 70
this._notReadyCount = 0; // 71
}; // 72
// 73
/** // 74
* Pass a function that returns true or false. // 75
*/ // 76
WaitList.prototype.wait = function (fn) { // 77
var self = this; // 78
// 79
var activeComp = Deps.currentComputation; // 80
// 81
assertNoInvalidationLoop(self._readyDep); // 82
// 83
// break with parent computation and grab the new comp // 84
Deps.nonreactive(function () { // 85
// 86
// store the cached result so we can see if it's different from one run to // 87
// the next. // 88
var cachedResult = null; // 89
// 90
// create a computation for this handle // 91
var comp = Deps.autorun(function (c) { // 92
// let's get the new result coerced into a true or false value. // 93
var result = !!fn(); // 94
// 95
var oldNotReadyCount = self._notReadyCount; // 96
// 97
// if it's the first run and we're false then inc // 98
if (c.firstRun && !result) // 99
self._notReadyCount++; // 100
else if (cachedResult !== null && result !== cachedResult && result === true) // 101
self._notReadyCount--; // 102
else if (cachedResult !== null && result !== cachedResult && result === false) // 103
self._notReadyCount++; // 104
// 105
cachedResult = result; // 106
// 107
if (oldNotReadyCount === 0 && self._notReadyCount > 0) // 108
self._readyDep.changed(); // 109
else if (oldNotReadyCount > 0 && self._notReadyCount === 0) // 110
self._readyDep.changed(); // 111
}); // 112
// 113
self._comps.push(comp); // 114
// 115
if (activeComp) { // 116
activeComp.onInvalidate(function () { // 117
// keep the old computation and notReadyCount the same for one // 118
// flush cycle so that we don't end up in an intermediate state // 119
// where list.ready() is not correct. // 120
// 121
// keep the state the same until the flush cycle is complete // 122
Deps.afterFlush(function () { // 123
// stop the computation // 124
comp.stop(); // 125
// 126
// remove the computation from the list // 127
self._comps.splice(_.indexOf(self._comps, comp), 1); // 128
// 129
if (cachedResult === false) { // 130
self._notReadyCount--; // 131
// 132
if (self._notReadyCount === 0) // 133
self._readyDep.changed(); // 134
} // 135
}); // 136
}); // 137
} // 138
}); // 139
}; // 140
// 141
WaitList.prototype.ready = function () { // 142
this._readyDep.depend(); // 143
return this._notReadyCount === 0; // 144
}; // 145
// 146
WaitList.prototype.stop = function () { // 147
_.each(this._comps, function (c) { c.stop(); }); // 148
this._comps = []; // 149
}; // 150
// 151
Iron.WaitList = WaitList; // 152
// 153
/////////////////////////////////////////////////////////////////////////////////////////////
}).call(this);
(function(){
/////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/iron_controller/lib/controller.js //
// //
/////////////////////////////////////////////////////////////////////////////////////////////
//
/*****************************************************************************/ // 1
/* Imports */ // 2
/*****************************************************************************/ // 3
var debug = Iron.utils.debug('iron:controller'); // 4
var Layout = Iron.Layout; // 5
var DynamicTemplate = Iron.DynamicTemplate; // 6
// 7
/*****************************************************************************/ // 8
/* Private */ // 9
/*****************************************************************************/ // 10
var bindData = function (value, thisArg) { // 11
return function () { // 12
return (typeof value === 'function') ? value.apply(thisArg, arguments) : value; // 13
}; // 14
}; // 15
// 16
/*****************************************************************************/ // 17
/* Controller */ // 18
/*****************************************************************************/ // 19
Controller = function (options) { // 20
var self = this; // 21
this.options = options || {}; // 22
this._layout = this.options.layout || new Layout(this.options); // 23
this._isController = true; // 24
this._layout._setLookupHost(this); // 25
// 26
// grab the event map from the Controller constructor which was // 27
// set if the user does MyController.events({...}); // 28
var eventMap = Controller._collectEventMaps.call(this.constructor); // 29
this._layout.events(eventMap, this); // 30
// 31
this.init(options); // 32
}; // 33
// 34
/** // 35
* Set or get the layout's template and optionally its data context. // 36
*/ // 37
Controller.prototype.layout = function (template, options) { // 38
var self = this; // 39
// 40
this._layout.template(template); // 41
// 42
// check whether options has a data property // 43
if (options && (_.has(options, 'data'))) // 44
this._layout.data(bindData(options.data, this)); // 45
// 46
return { // 47
data: function (val) { // 48
return self._layout.data(bindData(val, self)); // 49
} // 50
}; // 51
}; // 52
// 53
/** // 54
* Render a template into a region of the layout. // 55
*/ // 56
Controller.prototype.render = function (template, options) { // 57
var self = this; // 58
// 59
if (options && (typeof options.data !== 'undefined')) // 60
options.data = bindData(options.data, this); // 61
// 62
var tmpl = this._layout.render(template, options); // 63
// 64
// allow caller to do: this.render('MyTemplate').data(function () {...}); // 65
return { // 66
data: function (func) { // 67
return tmpl.data(bindData(func, self)); // 68
} // 69
}; // 70
}; // 71
// 72
/** // 73
* Begin recording rendered regions. // 74
*/ // 75
Controller.prototype.beginRendering = function (onComplete) { // 76
return this._layout.beginRendering(onComplete); // 77
}; // 78
// 79
/*****************************************************************************/ // 80
/* Controller Static Methods */ // 81
/*****************************************************************************/ // 82
/** // 83
* Inherit from Controller. // 84
* // 85
* Note: The inheritance function in Meteor._inherits is broken. Static // 86
* properties on functions don't get copied. // 87
*/ // 88
Controller.extend = function (props) { // 89
return Iron.utils.extend(this, props); // 90
}; // 91
// 92
Controller.events = function (events) { // 93
this._eventMap = events; // 94
return this; // 95
}; // 96
// 97
/** // 98
* Returns a single event map merged from super to child. // 99
* Called from the constructor function like this: // 100
* // 101
* this.constructor._collectEventMaps() // 102
*/ // 103
// 104
var mergeStaticInheritedObjectProperty = function (ctor, prop) { // 105
var merge = {}; // 106
// 107
if (ctor.__super__) // 108
_.extend(merge, mergeStaticInheritedObjectProperty(ctor.__super__.constructor, prop));
// 110
return _.has(ctor, prop) ? _.extend(merge, ctor[prop]) : merge; // 111
}; // 112
// 113
Controller._collectEventMaps = function () { // 114
return mergeStaticInheritedObjectProperty(this, '_eventMap'); // 115
}; // 116
// 117
// NOTE: helpers are not inherited from one controller to another, for now. // 118
Controller._helpers = {}; // 119
Controller.helpers = function (helpers) { // 120
_.extend(this._helpers, helpers); // 121
return this; // 122
}; // 123
// 124
/*****************************************************************************/ // 125
/* Global Helpers */ // 126
/*****************************************************************************/ // 127
if (typeof Template !== 'undefined') { // 128
/** // 129
* Returns the nearest controller for a template instance. You can call this // 130
* function from inside a template helper. // 131
* // 132
* Example: // 133
* Template.MyPage.helpers({ // 134
* greeting: function () { // 135
* var controller = Iron.controller(); // 136
* return controller.state.get('greeting'); // 137
* } // 138
* }); // 139
*/ // 140
Iron.controller = function () { // 141
//XXX establishes a reactive dependency which causes helper to run // 142
return DynamicTemplate.findLookupHostWithProperty(Blaze.getView(), '_isController'); // 143
}; // 144
// 145
/** // 146
* Find a lookup host with a state key and return it reactively if we have // 147
* it. // 148
*/ // 149
Template.registerHelper('get', function (key) { // 150
var controller = Iron.controller(); // 151
if (controller && controller.state) // 152
return controller.state.get(key); // 153
}); // 154
} // 155
/*****************************************************************************/ // 156
/* Namespacing */ // 157
/*****************************************************************************/ // 158
Iron.Controller = Controller; // 159
// 160
/////////////////////////////////////////////////////////////////////////////////////////////
}).call(this);
(function(){
/////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/iron_controller/lib/controller_client.js //
// //
/////////////////////////////////////////////////////////////////////////////////////////////
//
/*****************************************************************************/ // 1
/* Imports */ // 2
/*****************************************************************************/ // 3
var Layout = Iron.Layout; // 4
var debug = Iron.utils.debug('iron:controller'); // 5
var defaultValue = Iron.utils.defaultValue; // 6
// 7
/*****************************************************************************/ // 8
/* Private */ // 9
/*****************************************************************************/ // 10
var bindData = function (value, thisArg) { // 11
return function () { // 12
return (typeof value === 'function') ? value.apply(thisArg, arguments) : value; // 13
}; // 14
}; // 15
// 16
/*****************************************************************************/ // 17
/* Controller Client */ // 18
/*****************************************************************************/ // 19
/** // 20
* Client specific init code. // 21
*/ // 22
Controller.prototype.init = function (options) { // 23
this._waitlist = new WaitList; // 24
this.state = new ReactiveDict; // 25
}; // 26
// 27
/** // 28
* Insert the controller's layout into the DOM. // 29
*/ // 30
Controller.prototype.insert = function (options) { // 31
return this._layout.insert.apply(this._layout, arguments); // 32
}; // 33
// 34
/** // 35
* Add an item to the waitlist. // 36
*/ // 37
Controller.prototype.wait = function (fn) { // 38
var self = this; // 39
// 40
if (!fn) // 41
// it's possible fn is just undefined but we'll just return instead // 42
// of throwing an error, to make it easier to call this function // 43
// with waitOn which might not return anything. // 44
return; // 45
// 46
if (_.isArray(fn)) { // 47
_.each(fn, function eachWait (fnOrHandle) { // 48
self.wait(fnOrHandle); // 49
}); // 50
} else if (fn.ready) { // 51
this._waitlist.wait(function () { return fn.ready(); }); // 52
} else { // 53
this._waitlist.wait(fn); // 54
} // 55
// 56
return this; // 57
}; // 58
// 59
/** // 60
* Returns true if all items in the waitlist are ready. // 61
*/ // 62
Controller.prototype.ready = function () { // 63
return this._waitlist.ready(); // 64
}; // 65
// 66
/** // 67
* Clean up the controller and stop the waitlist. // 68
*/ // 69
Controller.prototype.stop = function () { // 70
this._waitlist.stop(); // 71
}; // 72
// 73
/////////////////////////////////////////////////////////////////////////////////////////////
}).call(this);
/* Exports */
if (typeof Package === 'undefined') Package = {};
Package['iron:controller'] = {};
})();
|
let tagElements = document.querySelectorAll('.tag')
let tagField = document.querySelector('#tagField')
let tagsId = document.querySelector('#tagsId')
for(let t of tagElements){
t.addEventListener('click',function(){
console.log(this)
console.log(this.innerText)
tagField.value+= this.innerText+','
tagsId.value += this.getAttribute('id')+','
})
} |
"use strict";
var request = require("request");
var LuisRecognizer = (function () {
function LuisRecognizer(models) {
if (typeof models == 'string') {
this.models = { '*': models };
}
else {
this.models = (models || {});
}
}
LuisRecognizer.prototype.recognize = function (context, cb) {
var result = { score: 0.0, intent: null };
if (context && context.message && context.message.text) {
var utterance = context.message.text;
var locale = context.locale || '*';
var model = this.models.hasOwnProperty(locale) ? this.models[locale] : this.models['*'];
if (model) {
LuisRecognizer.recognize(utterance, model, function (err, intents, entities) {
if (!err) {
result.intents = intents;
result.entities = entities;
var top;
intents.forEach(function (intent) {
if (top) {
if (intent.score > top.score) {
top = intent;
}
}
else {
top = intent;
}
});
if (top) {
result.score = top.score;
result.intent = top.intent;
switch (top.intent.toLowerCase()) {
case 'builtin.intent.none':
case 'none':
result.score = 0.1;
break;
}
}
cb(null, result);
}
else {
cb(err, null);
}
});
}
else {
cb(new Error("LUIS model not found for locale '" + locale + "'."), null);
}
}
else {
cb(null, result);
}
};
LuisRecognizer.recognize = function (utterance, modelUrl, callback) {
try {
var uri = modelUrl.trim();
if (uri.lastIndexOf('&q=') != uri.length - 3) {
uri += '&q=';
}
uri += encodeURIComponent(utterance || '');
request.get(uri, function (err, res, body) {
var result;
try {
if (!err) {
result = JSON.parse(body);
result.intents = result.intents || [];
result.entities = result.entities || [];
if (result.topScoringIntent && result.intents.length == 0) {
result.intents.push(result.topScoringIntent);
}
if (result.intents.length == 1 && typeof result.intents[0].score !== 'number') {
result.intents[0].score = 1.0;
}
}
}
catch (e) {
err = e;
}
try {
if (!err) {
callback(null, result.intents, result.entities);
}
else {
var m = err.toString();
callback(err instanceof Error ? err : new Error(m));
}
}
catch (e) {
console.error(e.toString());
}
});
}
catch (err) {
callback(err instanceof Error ? err : new Error(err.toString()));
}
};
return LuisRecognizer;
}());
exports.LuisRecognizer = LuisRecognizer;
|
'use strict';
function groupDataTypes($, path) {
let firstLi;
$('nav a').each(function() {
/* eslint-disable no-invalid-this */
if ($(this).attr('href').startsWith('class/lib/data-types.js~')) {
const li = $(this).closest('li');
if (!firstLi) {
firstLi = li;
firstLi.prepend('<a data-ice="dirPath" class="nav-dir-path" href="variable/index.html#static-variable-DataTypes">datatypes</a>');
firstLi.appendTo(firstLi.parent());
} else {
firstLi.after(li);
}
}
});
if (path.endsWith('identifiers.html')) {
const rowsToDelete = [];
$('table.summary td a').each(function() {
if ($(this).attr('href').startsWith('class/lib/data-types.js~')) {
rowsToDelete.push($(this).closest('tr'));
}
});
for (const row of rowsToDelete) {
$(row).remove();
}
}
}
module.exports = function transform($, path) {
groupDataTypes($, path);
$('nav li[data-ice=doc]:first-child').css('margin-top', '15px');
}; |
var fs = require('fs');
var path = require('canonical-path');
var Package = require('dgeni').Package;
var basePackage = require('../api-builder/docs-package');
var targetPackage = require('../api-builder/target-package');
var cheatsheetPackage = require('../api-builder/cheatsheet-package');
var PROJECT_PATH = path.resolve(__dirname, "../..");
var PUBLIC_PATH = path.resolve(PROJECT_PATH, 'public');
var DOCS_PATH = path.resolve(PUBLIC_PATH, 'docs');
var ANGULAR_REPO_PATH = path.resolve(__dirname, '../../../angular-dart');
// The 'docs' folder is actually named 'doc' for angular2 Dart.
var ANGULAR2_DOCS_PATH = path.resolve(ANGULAR_REPO_PATH, 'doc');
var NG_IO_PKG_PATH = path.resolve(__dirname, "../api-builder/angular.io-package");
function requireNgIoPkg(_path) { return require(path.resolve(NG_IO_PKG_PATH, _path)); }
module.exports = new Package('dart-api-and-cheatsheet-builder', [basePackage, targetPackage, cheatsheetPackage])
// overrides base packageInfo and returns the one for the Angular repo.
.factory(require('./services/packageInfo'))
// Configure rendering
.config(function (templateFinder, renderDocsProcessor) {
templateFinder.templateFolders
.unshift(path.resolve(NG_IO_PKG_PATH, 'templates'));
// helpers are made available to the nunjucks templates
renderDocsProcessor.helpers.relativePath = function (from, to) {
return path.relative(from, to);
};
})
.config(function (parseTagsProcessor, getInjectables) {
const tagDefs = requireNgIoPkg('./tag-defs');
parseTagsProcessor.tagDefinitions =
parseTagsProcessor.tagDefinitions.concat(getInjectables(tagDefs));
})
.config(function (readFilesProcessor) {
// confirm that the angular repo is actually there.
if (!fs.existsSync(ANGULAR_REPO_PATH)) {
throw new Error('dart-api-and-cheatsheet-builder task requires the angular2 repo to be at ' + ANGULAR_REPO_PATH);
}
readFilesProcessor.basePath = DOCS_PATH;
readFilesProcessor.sourceFiles = [{
basePath: ANGULAR2_DOCS_PATH,
include: path.resolve(ANGULAR2_DOCS_PATH, 'cheatsheet/*.md')
}];
})
.config(function (convertPrivateClassesToInterfacesProcessor,
createOverviewDump,
extractDecoratedClassesProcessor,
extractJSDocCommentsProcessor,
extractTitleFromGuides,
generateNavigationDoc,
mergeDecoratorDocs,
readTypeScriptModules
) {
// Clear out unwanted processors
createOverviewDump.$enabled = false;
convertPrivateClassesToInterfacesProcessor.$enabled = false;
extractDecoratedClassesProcessor.$enabled = false;
extractJSDocCommentsProcessor.$enabled = false;
extractTitleFromGuides.$enabled = false;
generateNavigationDoc.$enabled = false;
mergeDecoratorDocs.$enabled = false;
readTypeScriptModules.$enabled = false;
})
.config(function (computePathsProcessor) {
computePathsProcessor.pathTemplates.push({
docTypes: ['cheatsheet-data'],
pathTemplate: '../guide/cheatsheet.json',
outputPathTemplate: '${path}'
});
})
.config(function (getLinkInfo) {
getLinkInfo.relativeLinks = true;
})
.config(function (templateEngine, getInjectables) {
templateEngine.filters = templateEngine.filters.concat(getInjectables([
requireNgIoPkg('./rendering/trimBlankLines'),
requireNgIoPkg('./rendering/toId'),
requireNgIoPkg('./rendering/indentForMarkdown')
]));
})
;
|
var paginationLg = document.getElementById("paginationLg");
var comp = new u.pagination({el:paginationLg,showState:false});
comp.update({totalPages: 100,pageSize:20,currentPage:1,totalCount:200});
var paginationDefault = document.getElementById("paginationDefault");
var comp = new u.pagination({el:paginationDefault,jumppage:true,showState:false});
comp.update({totalPages: 100,pageSize:20,currentPage:1,totalCount:200});
var paginationSm = document.getElementById("paginationSm");
var comp = new u.pagination({el:paginationSm,jumppage:true,showState:false});
comp.update({totalPages: 100,pageSize:20,currentPage:1,totalCount:200});
|
window.Utils = (function () {
var Utils = {};
var queue = [];
var running = false;
var pop = function () {
if (queue.length) {
setTimeout(function() {
window.location = encodeURI(queue.shift());
pop();
}, 0);
} else {
running = false;
}
};
Utils.redirect = function (url) {
queue.push(url);
if (!running) {
running = true;
pop();
}
};
Utils.log = function () {
Utils.redirect('log:' + [].join.call(arguments, ' '));
};
Utils.save = function (key, value) {
if (Array.isArray(key)) {
key = key.join('/');
}
value = JSON.stringify({
time: Date.now(),
data: value
});
Utils.redirect('osx:set(' + key + '%%' + value + ')');
};
var callbacks = {};
window.get = function (key, value, expiration) {
key = decodeURI(key);
value = decodeURI(value);
var item = value && JSON.parse(value);
var time = null;
if (expiration !== -1 && item && Date.now() - item.time > expiration) {
item = null;
} else if (item) {
time = item.time;
item = item.data;
}
var callback = callbacks[key];
callbacks[key] = null;
callback(item, time);
};
Utils.fetch = function (key, expiration, callback) {
if (Array.isArray(key)) {
key = key.join('/');
}
if (typeof expiration === 'function') {
callback = expiration;
expiration = undefined;
}
callbacks[key] = callback;
Utils.redirect('osx:get(' + key + '%%' + (expiration || -1) + ')');
};
var rawCallbacks = {};
window.raw = function (fnName) {
var args = [].slice.call(arguments, 1);
var callback = rawCallbacks[fnName];
rawCallbacks[fnName] = null;
callback.apply(null, args);
};
Utils.raw = function (expression, callback) {
if (callback) {
fnName = expression.split('(').shift();
rawCallbacks[fnName] = callback;
}
Utils.redirect('osx:' + expression);
};
Utils.clear = function (key) {
if (Array.isArray(key)) {
key = key.join('/');
}
Utils.redirect('osx:remove(' + key + ')');
};
Utils.openURL = function (url) {
Utils.redirect('osx:open_url(' + url + ')');
};
var contributionsCallbacks = {};
window.contributions = function (username) {
var fn = contributionsCallbacks[username];
if (fn) {
contributionsCallbacks[username] = null;
fn.apply(null, [].slice.call(arguments, 1));
}
};
Utils.contributions = function (username, callback, skipUpdateIcon) {
contributionsCallbacks[username] = callback;
Utils.redirect('osx:contributions(' + username + (skipUpdateIcon?'%%false':'') + ')');
};
Utils.quit = function () {
this.raw('quit()');
};
return Utils;
})();
|
#!/usr/bin/env node
'use strict';
const chalk = require('chalk');
const {join} = require('path');
const semver = require('semver');
const {execRead, execUnlessDry, logPromise} = require('../utils');
const {projects} = require('../config');
const push = async ({cwd, dry, version}) => {
const errors = [];
const tag = semver.prerelease(version) ? 'next' : 'latest';
const publishProject = async project => {
try {
const path = join(cwd, 'build', 'packages', project);
await execUnlessDry(`npm publish --tag ${tag}`, {cwd: path, dry});
if (!dry) {
const status = JSON.parse(
await execRead(`npm info ${project} dist-tags --json`)
);
const remoteVersion = status[tag];
if (remoteVersion !== version) {
throw Error(
chalk`Publised version {yellow.bold ${version}} for ` +
`{bold ${project}} but NPM shows {yellow.bold ${remoteVersion}}`
);
}
}
} catch (error) {
errors.push(error.message);
}
};
await Promise.all(projects.map(publishProject));
if (errors.length > 0) {
throw Error(
chalk`
Failure publishing to NPM
{white ${errors.join('\n')}}`
);
}
};
module.exports = async params => {
return logPromise(push(params), 'Pushing to git remote');
};
|
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | Identity manager');
test('custom identity managers work', function(assert) {
let book = server.create('book');
assert.equal(book.id, 'a');
});
|
/*********************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2018 NAN contributors
*
* MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md>
********************************************************************/
const test = require('tap').test
, testRoot = require('path').resolve(__dirname, '..')
, bindings = require('bindings')({ module_root: testRoot, bindings: 'parse' });
test('parse', function (t) {
t.plan(8);
t.type(bindings.parse, 'function');
t.deepEqual(
bindings.parse('{ "a": "JSON", "string": "value" }'),
JSON.parse('{ "a": "JSON", "string": "value" }')
);
t.deepEqual(
bindings.parse('[ 1, 2, 3 ]'),
JSON.parse('[ 1, 2, 3 ]')
);
t.equal(
bindings.parse('57'),
JSON.parse('57')
);
t.equal(
bindings.parse('3.14159'),
JSON.parse('3.14159')
);
t.equal(
bindings.parse('true'),
JSON.parse('true')
);
t.equal(
bindings.parse('false'),
JSON.parse('false')
);
t.equal(
bindings.parse('"some string"'),
JSON.parse('"some string"')
);
});
|
MyComponents.Rate = React.createClass({
render: function() {
var keyMap = {'BEG': 'Beginning', 'END': 'End', 'RATE': 'Rate', 'RQ': 'Type of Rate', 'RR': 'Other Info', 'DESC': 'Description', }
var vals = [];
for(var key in this.props.rate) {
vals.push(<span key={key}>{keyMap[key]}: {this.props.rate[key]}<br /></span>);
}
return (
<span className="card-content">
<br /> { vals }----------------------------------------------------------------------------------<br />
</span>
);
}
});
MyComponents.GarageRates = React.createClass({
render: function() {
var rates = this.props.rates.map(function(r,i){
return <MyComponents.Rate rate={r} key={i}/>
})
return (
<div className="row">
<div className="col s12 m9">
<div className="card">
<div className="card-image waves-effect waves-block waves-light">
<img className="activator" src="http://www.rentenbach.com/Uploads/Images/PhotoGalleries/VA%20Tech%20Parking%20Deck%204[1].JPG" height="500"></img>
</div>
<div className="card-content">
<span className="card-title activator grey-text text-darken-4">Garage Rate Info<i className="material-icons right">more_vert</i></span>
</div>
<div className="card-reveal">
<span className="card-title grey-text text-darken-4">Garage Rate Info:<i className="material-icons right">close</i></span>
{rates}
</div>
</div>
</div>
</div>
);
}
}); |
import Link from 'next/link'
export default function Person({ person }) {
return (
<li>
<Link href="/person/[id]" as={`/person/${person.id}`}>
<a>{person.name}</a>
</Link>
</li>
)
}
|
'use strict'
/**
* promiseOrCallback will convert a function that returns a promise
* into one that will either make a node-style callback or return a promise
* based on whether or not a callback is passed in.
*
* @example
* prompt('input? ').then(function (input) {
* // deal with input
* })
* var prompt2 = promiseOrCallback(prompt)
* prompt('input? ', function (err, input) {
* // deal with input
* })
*
* @param {Function} fn a promise returning function to wrap
* @returns {Function} a function that behaves like before unless called with a callback
*/
function promiseOrCallback (fn) {
return function () {
if (typeof arguments[arguments.length - 1] === 'function') {
let args = Array.prototype.slice.call(arguments)
let callback = args.pop()
fn.apply(null, args).then(function () {
let args = Array.prototype.slice.call(arguments)
args.unshift(null)
callback.apply(null, args)
}).catch(function (err) {
callback(err)
})
} else {
return fn.apply(null, arguments)
}
}
}
exports.promiseOrCallback = promiseOrCallback
|
"use strict";
const execa = require("execa");
const ipRegex = require("ip-regex");
const gwArgs = "path Win32_NetworkAdapterConfiguration where IPEnabled=true get DefaultIPGateway,Index /format:table".split(" ");
const ifArgs = "path Win32_NetworkAdapter get Index,NetConnectionID /format:table".split(" ");
const parse = (gwTable, ifTable, family) => {
let gateway, gwid, result;
(gwTable || "").trim().split("\n").splice(1).some(line => {
const results = line.trim().split(/} +/) || [];
const gw = results[0];
const id = results[1];
gateway = (ipRegex[family]().exec((gw || "").trim()) || [])[0];
if (gateway) {
gwid = id;
return true;
}
});
(ifTable || "").trim().split("\n").splice(1).some(line => {
const i = line.indexOf(" ");
const id = line.substr(0, i).trim();
const name = line.substr(i + 1).trim();
if (id === gwid) {
result = {gateway: gateway, interface: name ? name : null};
return true;
}
});
if (!result) {
throw new Error("Unable to determine default gateway");
}
return result;
};
const spawnOpts = {
windowsHide: true,
};
const promise = family => {
return Promise.all([
execa.stdout("wmic", gwArgs, spawnOpts),
execa.stdout("wmic", ifArgs, spawnOpts),
]).then(results => {
const gwTable = results[0];
const ifTable = results[1];
return parse(gwTable, ifTable, family);
});
};
const sync = family => {
const gwTable = execa.sync("wmic", gwArgs, spawnOpts).stdout;
const ifTable = execa.sync("wmic", ifArgs, spawnOpts).stdout;
return parse(gwTable, ifTable, family);
};
module.exports.v4 = () => promise("v4");
module.exports.v6 = () => promise("v6");
module.exports.v4.sync = () => sync("v4");
module.exports.v6.sync = () => sync("v6");
|
/**
* WindowManager.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* This class handles the creation of native windows and dialogs. This class can be extended to provide for example inline dialogs.
*
* @class tinymce.WindowManager
* @example
* // Opens a new dialog with the file.htm file and the size 320x240
* // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog.
* tinymce.activeEditor.windowManager.open({
* url: 'file.htm',
* width: 320,
* height: 240
* }, {
* custom_param: 1
* });
*
* // Displays an alert box using the active editors window manager instance
* tinymce.activeEditor.windowManager.alert('Hello world!');
*
* // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm
* });
*/
define(
'tinymce.core.api.WindowManager',
[
'ephox.katamari.api.Arr',
'ephox.katamari.api.Option',
'tinymce.core.selection.SelectionBookmark',
'tinymce.core.ui.WindowManagerImpl'
],
function (Arr, Option, SelectionBookmark, WindowManagerImpl) {
return function (editor) {
var windows = [];
var getImplementation = function () {
var theme = editor.theme;
return theme && theme.getWindowManagerImpl ? theme.getWindowManagerImpl() : WindowManagerImpl();
};
var funcBind = function (scope, f) {
return function () {
return f ? f.apply(scope, arguments) : undefined;
};
};
var fireOpenEvent = function (win) {
editor.fire('OpenWindow', {
win: win
});
};
var fireCloseEvent = function (win) {
editor.fire('CloseWindow', {
win: win
});
};
var addWindow = function (win) {
windows.push(win);
fireOpenEvent(win);
};
var closeWindow = function (win) {
Arr.findIndex(windows, function (otherWindow) {
return otherWindow === win;
}).each(function (index) {
// Mutate here since third party might have stored away the window array, consider breaking this api
windows.splice(index, 1);
fireCloseEvent(win);
// Move focus back to editor when the last window is closed
if (windows.length === 0) {
editor.focus();
}
});
};
var getTopWindow = function () {
return Option.from(windows[windows.length - 1]);
};
var open = function (args, params) {
editor.editorManager.setActive(editor);
SelectionBookmark.store(editor);
var win = getImplementation().open(args, params, closeWindow);
addWindow(win);
return win;
};
var alert = function (message, callback, scope) {
var win = getImplementation().alert(message, funcBind(scope ? scope : this, callback), closeWindow);
addWindow(win);
};
var confirm = function (message, callback, scope) {
var win = getImplementation().confirm(message, funcBind(scope ? scope : this, callback), closeWindow);
addWindow(win);
};
var close = function () {
getTopWindow().each(function (win) {
getImplementation().close(win);
closeWindow(win);
});
};
var getParams = function () {
return getTopWindow().map(getImplementation().getParams).getOr(null);
};
var setParams = function (params) {
getTopWindow().each(function (win) {
getImplementation().setParams(win, params);
});
};
var getWindows = function () {
return windows;
};
editor.on('remove', function () {
Arr.each(windows.slice(0), function (win) {
getImplementation().close(win);
});
});
return {
// Used by the legacy3x compat layer and possible third party
// TODO: Deprecate this, and possible switch to a immutable window array for getWindows
windows: windows,
/**
* Opens a new window.
*
* @method open
* @param {Object} args Optional name/value settings collection contains things like width/height/url etc.
* @param {Object} params Options like title, file, width, height etc.
* @option {String} title Window title.
* @option {String} file URL of the file to open in the window.
* @option {Number} width Width in pixels.
* @option {Number} height Height in pixels.
* @option {Boolean} autoScroll Specifies whether the popup window can have scrollbars if required (i.e. content
* larger than the popup size specified).
*/
open: open,
/**
* Creates a alert dialog. Please don't use the blocking behavior of this
* native version use the callback method instead then it can be extended.
*
* @method alert
* @param {String} message Text to display in the new alert dialog.
* @param {function} callback Callback function to be executed after the user has selected ok.
* @param {Object} scope Optional scope to execute the callback in.
* @example
* // Displays an alert box using the active editors window manager instance
* tinymce.activeEditor.windowManager.alert('Hello world!');
*/
alert: alert,
/**
* Creates a confirm dialog. Please don't use the blocking behavior of this
* native version use the callback method instead then it can be extended.
*
* @method confirm
* @param {String} message Text to display in the new confirm dialog.
* @param {function} callback Callback function to be executed after the user has selected ok or cancel.
* @param {Object} scope Optional scope to execute the callback in.
* @example
* // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm
* tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) {
* if (s)
* tinymce.activeEditor.windowManager.alert("Ok");
* else
* tinymce.activeEditor.windowManager.alert("Cancel");
* });
*/
confirm: confirm,
/**
* Closes the top most window.
*
* @method close
*/
close: close,
/**
* Returns the params of the last window open call. This can be used in iframe based
* dialog to get params passed from the tinymce plugin.
*
* @example
* var dialogArguments = top.tinymce.activeEditor.windowManager.getParams();
*
* @method getParams
* @return {Object} Name/value object with parameters passed from windowManager.open call.
*/
getParams: getParams,
/**
* Sets the params of the last opened window.
*
* @method setParams
* @param {Object} params Params object to set for the last opened window.
*/
setParams: setParams,
/**
* Returns the currently opened window objects.
*
* @method getWindows
* @return {Array} Array of the currently opened windows.
*/
getWindows: getWindows
};
};
}
);
|
import "./public-path";
it("should prefetch correctly", () => {
expect(document.head._children).toHaveLength(1);
// Test prefetch from entry chunk
const link = document.head._children[0];
expect(link._type).toBe("link");
expect(link.rel).toBe("prefetch");
expect(link.href).toBe("https://example.com/public/path/chunk1.js");
if (Math.random() < -1) {
import(/* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1");
}
});
|
$(window).on('load', function() {
//Initialize skrollr and save the instance.
var s = skrollr.init({
edgeStrategy: 'set',
constants: {
myconst: 300,
my500: 500
},
easing: {
half1: function() {
return 0.5
}
}
});
//Counts how many assertions will be needed for the tests.
var countAssertions = function(tests) {
var counter = 0;
for(var i = 0; i < tests.length; i++) {
var curTest = tests[i];
if(curTest.styles) {
for(var k in curTest.styles) {
counter += Object.prototype.hasOwnProperty.call(curTest.styles, k);
}
}
counter += !!curTest.selector;
}
return counter;
};
//A meta-test which runs common tests
//which need synchronization of scrolling and rendering.
var scrollTests = function(offset, tests) {
module('at scroll position ' + offset);
asyncTest('rendering', function() {
//We can't run them in parallel,
//because they would interfere with each others scroll top offset.
stop();
expect(countAssertions(tests));
//Scroll to offset, which will cause rendering (sooner or later)
s.setScrollTop(offset, true);
s.on('render', function(info) {
//Prevent another render event. Only need one for test.
s.off('render');
for(var i = 0; i < tests.length; i++) {
var curTest = tests[i];
if(curTest.styles) {
for(var k in curTest.styles) {
if(Object.prototype.hasOwnProperty.call(curTest.styles, k)) {
QUnit.numericCSSPropertyEquals(curTest.element.css(k), curTest.styles[k], curTest.message || 'element\'s (#' + curTest.element[0].id + ') "' + k + '" CSS property is correct');
}
}
}
if(curTest.selector) {
ok(curTest.element.is(curTest.selector), 'element matches "' + curTest.selector + '"');
}
}
start(2);
});
});
};
//
// Now the actual tests.
//
//Add one element dynamically
var newElement = $('<div id="dynamic" data-0="bottom:0px;" data-250="bottom:100px;">TEST</div>').appendTo('body');
s.refresh(newElement[0]);
module('basic stuff');
test('CSS classes present', function() {
strictEqual($('.skrollable').length, 19, 'All elements have the .skrollable class');
ok($('html').is('.skrollr'), 'HTML element has skrollr class');
ok($('html').is(':not(.no-skrollr)'), 'HTML element does not have no-skrollr class');
});
scrollTests(500, [
{
message: 'colons inside urls are preserved (#73)',
element: $('#colon-url'),
styles: {
backgroundImage: 'url(https://secure.travis-ci.org/Prinzhorn/skrollr.png)'
}
},
{
message: 'a single period is no number (#74)',
element: $('#period-number'),
styles: {
backgroundImage: 'url(https://secure.travis-ci.org/Prinzhorn/skrollr.png?1337)'
}
},
{
element: $('#simple-numeric'),
styles: {
left: '100px',
top: '50px'
}
},
{
element: $('#easing'),
styles: {
left: '25px'
}
},
{
element: $('#compound-numeric'),
styles: {
marginTop: '30px',
marginRight: '20px',
marginBottom: '10px',
marginLeft: '0px'
}
},
{
element: $('#rgb-color'),
styles: {
color: 'rgb(50, 100, 150)'
}
},
{
element: $('#rgba-color'),
styles: {
color: 'rgba(50, 100, 150, 0.5)'
}
},
{
element: $('#hsl-color'),
styles: {
color: 'rgb(191, 63, 63)'
}
},
{
element: $('#no-interpolation'),
styles: {
right: '100px'
}
},
{
element: $('#anchor-2'),
styles: {
right: '200px'
}
},
{
element: $('#foreign-anchor'),
styles: {
paddingTop: '100px',
paddingRight: '100px',
paddingBottom: '100px',
paddingLeft: '100px'
}
},
{
element: $('#float'),
styles: {
float: 'left'
}
}
]);
scrollTests(0, [
{
element: $('#simple-numeric'),
styles: {
left: '-100px',
top: '0px'
}
},
{
element: $('#easing'),
styles: {
left: '25px'
}
},
{
element: $('#compound-numeric'),
styles: {
marginTop: '0px',
marginRight: '10px',
marginBottom: '20px',
marginLeft: '30px'
}
},
{
element: $('#rgb-color'),
styles: {
color: 'rgb(0, 0, 0)'
}
},
{
element: $('#rgba-color'),
styles: {
color: 'rgba(0, 0, 0, 0.2)'
}
},
{
element: $('#hsl-color'),
styles: {
color: 'rgb(0, 0, 0)'
}
},
{
element: $('#no-interpolation'),
styles: {
right: '0px'
}
},
{
element: $('#end'),
styles: {
fontSize: '10px'
}
},
{
element: newElement,
styles: {
bottom: '0px'
}
},
{
element: $('#float'),
styles: {
float: 'none'
}
}
]);
scrollTests(250, [
{
element: $('#simple-numeric'),
styles: {
left: '0px',
top: '25px'
}
},
{
element: $('#easing'),
styles: {
left: '25px'
}
},
{
element: $('#compound-numeric'),
styles: {
marginTop: '15px',
marginRight: '15px',
marginBottom: '15px',
marginLeft: '15px'
}
},
{
element: $('#rgb-color'),
styles: {
color: 'rgb(25, 50, 75)'
}
},
{
element: $('#rgba-color'),
styles: {
color: 'rgba(25, 50, 75, 0.35)'
}
},
{
element: $('#hsl-color'),
styles: {
color: 'rgb(79, 47, 47)'
}
},
{
element: $('#no-interpolation'),
styles: {
right: '0px'
}
},
{
element: $('#anchor-2'),
styles: {
right: '100px'
}
},
{
element: newElement,
styles: {
bottom: '100px'
}
},
{
element: $('#foreign-anchor'),
styles: {
paddingTop: '150px',
paddingRight: '150px',
paddingBottom: '150px',
paddingLeft: '150px'
}
},
{
element: $('#float'),
styles: {
float: 'none'
}
}
]);
//We scroll to a ridiculous large position so that the browser cuts it at the actual position.
var maxScrollHeight = s.setScrollTop(1e5) && s.getScrollTop();
scrollTests(maxScrollHeight, [
{
element: $('#anchor-1'),
styles: {
right: '100px'
}
},
{
element: $('#easing'),
styles: {
left: '50px'
}
},
{
element: $('#easing_with_easing_strategy'),
styles: {
left: '25px'
}
},
{
element: $('#reset-strategy'),
styles: {
left: '1337px'
}
}
]);
});//DOM ready
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.