code stringlengths 2 1.05M |
|---|
/* eslint-env node */
'use strict';
module.exports = {
name: 'en-codemirror'
};
|
import {
attribute,
collection,
clickable,
create,
hasClass,
isVisible,
text,
} from 'ember-cli-page-object';
const definition = {
scope: '[data-test-school-session-types-list]',
sessionTypes: collection('[data-test-session-type]', {
title: {
scope: '[data-test-title]',
edit: clickable('button'),
},
sessionCount: text('[data-test-sessions-count]'),
isAssessment: hasClass('yes', '[data-test-is-assessment] svg'),
assessmentOption: text('[data-test-assessment-option]'),
aamcMethod: text('[data-test-assessment-method-description]'),
calendarColor: attribute('style', '[data-test-colorbox]'),
manage: clickable('[data-test-manage]'),
delete: clickable('[data-test-delete]'),
isDeletable: isVisible('[data-test-delete]'),
}),
};
export default definition;
export const component = create(definition);
|
module.exports = function(grunt) {
grunt.config('copy', {
// @begin: karma reports
karma_report_jasmine: {
files: [
{
expand: true,
flatten: true,
cwd: '<%= project.paths.reports %>/__jasmine',
src: [
'Phantom*/index.html'
],
dest: '<%= project.paths.reports %>/jasmine',
}
]
},
// @end: karma reports
//----------------------------------------------------------------------------
// @begin: dev build tasks
dev_jstobuild: {
files: [
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'**/*.js',
'!**/tests/**/*',
'!vendor/**/*',
'!require.unit.load.js'
],
dest: '<%= project.paths.build %>/'
}
]
},
dev_tobuild: {
files: [
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'**',
'!{,app/**/,shared/**/}*.js',
'!**/*.{less,css}',
'!vendor/**/*'
],
dest: '<%= project.paths.build %>/'
}
]
},
dev_vendortobuild: {
files: [
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'vendor/**/*',
'!vendor/**/*.{less,html}',
],
dest: '<%= project.paths.build %>/'
}
]
},
// @end: dev build tasks
// @begin: prod build tasks
prod_jstobuild: {
files: [
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'**/*.js',
'!**/tests/**/*',
'!require.config.js',
'!require.unit.load.js'
],
dest: '<%= project.paths.build %>/'
}
]
},
prod_todist: {
files: [
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'**',
'!{,app/**/,shared/**/}*.js',
'!**/*.{less,html}',
'!styles/**/*.*'
],
dest: '<%= project.paths.dist %>/'
},
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'shared/fallback/ie.js'
],
dest: '<%= project.paths.dist %>/'
},
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'require.config.js'
],
dest: '<%= project.paths.dist %>/'
},
{
expand: true,
cwd: '<%= project.paths.src %>/',
src: [
'index.html'
],
dest: '<%= project.paths.dist %>/'
}
]
}
// @end: prod build tasks
});
};
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var AvSurroundSound = React.createClass({
displayName: 'AvSurroundSound',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM7.76 16.24l-1.41 1.41C4.78 16.1 4 14.05 4 12c0-2.05.78-4.1 2.34-5.66l1.41 1.41C6.59 8.93 6 10.46 6 12s.59 3.07 1.76 4.24zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm5.66 1.66l-1.41-1.41C17.41 15.07 18 13.54 18 12s-.59-3.07-1.76-4.24l1.41-1.41C19.22 7.9 20 9.95 20 12c0 2.05-.78 4.1-2.34 5.66zM12 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z' })
);
}
});
module.exports = AvSurroundSound; |
angular
.module('openflix')
.directive('movieCollection', function() {
return {
restrict: 'E',
templateUrl: '/views/movie-collection',
scope: {
collection: '='
}
};
});
|
export const CHOICE_REGEX = 'CHOICE_REGEX';
export function choiceRegex(regex) {
return {
type: CHOICE_REGEX, regex,
};
}
|
module.exports={A:{A:{"2":"EB","8":"H D G","260":"E A B"},B:{"1":"C p x J L N I"},C:{"1":"0 1 2 3 4 5 6 8 9 Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y","2":"YB","132":"BB WB QB","260":"F K H D G E A B C p x J L N I O P"},D:{"1":"0 1 2 3 4 5 6 8 9 V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y KB aB FB a GB HB IB","132":"F K","260":"H D G E A B C p x J L N I O P Q R S T U"},E:{"1":"D G E A B C MB NB OB PB z RB","132":"F JB CB","260":"K H LB"},F:{"1":"0 J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w","132":"E B SB TB UB VB","260":"7 C z AB XB"},G:{"1":"G dB eB fB gB hB iB jB kB","132":"CB","260":"ZB DB bB cB"},H:{"132":"lB"},I:{"1":"a qB rB","132":"mB","260":"BB F nB oB pB DB"},J:{"260":"D A"},K:{"1":"M","132":"A","260":"7 B C z AB"},L:{"1":"a"},M:{"1":"y"},N:{"260":"A B"},O:{"1":"sB"},P:{"1":"F K tB"},Q:{"1":"uB"},R:{"1":"vB"}},B:1,C:"HTML5 semantic elements"};
|
(function (win) {
function forEach(m, callback) {
for (var key in m) {
callback(key, m[key]);
}
}
function buildUrl(url, items) {
var query = '';
forEach(items, function (name, value) {
if (name != 'token') {
query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value);
}
});
if (query) {
url += (url.indexOf('?') > 0 ? '&' : '?') + query;
}
return url;
}
function encode2UTF8(argString) {
if (argString === null || typeof argString === 'undefined') {
return '';
}
var string = (argString + ''); // .replace(/\r\n/g, '\n').replace(/\r/g, '\n');
var utftext = '',
start, end, stringl = 0;
start = end = 0;
stringl = string.length;
for (var n = 0; n < stringl; n++) {
var c1 = string.charCodeAt(n);
var enc = null;
if (c1 < 128) {
end++;
} else if (c1 > 127 && c1 < 2048) {
enc = String.fromCharCode(
(c1 >> 6) | 192, (c1 & 63) | 128
);
} else if (c1 & 0xF800 ^ 0xD800 > 0) {
enc = String.fromCharCode(
(c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
} else { // surrogate pairs
if (c1 & 0xFC00 ^ 0xD800 > 0) {
throw new RangeError('Unmatched trail surrogate at ' + n);
}
var c2 = string.charCodeAt(++n);
if (c2 & 0xFC00 ^ 0xDC00 > 0) {
throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
}
c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
enc = String.fromCharCode(
(c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
);
}
if (enc !== null) {
if (end > start) {
utftext += string.slice(start, end);
}
utftext += enc;
start = end = n + 1;
}
}
if (end > start) {
utftext += string.slice(start, stringl);
}
return utftext;
}
// Copy 七牛 SDK 方法
function encode2Base64(data) {
var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = '',
tmp_arr = [];
if (!data) {
return data;
}
data = encode2UTF8(data + '');
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
switch (data.length % 3) {
case 1:
enc = enc.slice(0, -2) + '==';
break;
case 2:
enc = enc.slice(0, -1) + '=';
break;
}
return enc;
}
// Copy 七牛 SDK 方法
function URLSafeBase64Encode(v) {
v = encode2Base64(v);
return v.replace(/\//g, '_').replace(/\+/g, '-');
}
function chunkLastStep(data, opts, callback) {
// 七牛 URL 规定
var key = '/key/' + URLSafeBase64Encode(data.filename);
var fname = '/fname/' + URLSafeBase64Encode(data.filename);
var url = opts.domain + '/mkfile/' + data.size + key + fname;
var options = {
domain: url,
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream'
},
multi_parmas: opts.multi_parmas,
support_options: true,
stream: true
};
uploadData(data.ctx, options, {
onCompleted: function (res) {
res.filename = data.filename;
res.name = data.name;
callback.onCompleted(res);
},
onError: function () {
throw new Error('qiniu uploadChunk error');
},
onProgress: function (chunkLoaded, total) { },
onOpen: function (xhr) {
callback.onOpen(xhr);
}
});
}
var offset = 0,
ctxStore = {};
function uploadNextChunk(blob, opts, callback) {
var chunk = Math.ceil(offset / opts.chunk_size),
chunks = Math.ceil(blob.size / opts.chunk_size),
curChunkSize = Math.min(opts.chunk_size, blob.size - offset),
chunkBlob = blob.slice(offset, offset + curChunkSize),
chunkInfo = {
chunk: chunk,
chunks: chunks,
name: blob.uniqueName
};
forEach(chunkInfo, function (key, value) {
opts.multi_parmas[key] = value;
});
opts.filesize = blob.size;
opts.headers = {
'Content-Type': 'application/octet-stream'
};
opts.isChunk = true;
uploadData(chunkBlob, opts, {
onCompleted: function (chunkRes) {
offset += curChunkSize;
// callback.onProgress(Math.floor((chunk + 1) / chunks * blob.size), blob.size);
ctxStore[blob.uniqueName] = ctxStore[blob.uniqueName] || [];
ctxStore[blob.uniqueName].push(chunkRes.ctx);
if (offset < blob.size) {
if (chunkRes.ctx) {
uploadNextChunk(blob, opts, callback);
} else {
offset = 0;
delete ctxStore[blob.uniqueName]
}
} else {
offset = 0;
delete opts.isChunk;
delete opts.headers['Content-Type'];
forEach(chunkInfo, function (key, value) {
delete opts.multi_parmas[key];
});
var ctx = ctxStore[blob.uniqueName].join(',');
var data = {
ctx: ctx,
name: blob.name,
size: blob.size,
filename: blob.uniqueName
};
chunkLastStep(data, opts, callback);
}
},
onError: function () {
throw new Error('qiniu uploadChunk error');
},
onProgress: function (chunkLoaded, total) {
var loaded = chunkLoaded + offset;
callback.onProgress(loaded, opts.filesize);
},
onOpen: function (xhr) {
callback.onOpen(xhr);
}
});
}
function uploadData(data, options, callback) {
var xhr = new XMLHttpRequest();
if (xhr.upload && options.support_options) {
xhr.upload.onprogress = function (event) {
callback.onProgress(event.loaded, event.total);
};
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var result = xhr.responseText || "{}";
result = JSON.parse(result);
result.filename = options.unique_value;
callback.onCompleted(result);
}
};
var url = options.domain;
if (options.isChunk) {
url += '/mkblk/' + data.size;
url = buildUrl(url, options.multi_parmas);
}
xhr.open(options.method, url, true);
callback.onOpen(xhr);
if (options.stream) {
xhr.setRequestHeader('authorization', 'UpToken ' + options.multi_parmas.token);
}
forEach(options.headers, function (key, value) {
xhr.setRequestHeader(key, value);
});
xhr.send(data);
}
function uploadQiniu(file, opts, callback) {
if (file.size && opts.chunk_size < file.size) {
var uniqueName = opts['genUId'](file);
var suffix = file.name.substr(file.name.lastIndexOf('.'));
uniqueName = uniqueName + suffix;
file.uniqueName = uniqueName;
opts.stream = true;
uploadNextChunk(file, opts, callback);
} else {
var data = opts['data'](file, opts);
uploadData(data, opts, callback);
}
}
win.uploadProcess = uploadQiniu;
})(window);
(function (win) {
var dataType = {
form: getFormData,
json: getJsonData,
data: getData
};
function genUId() {
var date = new Date().getTime();
var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (date + Math.random() * 16) % 16 | 0;
date = Math.floor(date / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
function mergeOption(opts) {
var options = {
domain: '',
method: 'POST',
file_data_name: 'file',
unique_key: 'key',
base64_size: 4 * 1024 * 1024,
chunk_size: 4 * 1024 * 1024,
headers: {},
multi_parmas: {},
query: {},
support_options: true,
data: dataType.form,
genUId: genUId
};
if (!opts || !opts.domain) {
throw new Error('domain is null');
}
for (var key in opts) {
options[key] = opts[key];
}
return options;
}
function mEach(m, callback) {
for (var key in m) {
callback(key, m[key]);
}
}
function getFormData(file, opts) {
var form = new FormData();
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
form.append(opts.unique_key, unique_value);
opts.unique_value = unique_value;
}
form.append(opts.file_data_name, file);
mEach(opts.multi_parmas, function (key, value) {
form.append(key, value);
});
return form;
}
function getJsonData(file, opts) {
var data = {};
if (opts.unique_key) {
var suffix = file.name.substr(file.name.lastIndexOf('.'));
var unique_value = genUId() + suffix;
data[opts.unique_key] = unique_value;
opts.unique_value = unique_value;
}
data[opts.file_data_name] = file;
mEach(opts.multi_parmas, function (key, value) {
data[key] = value;
});
return JSON.stringify(data);
}
function getData(file, opts) {
return file;
}
function Upload(options) {
this.options = mergeOption(options);
this.setOptions = function (opts) {
var me = this;
mEach(opts, function (key, value) {
me.options[key] = value;
});
};
this.upload = function (file, callback) {
if (!file) {
callback.onError('upload file is null.');
return;
}
var me = this;
uploadProcess(file, this.options, {
onProgress: function (loaded, total) {
callback.onProgress(loaded, total);
},
onCompleted: function (data) {
callback.onCompleted(data);
},
onError: function (errorCode) {
callback.onError(errorCode);
},
onOpen: function (xhr) {
me.xhr = xhr;
}
});
};
this.cancel = function () {
this.xhr && this.xhr.abort();
};
}
function init(options) {
return new Upload(options);
}
function getResizeRatio(imageInfo, config) {
//hasOwnProperty?
var ratio = 1;
var oWidth = imageInfo.width;
var maxWidth = config.maxWidth || 0;
if (maxWidth > 0 && oWidth > maxWidth) {
ratio = maxWidth / oWidth;
}
var oHeight = imageInfo.height;
var maxHeight = config.maxHeight || 0;
if (maxHeight > 0 && oHeight > maxHeight) {
var ratioHeight = maxHeight / oHeight;
ratio = Math.min(ratio, ratioHeight);
}
var maxSize = config.maxSize || 0;
var oSize = Math.ceil(imageInfo.size / 1000); //K,Math.ceil(0.3) = 1;
if (oSize > maxSize) {
ratioSize = maxSize / oSize;
ratio = Math.min(ratio, ratioSize);
}
return ratio;
}
function resize(file, config, callback) {
//file对象没有高宽
var type = file.type; //image format
var canvas = document.createElement("canvas");
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (evt) {
var imageData = evt.target.result;
var img = new Image();
img.src = imageData;
var width = img.width;
var height = img.height;
var imageInfo = {
width: width,
height: height,
size: evt.total
}
var ratio = getResizeRatio(imageInfo, config);
var newImageData = imageData;
if (ratio < 1) {
newImageData = compress(img, width * ratio, height * ratio);;
}
callback(newImageData);
}
function compress(img, width, height) {
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, width, height);
/*
If the height or width of the canvas is 0, the string "data:," is returned.
If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
Chrome also supports the image/webp type.
*/
var supportTypes = {
"image/jpg": true,
"image/png": true,
"image/webp": supportWebP()
};
// var exportType = "image/png";
// if(supportTypes[type]){
// exportType = type;
// }
// 多端一致,缩略图必须是 jpg
var exportType = "image/jpg";
var newImageData = canvas.toDataURL(exportType);
return newImageData;
}
function supportWebP() {
try {
return (canvas.toDataURL('image/webp').indexOf('data:image/webp') == 0);
} catch (err) {
return false;
}
}
}
win.UploadFile = {
init: init,
dataType: dataType,
resize: resize
};
})(window);
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) : (global.UploadClient = factory());
}(this, function () {
var calcPosition = function (width, height, opts) {
var isheight = width < height;
var scale = isheight ? height / width : width / height;
var zoom, x = 0,
y = 0,
w, h;
var gtScale = function () {
if (isheight) {
zoom = width / 100;
w = 100;
h = height / zoom;
y = (h - opts.maxHeight) / 2;
} else {
zoom = height / 100;
h = 100;
w = width / zoom;
x = (w - opts.maxWidth) / 2;
}
return {
w: w,
h: h,
x: -x,
y: -y
};
};
var ltScale = function () {
if (isheight) {
zoom = height / opts.maxHeight;
h = opts.maxHeight;
w = width / zoom;
} else {
zoom = width / opts.maxWidth;
w = opts.maxWidth;
h = height / zoom;
}
return {
w: w,
h: h,
x: -x,
y: -y
};
};
return scale > opts.scale ? gtScale() : ltScale();
};
var getBlobUrl = function (file) {
var URL = window.URL || window.webkitURL;
return URL ? URL.createObjectURL(file) : "";
};
var getThumbnail = function (file, opts, callback) {
var canvas = document.createElement("canvas"),
context = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
var pos = calcPosition(img.width, img.height, opts);
canvas.width = pos.w > opts.maxWidth ? opts.maxWidth : pos.w;
canvas.height = pos.h > opts.maxHeight ? opts.maxHeight : pos.h;
context.drawImage(img, pos.x, pos.y, pos.w, pos.h);
try {
var base64 = canvas.toDataURL(file.type, opts.quality);
var reg = new RegExp('^data:image/[^;]+;base64,');
base64 = base64.replace(reg, '');
callback(base64);
} catch (e) {
throw new Error(e);
}
};
img.src = typeof file == 'string' ? 'data:image/jpg;base64,' + file : getBlobUrl(file);
};
var _compress = function (data, callback) {
var file = data.file;
var opts = data.compress;
getThumbnail(file, opts, callback);
};
_init = function (config, callback) {
if (config.getToken) {
config.getToken(function (token) {
config.multi_parmas || (config.multi_parmas = {});
config.multi_parmas.token = token;
config.headers || (config.headers = {});
if (config.base64) {
config.headers['Content-type'] = 'application/octet-stream';
config.headers['Authorization'] = 'UpToken ' + token;
}
var instance = UploadFile.init(config);
callback(instance);
});
} else {
config.headers || (config.headers = {});
if (config.base64) {
config.headers['Content-type'] = 'application/octet-stream';
}
var instance = UploadFile.init(config);
callback(instance);
}
};
var _upload = function (data, instance, callback) {
instance.upload(data.file, {
onError: function (errorCode) {
callback.onError(errorCode);
},
onProgress: function (loaded, total) {
callback.onProgress(loaded, total);
},
onCompleted: function (result) {
result.filename || (result.filename = result.hash);
var compress = data.compressThumbnail || _compress;
if (data.compress) {
compress(data, function (thumbnail) {
result.thumbnail = thumbnail;
callback.onCompleted(result);
});
} else {
callback.onCompleted(result);
}
}
});
};
var File = function (instance) {
var me = this;
this.instance = instance
this.upload = function (file, callback) {
var data = {
file: file
};
_upload(data, me.instance, callback);
};
this.cancel = function () {
me.instance.cancel();
};
};
var initFile = function (config, callback) {
_init(config, function (instance) {
var uploadFile = new File(instance);
callback(uploadFile);
});
};
var Img = function (instance, cfg) {
var me = this;
this.cfg = cfg;
this.instance = instance;
this.upload = function (file, callback) {
var data = {
file: file,
compress: me.cfg
};
_upload(data, me.instance, callback);
};
this.cancel = function () {
me.instance.cancel();
};
};
var initImage = function (config, callback) {
_init(config, function (instance) {
var compress = {
maxHeight: config.height || 240,
maxWidth: config.width || 240,
quality: config.quality || 0.5,
scale: config.scale || 2.4
};
var uploadImage = new Img(instance, compress);
callback(uploadImage);
});
};
var ImgBase64 = function (config) {
config.base64 = true;
Img.call(this, config);
};
var initImgBase64 = function (config, callback) {
config.base64 = true;
initImage.call(this, config, callback);
};
return {
initFile: initFile,
initImage: initImage,
initImgBase64: initImgBase64,
dataType: UploadFile.dataType
};
})); |
function changeValue(what){
var element = document.getElementById(what);
var inputElement = document.getElementById(what+"Input");
var value = element.innerHTML;
var type = '';
switch (what){
case 'name':
type = 'nime';
break;
case 'type':
type = 'tüüpi';
break;
case 'county':
type = 'maakonda';
break;
case 'city':
type = 'valda/linna';
break;
case 'parish':
type = 'asulat/linnaosa';
break;
case 'address':
type = 'aadressi';
break;
case 'postcode':
type = 'postiindeksit';
break;
case 'webpage':
type = 'veebilehte';
break;
}
console.log(type);
newValue = prompt("Muuda kooli "+type, value);
if (newValue === null) {
return;
}
element.innerHTML = newValue;
inputElement.value = newValue;
console.log(inputElement);
element.parentNode.parentNode.style.backgroundColor = 'lightgray';
}
function changeYearValue(what){
var element = document.getElementById(what);
var inputElement = document.getElementById(what+"Input");
var value = element.innerHTML;
var type = '';
switch (what){
case 'year':
type = 'aastat';
case 'students':
type = 'õpilaste arvu';
case 'boys':
type = 'poiste arvu';
case 'girls':
type = 'tüdrukute arvu';
case 'teachers':
type = 'õpetajate arvu';
case 'language':
type = 'õppekeelt';
case 'notes':
type = 'märkuseid';
default:
}
newValue = prompt("Muuda õppeaasta "+type, value);
if (newValue === null) {
return;
}
element.innerHTML = newValue;
inputElement.value = newValue;
console.log(inputElement);
element.parentNode.parentNode.style.backgroundColor = 'lightgray';
}
function changeDirectorValue(what){
var element = document.getElementById(what);
var inputElement = document.getElementById(what+"Input");
var value = element.innerHTML;
var type = '';
switch (what){
case 'start_year':
type = 'alustamise aastat';
case 'end_year':
type = 'lõpetamise aastat';
case 'principal':
type = 'nime';
default:
}
newValue = prompt("Muuda direktori "+type, value);
if (newValue === null) {
return;
}
element.innerHTML = newValue;
inputElement.value = newValue;
console.log(inputElement);
element.parentNode.parentNode.style.backgroundColor = 'lightgray';
}
|
// Load the routes (which also boots react)
import "./routes";
|
d3.queue()
.defer(d3.json, '../assets/json/nhv_neighborhoods.json')
.defer(d3.json, '../assets/json/nhv_tracts.json')
.defer(d3.csv, '../assets/data/workforce/underemployment_by_location.csv')
.defer(d3.csv, '../assets/data/workforce/underemployment_by_year.csv')
.defer(d3.csv, '../assets/data/workforce/unemployment_rate_by_year.csv')
.defer(d3.csv, '../assets/data/workforce/acs_public_transit_by_neighborhood.csv')
.defer(d3.csv, '../assets/data/workforce/acs_median_income_by_tract.csv')
.await(initWorkforce);
///////////// INIT
function initWorkforce(error, hoods, tracts, underempLoc, underempTrend, unempTrend, transit, income) {
if (error) throw error;
underempLoc.forEach(function(d) {
d.value = +d.value;
});
underempTrend.forEach(function(d) {
d.value = +d.value;
});
unempTrend.forEach(function(d) {
d.value = +d.value;
});
transit.forEach(function(d) {
d.value = +d.value;
});
income.forEach(function(d) {
d.value = +d.value;
});
var commuteMap = d3map();
d3.select('#commute-map')
.datum(topojson.feature(hoods, hoods.objects.shapes))
.call(commuteMap);
commuteMap.color(transit, choroscale)
.tip('d3-tip', d3.format('.2p'), true)
.legend(d3.format('.0%'), 15, 0);
var incomeMap = d3map();
d3.select('#income-map')
.datum(topojson.feature(tracts, tracts.objects.nhv_tracts))
.call(incomeMap);
incomeMap.color(income, choroscale)
.tip('d3-tip', d3.format('$,'), false)
.legend(d3.format('$,'), 15, 0);
var locationChart = makeUnderLocation(underempLoc);
var underTrend = makeUnderTrend(underempTrend);
var unTrend = makeUnTrend(unempTrend);
d3.select(window).on('resize', function() {
locationChart.draw(0, true);
underTrend = makeUnderTrend(underempTrend);
unTrend = makeUnTrend(unempTrend);
commuteMap.draw();
incomeMap.draw();
redrawDots();
});
redrawDots();
}
function makeUnderLocation(data) {
var margin = { top: 12, right: 18, bottom: 40, left: 100 };
var svg = d3.select('#underemployment-chart')
.append('svg')
.attr('width', '100%')
.attr('height', '100%');
// .attr('viewBox', '0 0 ' + fullwidth + ' ' + fullheight);
var chart = new dimple.chart(svg, data);
chart.setMargins(margin.left, margin.top, margin.right, margin.bottom);
chart.defaultColors = [ pink ];
var y = chart.addCategoryAxis('y', 'name');
y.addOrderRule(['CT', 'GNH', 'New Haven', 'NHV low-income', 'Other NHV'], true);
y.title = null;
var x = chart.addMeasureAxis('x', 'value');
// x.title = '';
x.tickFormat = '.0%';
x.ticks = 4;
x.title = null;
var bars = chart.addSeries(null, dimple.plot.bar);
chart.draw();
var tip = d3.tip()
.attr('class', 'd3-tip')
.html(horizTip);
svg.selectAll('rect.dimple-bar')
.call(tip)
.on('mouseover', function(d) {
tip.show(d);
barOver(this);
})
.on('mouseout', function(d) {
tip.hide(d);
barOut(this);
})
.on('touchend', function(d) {
tip.show(d);
barOver(this);
});
return chart;
}
function makeUnderTrend(data) {
var margin = { top: 24, right: 32, bottom: 48, left: 32 };
var svg = d3.select('#underemployment-trend')
.select('svg')
.attr('width', '100%')
.attr('height', '100%')
.html('');
var chart = new dimple.chart(svg, data);
chart.setMargins(margin.left, margin.top, margin.right, margin.bottom);
var x = chart.addTimeAxis('x', 'year', '%Y', '%Y');
x.title = null;
var y = chart.addMeasureAxis('y', 'value');
y.tickFormat = '.0%';
y.ticks = 4;
chart.defaultColors = [ ltblue, pink ];
// var colorline = chart.addSeries('Type', dimple.plot.line);
// colorline.lineMarkers = true;
var past = dimple.filterData(data, 'type', 'past');
var goal = dimple.filterData(data, 'type', 'goal');
var goalline = chart.addSeries('type', dimple.plot.line);
var pastline = chart.addSeries(null, dimple.plot.line);
pastline.lineMarkers = true;
goalline.lineMarkers = true;
pastline.data = past;
goalline.data = goal;
// chart.addLegend('80%', '8%', '10%', '20%', 'right', colorline);
chart.draw();
d3.select('#dimple-goal')
.style('stroke-dasharray', ('5, 5'));
var tip = d3.tip()
.attr('class', 'd3-tip')
.html(trendTip);
svg.selectAll('circle.dimple-marker')
.call(tip)
.on('mouseover', function(d) {
tip.show(d);
dotOver(this);
})
.on('mouseout', function(d) {
tip.hide(d);
dotOut(this);
})
.on('touchstart', function(d) {
d3.event.preventDefault();
tip.show(d);
dotOver(this);
});
// svg.selectAll('.dimple-marker.dimple-goal:first-child')
// .attr('display', 'none');
return chart;
}
function makeUnTrend(data) {
var margin = { top: 24, right: 32, bottom: 48, left: 32 };
var svg = d3.select('#unemployment-trend')
.select('svg')
.attr('width', '100%')
.attr('height', '100%')
.html('');
var chart = new dimple.chart(svg, data);
chart.setMargins(margin.left, margin.top, margin.right, margin.bottom);
var x = chart.addTimeAxis('x', 'year', '%Y', '%Y');
x.title = null;
var y = chart.addMeasureAxis('y', 'value');
y.tickFormat = '.0%';
y.ticks = 6;
chart.defaultColors = [ pink, ltblue ];
var colorline = chart.addSeries('name', dimple.plot.line);
colorline.lineMarkers = true;
chart.addLegend('80%', '8%', '10%', '20%', 'right', colorline);
chart.draw();
var tip = d3.tip()
.attr('class', 'd3-tip')
.html(trendGroupTip);
svg.selectAll('circle.dimple-marker')
.call(tip)
.on('mouseover', function(d) {
tip.show(d);
dotOver(this);
})
.on('mouseout', function(d) {
tip.hide(d);
dotOut(this);
});
return chart;
}
|
const express = require('express')
const router = express.Router()
router.post('/createDev', require('./createDev'))
router.get('/', require('./getAll'))
router.post('/', require('./create'))
router.delete('/:id', require('./remove'))
router.put('/:id', require('./update'))
module.exports = router
|
const express = require('express');
const path = require('path');
const router = express.Router();
router.get('/', (req, res, next) => {
res.sendfile(path.join(__dirname, '../../dist/b/app.htm'));
});
module.exports = router;
|
'use strict';
/**
* This contains all the core commands that kalabox can run on every machine
*/
module.exports = function(kbox) {
var _ = require('lodash');
var Promise = require('bluebird');
var format = require('util').format;
kbox.whenApp(function(app) {
kbox.tasks.add(function(task) {
task.path = [app.name, 'terminal'];
task.description = 'Terminal into a container.';
task.kind = 'argv1';
task.func = function(done) {
// CLI argument.
var target = this.payload[0];
// Get list of containers for this app.
kbox.engine.list(app.name)
// Filter containers that match target.
.filter(function(container) {
// Match target against container's id.
var isContainerId = container.id === target;
// Match target against container's name.
var isContainerName = container.name === target;
// Match target against component's name.
var isComponentName = (function() {
var o = kbox.util.docker.containerName.parse(container.name);
return o.name === target;
})();
return isContainerId || isContainerName || isComponentName;
})
// If no containers matched, then throw an error.
.then(function(containers) {
if (containers.length > 0) {
return _.head(containers);
} else {
throw new Error(format(
'Could not find any containers matching "%s".', target
));
}
})
// Terminal into container.
.then(function(container) {
return kbox.engine.terminal(container.id);
})
// Return.
.nodeify(done);
};
});
});
};
|
(function () {
"use strict";
angular.module('app').directive('dTrailsIndex', function () {
return {
templateUrl: 'app/templates/dTrailsIndexTemplate.html'
}
});
})(); |
'use strict';
/**
* Module dependencies.
*/
var errorHandler = require('./errors.server.controller'),
db = require('../models/fixmanager.server.model'),
_ = require('lodash'),
bluebird = require('bluebird');
/**
* Create a Fixmanager
*/
exports.create = function(req, res) {
db.FixManager.create({
name: req.body.name,
assignedWorkerThread: req.body.assignedWorkerThread
}).complete(function(err, results){
res.sendStatus(201);
});
};
/**
* List of Fixmanagers
*/
exports.list = function(req, res) {
db.FixManager.findAll()
.complete(function(err, results){
res.json(results);
});
};
|
'use strict';
const winston = require('winston');
const { ENV } = require('./config');
/**
* Use winston to loge inside the moudles
* And another generic logger to get http requests
*/
const consoleOptions = {
level: 'debug',
handleExceptions: true,
json: true,
colorize: true
};
let logger;
if(ENV!=="test"){
logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(consoleOptions),
]
});
logger.stream = {
write: (message, encoding) => {
logger.debug(message);
}
};
}else{
logger = new (winston.Logger)({});
}
module.exports = {logger};
|
// CookieUtil.get()/CookieUtil.set()
// use to set cookie
//
var CookieUtil = {
get: function (name) {
var cookieName = encodeURIComponent(name) + '=',
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if (cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(';', cookieStart);
if (cookieEnd == -1) cookieEnd = document.cookie.length;
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart
+ cookieName.length, cookieEnd));
}
return cookieValue;
},
set: function (name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if (expires instanceof Date) {
cookieText += '; expires=' + expires.toGMTString();
}
if (path) cookieText += '; path=' + path;
domain && (cookieText += '; domain=' + domain);
secure && (cookieText += '; secure');
document.cookie = cookieText;
},
unset: function (name, path, domain, secure) {
this.set(name, '', new Date(0), path, domain, secure);
}
};
// send authentication request
//
$.ajax({
url: '/auth/',
type: 'get',
async: false
})
.done(function (resData) {
var res = resData;
if (res.errcode && res.errcode == 1) {
document.title != 'Continue-login' && (location.href = '/login.html');
} else {
// if has login, record the userId as browser identify
CookieUtil.set('identify', res.member_id);
}
});
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
let act;
describe('ReactSuspenseEffectsSemanticsDOM', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
act = require('jest-react').act;
});
it('should not cause a cycle when combined with a render phase update', () => {
let scheduleSuspendingUpdate;
function App() {
const [value, setValue] = React.useState(true);
scheduleSuspendingUpdate = () => setValue(!value);
return (
<>
<React.Suspense fallback="Loading...">
<ComponentThatCausesBug value={value} />
<ComponentThatSuspendsOnUpdate shouldSuspend={!value} />
</React.Suspense>
</>
);
}
function ComponentThatCausesBug({value}) {
const [mirroredValue, setMirroredValue] = React.useState(value);
if (mirroredValue !== value) {
setMirroredValue(value);
}
// eslint-disable-next-line no-unused-vars
const [_, setRef] = React.useState(null);
return <div ref={setRef} />;
}
const promise = Promise.resolve();
function ComponentThatSuspendsOnUpdate({shouldSuspend}) {
if (shouldSuspend) {
// Fake Suspend
throw promise;
}
return null;
}
act(() => {
const root = ReactDOM.createRoot(document.createElement('div'));
root.render(<App />);
});
act(() => {
scheduleSuspendingUpdate();
});
});
});
|
System.register([], function (_export, _context) {
"use strict";
var PDF;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
return {
setters: [],
execute: function () {
_export("PDF", PDF = function PDF() {
_classCallCheck(this, PDF);
});
_export("PDF", PDF);
}
};
});
//# sourceMappingURL=../dist/dev/pdf/pdf.js.map
|
NEWSBLUR.Modal = function(options) {
var defaults = {
width: 600
};
this.options = _.extend({}, defaults, options);
this.model = NEWSBLUR.assets;
this.runner();
this.flags = {};
};
NEWSBLUR.Modal.prototype = {
runner: function() {},
open_modal: function(callback) {
var self = this;
this.$modal.modal({
'minWidth': this.options.width || 600,
'maxWidth': this.options.width || 600,
'overlayClose': true,
'onOpen': function (dialog) {
self.flags.open = true;
dialog.overlay.fadeIn(200, function () {
dialog.container.addClass(self.options.modal_container_class);
dialog.container.fadeIn(200);
dialog.data.fadeIn(200, function() {
if (self.options.onOpen) {
self.options.onOpen();
}
if (callback) {
callback();
}
});
setTimeout(function() {
// $(window).resize();
self.resize();
self.flags.modal_loaded = true;
});
});
},
'onShow': function(dialog) {
$('#simplemodal-container').corner('6px');
if (self.options.onShow) {
self.options.onShow();
}
},
'onClose': function(dialog, callback) {
self.flags.open = false;
dialog.data.hide().empty().remove();
dialog.container.hide().empty().remove();
dialog.overlay.fadeOut(200, function() {
if (self.options.onOpen) {
self.options.onOpen();
}
dialog.overlay.empty().remove();
$.modal.close(callback);
});
$('.NB-modal-holder').empty().remove();
}
});
},
resize: function() {
// $(window).trigger('resize.simplemodal');
$.modal.resize();
},
close: function(callback) {
$('.NB-modal-loading', this.$modal).removeClass('NB-active');
$.modal.close(callback);
},
make_feed_chooser: function(options) {
options = options || {};
var $chooser = $.make('select', { name: 'feed', className: 'NB-modal-feed-chooser' });
var $feeds_optgroup = $.make('optgroup', { label: "Sites" });
var $social_feeds_optgroup = $.make('optgroup', { label: "Blurblogs" });
var $starred_feeds_optgroup = $.make('optgroup', { label: "Saved Tags" });
var current_feed_id = this.feed_id;
var make_feed_option = function(feed) {
if (!feed.get('feed_title')) return;
var $option = $.make('option', { value: feed.id }, feed.get('feed_title'));
$option.appendTo(feed.is_starred() ? $starred_feeds_optgroup :
feed.is_social() ? $social_feeds_optgroup :
$feeds_optgroup);
if (feed.id == current_feed_id) {
$option.attr('selected', true);
}
};
this.feeds = this.model.get_feeds();
this.feeds.each(make_feed_option);
if (!options.skip_social) {
this.social_feeds = this.model.get_social_feeds();
this.social_feeds.each(make_feed_option);
}
if (!options.skip_starred) {
this.starred_feeds = this.model.get_starred_feeds();
this.starred_feeds.each(make_feed_option);
}
$('option', $feeds_optgroup).tsort();
$('option', $social_feeds_optgroup).tsort();
$('option', $starred_feeds_optgroup).tsort();
$chooser.append($feeds_optgroup);
if (!options.skip_social) {
$chooser.append($social_feeds_optgroup);
}
if (!options.skip_starred) {
$chooser.append($starred_feeds_optgroup);
}
return $chooser;
},
initialize_feed: function(feed_id) {
this.feed_id = feed_id;
this.feed = this.model.get_feed(feed_id);
this.options.social_feed = this.feed.is_social();
$('.NB-modal-subtitle .NB-modal-feed-image', this.$modal).attr('src', $.favicon(this.feed));
$('.NB-modal-subtitle .NB-modal-feed-title', this.$modal).html(this.feed.get('feed_title'));
$('.NB-modal-subtitle .NB-modal-feed-subscribers', this.$modal).html(Inflector.pluralize(' subscriber', this.feed.get('num_subscribers'), true));
},
switch_tab: function(newtab) {
var $modal_tabs = $('.NB-modal-tab', this.$modal);
var $tabs = $('.NB-tab', this.$modal);
$modal_tabs.removeClass('NB-active');
$tabs.removeClass('NB-active');
$modal_tabs.filter('.NB-modal-tab-'+newtab).addClass('NB-active');
$tabs.filter('.NB-tab-'+newtab).addClass('NB-active');
}
}; |
define([], function() {
var strings = {
"_NAR8NFw8cblGJm9t5CjqOw": {
"SuccessfullyLoadedText": "โหลดไฟล์กำกับการดีบักเสร็จเรียบร้อยแล้ว",
"ErrorLoadingText": "ไม่สามารถโหลดไฟล์กำกับการดีบัก: {0}"
},
"_vd/LT/qfiQhbHFfeM1GtlA": {
"FetchFailedError": "การดึงข้อมูล Webpart ล้มเหลว โดยมีข้อผิดพลาด \"{0}\" การแสดงผลเวิร์กเบนช์ที่แคชไว้อาจล้มเหลว",
"CanvasInitializationError": "การเตรียมใช้งานพื้นที่ทำงานล้มเหลวโดยมีข้อผิดพลาด \"{0}\"",
"UnknownError": "มีข้อผิดพลาดที่ไม่รู้จักเกิดขึ้น \"{0}\""
},
"_FQya7ZjwIyrOEutOa+omIA": {
"Title": "คำเตือน",
"SubText": "Web Part ของคุณจะไม่ปรากฏในกล่องเครื่องมือ โปรดตรวจสอบให้แน่ใจว่า \"gulp serve\" กำลังทำงานอยู่ในโครงการ Web Part และโปรดรีเฟรชหน้าเมื่อ \"gulp serve\" ทำงานแล้ว",
"OkButtonText": "ตกลง",
"ClickHerePrefix": "คลิก ",
"ClickHereLink": "ที่นี่",
"ClickHereSuffix": " สำหรับข้อมูลเพิ่มเติม"
},
"_1JArBGDet5Uj9pJOV/9sFw": {
"UrlTextBoxPlaceholder": "ใส่ URL ที่จะดูในเครื่องมือแสดงตัวอย่างแบบอุปกรณ์เคลื่อนที่",
"ScreenReaderMobilePreviewEntered": "คุณได้ใส่เครื่องมือแสดงตัวอย่างแบบอุปกรณ์เคลื่อนที่ ถ้าคุณต้องการแสดงตัวอย่างเพจอื่น ให้ป้อน URL ลงในเขตข้อมูลข้อความ URL เมื่อต้องการปิดเครื่องมือนี้และกลับไปยังบนเวิร์กเบนช์ ให้กด Escape",
"ScreenReaderDevicePickerEntered": "ใช้แป้นลูกศรซ้ายและขวาเพื่อเลือกอุปกรณ์เมื่อต้องการเปลี่ยนขนาดของหน้าจอตัวอย่าง",
"ScreenReaderDevicePickerSelectionChanged": "กด Enter เพื่อเลือกอุปกรณ์นี้",
"Width": "ความกว้าง",
"Height": "ความสูง"
},
"_8EVKOH1av6NjR/ZNfdafrw": {
"WebPartData": "ข้อมูล Web Part ",
"ClassicPages": "หน้าแบบคลาสสิก",
"ModernPages": "หน้าแบบสมัยใหม่",
"Close": "ปิด",
"WebPartDataHelpInfoLink": "เรียนรู้เกี่ยวกับการเตรียมใช้งานแอสเซท SharePoint จาก Web part ฝั่งไคลเอ็นต์ของ SharePoint"
},
"_IusqdbcSoVYQiit3+QRSxw": {
"Office365Title": "Office 365",
"SharePointWorkbenchTitle": "เวิร์กเบนช์ SharePoint",
"ScreenReaderDisplayModeSwitchToEditMode": "สลับจากโหมดแสดงตัวอย่างไปยังโหมดแก้ไข",
"ScreenReaderDisplayModeSwitchToReadMode": "สลับจากโหมดแก้ไขไปยังโหมดแสดงตัวอย่าง"
},
"_nCtJlVOXBHa59LgYtajnjA": {
"Save": "บันทึก",
"SaveAltText": "ใช้เพื่อบันทึกสถานะเวิร์กเบนช์ปัจจุบัน",
"Discard": "ละทิ้ง",
"DiscardAltText": "ใช้เพื่อละทิ้งสถานะเวิร์กเบนช์ปัจจุบัน",
"Mobile": "มือถือ",
"MobleAltText": "ใช้เพื่อเปิดเครื่องมือแสดงตัวอย่างแบบอุปกรณ์เคลื่อนที่สำหรับโทรศัพท์มือถือ",
"Tablet": "แท็บเล็ต",
"TabletAltText": "ใช้เพื่อเปิดเครื่องมือแสดงตัวอย่างแบบอุปกรณ์เคลื่อนที่สำหรับแท็บเล็ต",
"Preview": "แสดงตัวอย่าง",
"PreviewAltText": "ใช้เพื่อสลับจากโหมดแก้ไขไปยังโหมดแสดงตัวอย่าง",
"Edit": "แก้ไข",
"EditAltText": "ใช้เพื่อสลับไปยังโหมดแก้ไข",
"WebPartData": "ข้อมูล Web part ",
"WebPartDataAltText": "แสดงข้อมูล Web part แบบอนุกรม"
}
};
strings.default = strings;
return strings;
}); |
module.exports = (req, cb) => {
const chekt = req.body.text || 'rekt';
const text = `\n[ ] not ${chekt} [✓] ${chekt}`;
const payload = {
icon_emoji: ':grimacing:',
text: text,
};
return cb(payload);
};
|
import React from 'react';
import {
Button,
Card,
CardTitle,
CardTitleText,
CardSubtitleText,
CardSupportingText,
CardMedia,
CardMenu,
CardActions
} from '../index'; // material-design-react
class Examples extends React.Component {
render() {
let children = React.Children.map(this.props.children, (child) => {
return <div>{child}</div>;
});
return (
<div>{children}</div>
);
}
}
class App extends React.Component {
render() {
return (
<Examples>
<Button raised colored ripple >standard</Button>
<Button disabled >disabled</Button>
<Button colored raised >raised colored</Button>
<Button raised ripple >raised ripple</Button>
<Button display="raised" >use prop display="raised"</Button>
<Button fab colored ripple ><i className={'material-icons'}>add</i></Button>
<Button icon ripple ><i className={'material-icons'}>add</i></Button>
<Button display="miniFab" colored ><i className={'material-icons'}>add</i></Button>
<Button miniFab colored ><i className={'material-icons'}>add</i></Button>
<Button className="example-custom-red">Custom style</Button>
<Card shadow="3">
<Card.Title>
<Card.TitleText border>
Card.TitleText
</Card.TitleText>
</Card.Title>
</Card>
<Card shadow="8">
<CardTitle border>
<CardTitleText level="1">
CardTitleText level 1
</CardTitleText>
<CardSubtitleText border>
Subtitle
</CardSubtitleText>
</CardTitle>
<CardMedia>
CardMedia
</CardMedia>
<CardSupportingText border>
A man once sat under a tree
</CardSupportingText>
<CardMenu>
<Button icon className="material-icons">add</Button>
</CardMenu>
<CardActions border>
<Button display="raised">
action!
</Button>
</CardActions>
</Card>
<br/>
<Card
title="the card title"
titleBorder
subtitle="a subtitle"
media={<div>Some media</div>}
supporting="supporting text"
actions={[<Button colored>GO!</Button>]}
actionsBorder
shadow="8" />
</Examples>
);
}
}
React.render(<App />, document.getElementById('app'));
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var AvStop = React.createClass({
displayName: 'AvStop',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M6 6h12v12H6z' })
);
}
});
module.exports = AvStop; |
/**
* Javascript code to store data as JSON strings in cookies.
* It uses prototype.js 1.5.1 (http://www.prototypejs.org)
*
* Author : Lalit Patel
* Website: http://www.lalit.org/lab/jsoncookies
* License: Creative Commons Attribution-ShareAlike 2.5
* http://creativecommons.org/licenses/by-sa/2.5/
* Version: 0.4
* Updated: Aug 11, 2007 10:09am
*
* Chnage Log:
* v 0.4
* - Removed a extra comma in options (was breaking in IE and Opera). (Thanks Jason)
* - Removed the parameter name from the initialize function
* - Changed the way expires date was being calculated. (Thanks David)
* v 0.3
* - Removed dependancy on json.js (http://www.json.org/json.js)
* - empty() function only deletes the cookies set by CookieJar
*/
var CookieJar = Class.create();
CookieJar.prototype = {
/**
* Append before all cookie names to differntiate them.
*/
appendString: "",
/**
* Initializes the cookie jar with the options.
*/
initialize: function(options) {
this.options = {
expires: 3600, // seconds (1 hr)
path: '', // cookie path
domain: '', // cookie domain
secure: '' // secure ?
};
Object.extend(this.options, options || {});
if (this.options.expires != '') {
var date = new Date();
date = new Date(date.getTime() + (this.options.expires * 1000));
this.options.expires = '; expires=' + date.toGMTString();
}
if (this.options.path != '') {
this.options.path = '; path=' + escape(this.options.path);
}
if (this.options.domain != '') {
this.options.domain = '; domain=' + escape(this.options.domain);
}
if (this.options.secure == 'secure') {
this.options.secure = '; secure';
} else {
this.options.secure = '';
}
},
/**
* Adds a name values pair.
*/
put: function(name, value) {
name = this.appendString + name;
cookie = this.options;
var type = typeof value;
switch(type) {
case 'undefined':
case 'function' :
case 'unknown' : return false;
case 'boolean' :
case 'string' :
case 'number' : value = String(value.toString());
}
var cookie_str = name + "=" + escape(Object.toJSON(value));
try {
document.cookie = cookie_str + cookie.expires + cookie.path + cookie.domain + cookie.secure;
} catch (e) {
return false;
}
return true;
},
/**
* Removes a particular cookie (name value pair) form the Cookie Jar.
*/
remove: function(name) {
name = this.appendString + name;
cookie = this.options;
try {
var date = new Date();
date.setTime(date.getTime() - (3600 * 1000));
var expires = '; expires=' + date.toGMTString();
document.cookie = name + "=" + expires + cookie.path + cookie.domain + cookie.secure;
} catch (e) {
return false;
}
return true;
},
/**
* Return a particular cookie by name;
*/
get: function(name) {
name = this.appendString + name;
var cookies = document.cookie.match(name + '=(.*?)(;|$)');
if (cookies) {
return (unescape(cookies[1].replace(/\+/g, ' '))).evalJSON();
} else {
return null;
}
},
/**
* Empties the Cookie Jar. Deletes all the cookies.
*/
empty: function() {
keys = this.getKeys();
size = keys.size();
for(i=0; i<size; i++) {
this.remove(keys[i]);
}
},
/**
* Returns all cookies as a single object
*/
getPack: function() {
pack = {};
keys = this.getKeys();
size = keys.size();
for(i=0; i<size; i++) {
pack[keys[i]] = this.get(keys[i]);
}
return pack;
},
/**
* Returns all keys.
*/
getKeys: function() {
keys = $A();
keyRe= /[^=; ]+(?=\=)/g;
str = document.cookie;
CJRe = new RegExp("^" + this.appendString);
while((match = keyRe.exec(str)) != undefined) {
if (CJRe.test(match[0].strip())) {
keys.push(match[0].strip().gsub("^" + this.appendString,""));
}
}
return keys;
}
}; |
(function(root, undefined) {
'use strict';
|
/*!
* QUnit 1.19.0
* http://qunitjs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-09-01T15:00Z
*/
(function (global) {
var QUnit = {};
var Date = global.Date;
var now = Date.now || function () {
return new Date().getTime();
};
var setTimeout = global.setTimeout;
var clearTimeout = global.clearTimeout;
// Store a local window from the global to allow direct references.
var window = global.window;
var defined = {
document: window && window.document !== undefined,
setTimeout: setTimeout !== undefined,
sessionStorage: (function () {
var x = "qunit-test-string";
try {
sessionStorage.setItem(x, x);
sessionStorage.removeItem(x);
return true;
} catch (e) {
return false;
}
}() )
};
var fileName = ( sourceFromStacktrace(0) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, "");
var globalStartCalled = false;
var runStarted = false;
var toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty;
// returns a new Array with the elements that are in a but not in b
function diff(a, b) {
var i, j,
result = a.slice();
for (i = 0; i < result.length; i++) {
for (j = 0; j < b.length; j++) {
if (result[i] === b[j]) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
// from jquery.js
function inArray(elem, array) {
if (array.indexOf) {
return array.indexOf(elem);
}
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === elem) {
return i;
}
}
return -1;
}
/**
* Makes a clone of an object using only Array or Object as base,
* and copies over the own enumerable properties.
*
* @param {Object} obj
* @return {Object} New object with only the own properties (recursively).
*/
function objectValues(obj) {
var key, val,
vals = QUnit.is("array", obj) ? [] : {};
for (key in obj) {
if (hasOwn.call(obj, key)) {
val = obj[key];
vals[key] = val === Object(val) ? objectValues(val) : val;
}
}
return vals;
}
function extend(a, b, undefOnly) {
for (var prop in b) {
if (hasOwn.call(b, prop)) {
// Avoid "Member not found" error in IE8 caused by messing with window.constructor
// This block runs on every environment, so `global` is being used instead of `window`
// to avoid errors on node.
if (prop !== "constructor" || a !== global) {
if (b[prop] === undefined) {
delete a[prop];
} else if (!( undefOnly && typeof a[prop] !== "undefined" )) {
a[prop] = b[prop];
}
}
}
}
return a;
}
function objectType(obj) {
if (typeof obj === "undefined") {
return "undefined";
}
// Consider: typeof null === object
if (obj === null) {
return "null";
}
var match = toString.call(obj).match(/^\[object\s(.*)\]$/),
type = match && match[1] || "";
switch (type) {
case "Number":
if (isNaN(obj)) {
return "nan";
}
return "number";
case "String":
case "Boolean":
case "Array":
case "Set":
case "Map":
case "Date":
case "RegExp":
case "Function":
return type.toLowerCase();
}
if (typeof obj === "object") {
return "object";
}
return undefined;
}
// Safe object type checking
function is(type, obj) {
return QUnit.objectType(obj) === type;
}
var getUrlParams = function () {
var i, current;
var urlParams = {};
var location = window.location;
var params = location.search.slice(1).split("&");
var length = params.length;
if (params[0]) {
for (i = 0; i < length; i++) {
current = params[i].split("=");
current[0] = decodeURIComponent(current[0]);
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[1] = current[1] ? decodeURIComponent(current[1]) : true;
if (urlParams[current[0]]) {
urlParams[current[0]] = [].concat(urlParams[current[0]], current[1]);
} else {
urlParams[current[0]] = current[1];
}
}
}
return urlParams;
};
// Doesn't support IE6 to IE9, it will return undefined on these browsers
// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
function extractStacktrace(e, offset) {
offset = offset === undefined ? 4 : offset;
var stack, include, i;
if (e.stack) {
stack = e.stack.split("\n");
if (/^error$/i.test(stack[0])) {
stack.shift();
}
if (fileName) {
include = [];
for (i = offset; i < stack.length; i++) {
if (stack[i].indexOf(fileName) !== -1) {
break;
}
include.push(stack[i]);
}
if (include.length) {
return include.join("\n");
}
}
return stack[offset];
// Support: Safari <=6 only
} else if (e.sourceURL) {
// exclude useless self-reference for generated Error objects
if (/qunit.js$/.test(e.sourceURL)) {
return;
}
// for actual exceptions, this is useful
return e.sourceURL + ":" + e.line;
}
}
function sourceFromStacktrace(offset) {
var error = new Error();
// Support: Safari <=7 only, IE <=10 - 11 only
// Not all browsers generate the `stack` property for `new Error()`, see also #636
if (!error.stack) {
try {
throw error;
} catch (err) {
error = err;
}
}
return extractStacktrace(error, offset);
}
/**
* Config object: Maintain internal state
* Later exposed as QUnit.config
* `config` initialized at top of scope
*/
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
// by default, scroll to top of the page when suite is done
scrolltop: true,
// depth up-to which object will be dumped
maxDepth: 5,
// when enabled, all tests must call expect()
requireExpects: false,
// add checkboxes that are persisted in the query-string
// when enabled, the id is set to `true` as a `QUnit.config` property
urlConfig: [
{
id: "hidepassed",
label: "Hide passed tests",
tooltip: "Only show tests and assertions that fail. Stored as query-strings."
},
{
id: "noglobals",
label: "Check for Globals",
tooltip: "Enabling this will test if any test introduces new properties on the " +
"global object (`window` in Browsers). Stored as query-strings."
},
{
id: "notrycatch",
label: "No try-catch",
tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging " +
"exceptions in IE reasonable. Stored as query-strings."
}
],
// Set of all modules.
modules: [],
// The first unnamed module
currentModule: {
name: "",
tests: []
},
callbacks: {}
};
var urlParams = defined.document ? getUrlParams() : {};
// Push a loose unnamed module to the modules collection
config.modules.push(config.currentModule);
if (urlParams.filter === true) {
delete urlParams.filter;
}
// String search anywhere in moduleName+testName
config.filter = urlParams.filter;
config.testId = [];
if (urlParams.testId) {
// Ensure that urlParams.testId is an array
urlParams.testId = decodeURIComponent(urlParams.testId).split(",");
for (var i = 0; i < urlParams.testId.length; i++) {
config.testId.push(urlParams.testId[i]);
}
}
var loggingCallbacks = {};
// Register logging callbacks
function registerLoggingCallbacks(obj) {
var i, l, key,
callbackNames = ["begin", "done", "log", "testStart", "testDone",
"moduleStart", "moduleDone"];
function registerLoggingCallback(key) {
var loggingCallback = function (callback) {
if (objectType(callback) !== "function") {
throw new Error(
"QUnit logging methods require a callback function as their first parameters."
);
}
config.callbacks[key].push(callback);
};
// DEPRECATED: This will be removed on QUnit 2.0.0+
// Stores the registered functions allowing restoring
// at verifyLoggingCallbacks() if modified
loggingCallbacks[key] = loggingCallback;
return loggingCallback;
}
for (i = 0, l = callbackNames.length; i < l; i++) {
key = callbackNames[i];
// Initialize key collection of logging callback
if (objectType(config.callbacks[key]) === "undefined") {
config.callbacks[key] = [];
}
obj[key] = registerLoggingCallback(key);
}
}
function runLoggingCallbacks(key, args) {
var i, l, callbacks;
callbacks = config.callbacks[key];
for (i = 0, l = callbacks.length; i < l; i++) {
callbacks[i](args);
}
}
// DEPRECATED: This will be removed on 2.0.0+
// This function verifies if the loggingCallbacks were modified by the user
// If so, it will restore it, assign the given callback and print a console warning
function verifyLoggingCallbacks() {
var loggingCallback, userCallback;
for (loggingCallback in loggingCallbacks) {
if (QUnit[loggingCallback] !== loggingCallbacks[loggingCallback]) {
userCallback = QUnit[loggingCallback];
// Restore the callback function
QUnit[loggingCallback] = loggingCallbacks[loggingCallback];
// Assign the deprecated given callback
QUnit[loggingCallback](userCallback);
if (global.console && global.console.warn) {
global.console.warn(
"QUnit." + loggingCallback + " was replaced with a new value.\n" +
"Please, check out the documentation on how to apply logging callbacks.\n" +
"Reference: http://api.qunitjs.com/category/callbacks/"
);
}
}
}
}
(function () {
if (!defined.document) {
return;
}
// `onErrorFnPrev` initialized at top of scope
// Preserve other handlers
var onErrorFnPrev = window.onerror;
// Cover uncaught exceptions
// Returning true will suppress the default browser handler,
// returning false will let it run.
window.onerror = function (error, filePath, linerNr) {
var ret = false;
if (onErrorFnPrev) {
ret = onErrorFnPrev(error, filePath, linerNr);
}
// Treat return value as window.onerror itself does,
// Only do our handling if not suppressed.
if (ret !== true) {
if (QUnit.config.current) {
if (QUnit.config.current.ignoreGlobalErrors) {
return true;
}
QUnit.pushFailure(error, filePath + ":" + linerNr);
} else {
QUnit.test("global failure", extend(function () {
QUnit.pushFailure(error, filePath + ":" + linerNr);
}, {validTest: true}));
}
return false;
}
return ret;
};
})();
QUnit.urlParams = urlParams;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !( defined.document && window.location.protocol !== "file:" );
// Expose the current QUnit version
QUnit.version = "1.19.0";
extend(QUnit, {
// call on start of module test to prepend name to all tests
module: function (name, testEnvironment) {
var currentModule = {
name: name,
testEnvironment: testEnvironment,
tests: []
};
// DEPRECATED: handles setup/teardown functions,
// beforeEach and afterEach should be used instead
if (testEnvironment && testEnvironment.setup) {
testEnvironment.beforeEach = testEnvironment.setup;
delete testEnvironment.setup;
}
if (testEnvironment && testEnvironment.teardown) {
testEnvironment.afterEach = testEnvironment.teardown;
delete testEnvironment.teardown;
}
config.modules.push(currentModule);
config.currentModule = currentModule;
},
// DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0.
asyncTest: asyncTest,
test: test,
skip: skip,
// DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0.
// In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior.
start: function (count) {
var globalStartAlreadyCalled = globalStartCalled;
if (!config.current) {
globalStartCalled = true;
if (runStarted) {
throw new Error("Called start() outside of a test context while already started");
} else if (globalStartAlreadyCalled || count > 1) {
throw new Error("Called start() outside of a test context too many times");
} else if (config.autostart) {
throw new Error("Called start() outside of a test context when " +
"QUnit.config.autostart was true");
} else if (!config.pageLoaded) {
// The page isn't completely loaded yet, so bail out and let `QUnit.load` handle it
config.autostart = true;
return;
}
} else {
// If a test is running, adjust its semaphore
config.current.semaphore -= count || 1;
// Don't start until equal number of stop-calls
if (config.current.semaphore > 0) {
return;
}
// throw an Error if start is called more often than stop
if (config.current.semaphore < 0) {
config.current.semaphore = 0;
QUnit.pushFailure(
"Called start() while already started (test's semaphore was 0 already)",
sourceFromStacktrace(2)
);
return;
}
}
resumeProcessing();
},
// DEPRECATED: QUnit.stop() will be removed in QUnit 2.0.
stop: function (count) {
// If there isn't a test running, don't allow QUnit.stop() to be called
if (!config.current) {
throw new Error("Called stop() outside of a test context");
}
// If a test is running, adjust its semaphore
config.current.semaphore += count || 1;
pauseProcessing();
},
config: config,
is: is,
objectType: objectType,
extend: extend,
load: function () {
config.pageLoaded = true;
// Initialize the configuration options
extend(config, {
stats: {all: 0, bad: 0},
moduleStats: {all: 0, bad: 0},
started: 0,
updateRate: 1000,
autostart: true,
filter: ""
}, true);
config.blocking = false;
if (config.autostart) {
resumeProcessing();
}
},
stack: function (offset) {
offset = ( offset || 0 ) + 2;
return sourceFromStacktrace(offset);
}
});
registerLoggingCallbacks(QUnit);
function begin() {
var i, l,
modulesLog = [];
// If the test run hasn't officially begun yet
if (!config.started) {
// Record the time of the test run's beginning
config.started = now();
verifyLoggingCallbacks();
// Delete the loose unnamed module if unused.
if (config.modules[0].name === "" && config.modules[0].tests.length === 0) {
config.modules.shift();
}
// Avoid unnecessary information by not logging modules' test environments
for (i = 0, l = config.modules.length; i < l; i++) {
modulesLog.push({
name: config.modules[i].name,
tests: config.modules[i].tests
});
}
// The test run is officially beginning now
runLoggingCallbacks("begin", {
totalTests: Test.count,
modules: modulesLog
});
}
config.blocking = false;
process(true);
}
function process(last) {
function next() {
process(last);
}
var start = now();
config.depth = ( config.depth || 0 ) + 1;
while (config.queue.length && !config.blocking) {
if (!defined.setTimeout || config.updateRate <= 0 ||
( ( now() - start ) < config.updateRate )) {
if (config.current) {
// Reset async tracking for each phase of the Test lifecycle
config.current.usedAsync = false;
}
config.queue.shift()();
} else {
setTimeout(next, 13);
break;
}
}
config.depth--;
if (last && !config.blocking && !config.queue.length && config.depth === 0) {
done();
}
}
function pauseProcessing() {
config.blocking = true;
if (config.testTimeout && defined.setTimeout) {
clearTimeout(config.timeout);
config.timeout = setTimeout(function () {
if (config.current) {
config.current.semaphore = 0;
QUnit.pushFailure("Test timed out", sourceFromStacktrace(2));
} else {
throw new Error("Test timed out");
}
resumeProcessing();
}, config.testTimeout);
}
}
function resumeProcessing() {
runStarted = true;
// A slight delay to allow this iteration of the event loop to finish (more assertions, etc.)
if (defined.setTimeout) {
setTimeout(function () {
if (config.current && config.current.semaphore > 0) {
return;
}
if (config.timeout) {
clearTimeout(config.timeout);
}
begin();
}, 13);
} else {
begin();
}
}
function done() {
var runtime, passed;
config.autorun = true;
// Log the last module results
if (config.previousModule) {
runLoggingCallbacks("moduleDone", {
name: config.previousModule.name,
tests: config.previousModule.tests,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all,
runtime: now() - config.moduleStats.started
});
}
delete config.previousModule;
runtime = now() - config.started;
passed = config.stats.all - config.stats.bad;
runLoggingCallbacks("done", {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
});
}
function Test(settings) {
var i, l;
++Test.count;
extend(this, settings);
this.assertions = [];
this.semaphore = 0;
this.usedAsync = false;
this.module = config.currentModule;
this.stack = sourceFromStacktrace(3);
// Register unique strings
for (i = 0, l = this.module.tests; i < l.length; i++) {
if (this.module.tests[i].name === this.testName) {
this.testName += " ";
}
}
this.testId = generateHash(this.module.name, this.testName);
this.module.tests.push({
name: this.testName,
testId: this.testId
});
if (settings.skip) {
// Skipped tests will fully ignore any sent callback
this.callback = function () {
};
this.async = false;
this.expected = 0;
} else {
this.assert = new Assert(this);
}
}
Test.count = 0;
Test.prototype = {
before: function () {
if (
// Emit moduleStart when we're switching from one module to another
this.module !== config.previousModule ||
// They could be equal (both undefined) but if the previousModule property doesn't
// yet exist it means this is the first test in a suite that isn't wrapped in a
// module, in which case we'll just emit a moduleStart event for 'undefined'.
// Without this, reporters can get testStart before moduleStart which is a problem.
!hasOwn.call(config, "previousModule")
) {
if (hasOwn.call(config, "previousModule")) {
runLoggingCallbacks("moduleDone", {
name: config.previousModule.name,
tests: config.previousModule.tests,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all,
runtime: now() - config.moduleStats.started
});
}
config.previousModule = this.module;
config.moduleStats = {all: 0, bad: 0, started: now()};
runLoggingCallbacks("moduleStart", {
name: this.module.name,
tests: this.module.tests
});
}
config.current = this;
if (this.module.testEnvironment) {
delete this.module.testEnvironment.beforeEach;
delete this.module.testEnvironment.afterEach;
}
this.testEnvironment = extend({}, this.module.testEnvironment);
this.started = now();
runLoggingCallbacks("testStart", {
name: this.testName,
module: this.module.name,
testId: this.testId
});
if (!config.pollution) {
saveGlobal();
}
},
run: function () {
var promise;
config.current = this;
if (this.async) {
QUnit.stop();
}
this.callbackStarted = now();
if (config.notrycatch) {
promise = this.callback.call(this.testEnvironment, this.assert);
this.resolvePromise(promise);
return;
}
try {
promise = this.callback.call(this.testEnvironment, this.assert);
this.resolvePromise(promise);
} catch (e) {
this.pushFailure("Died on test #" + ( this.assertions.length + 1 ) + " " +
this.stack + ": " + ( e.message || e ), extractStacktrace(e, 0));
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if (config.blocking) {
QUnit.start();
}
}
},
after: function () {
checkPollution();
},
queueHook: function (hook, hookName) {
var promise,
test = this;
return function runHook() {
config.current = test;
if (config.notrycatch) {
promise = hook.call(test.testEnvironment, test.assert);
test.resolvePromise(promise, hookName);
return;
}
try {
promise = hook.call(test.testEnvironment, test.assert);
test.resolvePromise(promise, hookName);
} catch (error) {
test.pushFailure(hookName + " failed on " + test.testName + ": " +
( error.message || error ), extractStacktrace(error, 0));
}
};
},
// Currently only used for module level hooks, can be used to add global level ones
hooks: function (handler) {
var hooks = [];
// Hooks are ignored on skipped tests
if (this.skip) {
return hooks;
}
if (this.module.testEnvironment &&
QUnit.objectType(this.module.testEnvironment[handler]) === "function") {
hooks.push(this.queueHook(this.module.testEnvironment[handler], handler));
}
return hooks;
},
finish: function () {
config.current = this;
if (config.requireExpects && this.expected === null) {
this.pushFailure("Expected number of assertions to be defined, but expect() was " +
"not called.", this.stack);
} else if (this.expected !== null && this.expected !== this.assertions.length) {
this.pushFailure("Expected " + this.expected + " assertions, but " +
this.assertions.length + " were run", this.stack);
} else if (this.expected === null && !this.assertions.length) {
this.pushFailure("Expected at least one assertion, but none were run - call " +
"expect(0) to accept zero assertions.", this.stack);
}
var i,
bad = 0;
this.runtime = now() - this.started;
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
for (i = 0; i < this.assertions.length; i++) {
if (!this.assertions[i].result) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
runLoggingCallbacks("testDone", {
name: this.testName,
module: this.module.name,
skipped: !!this.skip,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length,
runtime: this.runtime,
// HTML Reporter use
assertions: this.assertions,
testId: this.testId,
// Source of Test
source: this.stack,
// DEPRECATED: this property will be removed in 2.0.0, use runtime instead
duration: this.runtime
});
// QUnit.reset() is deprecated and will be replaced for a new
// fixture reset function on QUnit 2.0/2.1.
// It's still called here for backwards compatibility handling
QUnit.reset();
config.current = undefined;
},
queue: function () {
var bad,
test = this;
if (!this.valid()) {
return;
}
function run() {
// each of these can by async
synchronize([
function () {
test.before();
},
test.hooks("beforeEach"),
function () {
test.run();
},
test.hooks("afterEach").reverse(),
function () {
test.after();
},
function () {
test.finish();
}
]);
}
// `bad` initialized at top of scope
// defer when previous test run passed, if storage is available
bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-test-" + this.module.name + "-" + this.testName);
if (bad) {
run();
} else {
synchronize(run, true);
}
},
push: function (result, actual, expected, message, negative) {
var source,
details = {
module: this.module.name,
name: this.testName,
result: result,
message: message,
actual: actual,
expected: expected,
testId: this.testId,
negative: negative || false,
runtime: now() - this.started
};
if (!result) {
source = sourceFromStacktrace();
if (source) {
details.source = source;
}
}
runLoggingCallbacks("log", details);
this.assertions.push({
result: !!result,
message: message
});
},
pushFailure: function (message, source, actual) {
if (!( this instanceof Test )) {
throw new Error("pushFailure() assertion outside test context, was " +
sourceFromStacktrace(2));
}
var details = {
module: this.module.name,
name: this.testName,
result: false,
message: message || "error",
actual: actual || null,
testId: this.testId,
runtime: now() - this.started
};
if (source) {
details.source = source;
}
runLoggingCallbacks("log", details);
this.assertions.push({
result: false,
message: message
});
},
resolvePromise: function (promise, phase) {
var then, message,
test = this;
if (promise != null) {
then = promise.then;
if (QUnit.objectType(then) === "function") {
QUnit.stop();
then.call(
promise,
function () {
QUnit.start();
},
function (error) {
message = "Promise rejected " +
( !phase ? "during" : phase.replace(/Each$/, "") ) +
" " + test.testName + ": " + ( error.message || error );
test.pushFailure(message, extractStacktrace(error, 0));
// else next test will carry the responsibility
saveGlobal();
// Unblock
QUnit.start();
}
);
}
}
},
valid: function () {
var include,
filter = config.filter && config.filter.toLowerCase(),
module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(),
fullName = ( this.module.name + ": " + this.testName ).toLowerCase();
// Internally-generated tests are always valid
if (this.callback && this.callback.validTest) {
return true;
}
if (config.testId.length > 0 && inArray(this.testId, config.testId) < 0) {
return false;
}
if (module && ( !this.module.name || this.module.name.toLowerCase() !== module )) {
return false;
}
if (!filter) {
return true;
}
include = filter.charAt(0) !== "!";
if (!include) {
filter = filter.slice(1);
}
// If the filter matches, we need to honour include
if (fullName.indexOf(filter) !== -1) {
return include;
}
// Otherwise, do the opposite
return !include;
}
};
// Resets the test setup. Useful for tests that modify the DOM.
/*
DEPRECATED: Use multiple tests instead of resetting inside a test.
Use testStart or testDone for custom cleanup.
This method will throw an error in 2.0, and will be removed in 2.1
*/
QUnit.reset = function () {
// Return on non-browser environments
// This is necessary to not break on node tests
if (!defined.document) {
return;
}
var fixture = defined.document && document.getElementById &&
document.getElementById("qunit-fixture");
if (fixture) {
fixture.innerHTML = config.fixture;
}
};
QUnit.pushFailure = function () {
if (!QUnit.config.current) {
throw new Error("pushFailure() assertion outside test context, in " +
sourceFromStacktrace(2));
}
// Gets current test obj
var currentTest = QUnit.config.current;
return currentTest.pushFailure.apply(currentTest, arguments);
};
// Based on Java's String.hashCode, a simple but not
// rigorously collision resistant hashing function
function generateHash(module, testName) {
var hex,
i = 0,
hash = 0,
str = module + "\x1C" + testName,
len = str.length;
for (; i < len; i++) {
hash = ( ( hash << 5 ) - hash ) + str.charCodeAt(i);
hash |= 0;
}
// Convert the possibly negative integer hash code into an 8 character hex string, which isn't
// strictly necessary but increases user understanding that the id is a SHA-like hash
hex = ( 0x100000000 + hash ).toString(16);
if (hex.length < 8) {
hex = "0000000" + hex;
}
return hex.slice(-8);
}
function synchronize(callback, last) {
if (QUnit.objectType(callback) === "array") {
while (callback.length) {
synchronize(callback.shift());
}
return;
}
config.queue.push(callback);
if (config.autorun && !config.blocking) {
process(last);
}
}
function saveGlobal() {
config.pollution = [];
if (config.noglobals) {
for (var key in global) {
if (hasOwn.call(global, key)) {
// in Opera sometimes DOM element ids show up here, ignore them
if (/^qunit-test-output/.test(key)) {
continue;
}
config.pollution.push(key);
}
}
}
}
function checkPollution() {
var newGlobals,
deletedGlobals,
old = config.pollution;
saveGlobal();
newGlobals = diff(config.pollution, old);
if (newGlobals.length > 0) {
QUnit.pushFailure("Introduced global variable(s): " + newGlobals.join(", "));
}
deletedGlobals = diff(old, config.pollution);
if (deletedGlobals.length > 0) {
QUnit.pushFailure("Deleted global variable(s): " + deletedGlobals.join(", "));
}
}
// Will be exposed as QUnit.asyncTest
function asyncTest(testName, expected, callback) {
if (arguments.length === 2) {
callback = expected;
expected = null;
}
QUnit.test(testName, expected, callback, true);
}
// Will be exposed as QUnit.test
function test(testName, expected, callback, async) {
var newTest;
if (arguments.length === 2) {
callback = expected;
expected = null;
}
newTest = new Test({
testName: testName,
expected: expected,
async: async,
callback: callback
});
newTest.queue();
}
// Will be exposed as QUnit.skip
function skip(testName) {
var test = new Test({
testName: testName,
skip: true
});
test.queue();
}
function Assert(testContext) {
this.test = testContext;
}
// Assert helpers
QUnit.assert = Assert.prototype = {
// Specify the number of expected assertions to guarantee that failed test
// (no assertions are run at all) don't slip through.
expect: function (asserts) {
if (arguments.length === 1) {
this.test.expected = asserts;
} else {
return this.test.expected;
}
},
// Increment this Test's semaphore counter, then return a single-use function that
// decrements that counter a maximum of once.
async: function () {
var test = this.test,
popped = false;
test.semaphore += 1;
test.usedAsync = true;
pauseProcessing();
return function done() {
if (!popped) {
test.semaphore -= 1;
popped = true;
resumeProcessing();
} else {
test.pushFailure("Called the callback returned from `assert.async` more than once",
sourceFromStacktrace(2));
}
};
},
// Exports test.push() to the user API
push: function (/* result, actual, expected, message, negative */) {
var assert = this,
currentTest = ( assert instanceof Assert && assert.test ) || QUnit.config.current;
// Backwards compatibility fix.
// Allows the direct use of global exported assertions and QUnit.assert.*
// Although, it's use is not recommended as it can leak assertions
// to other tests from async tests, because we only get a reference to the current test,
// not exactly the test where assertion were intended to be called.
if (!currentTest) {
throw new Error("assertion outside test context, in " + sourceFromStacktrace(2));
}
if (currentTest.usedAsync === true && currentTest.semaphore === 0) {
currentTest.pushFailure("Assertion after the final `assert.async` was resolved",
sourceFromStacktrace(2));
// Allow this assertion to continue running anyway...
}
if (!( assert instanceof Assert )) {
assert = currentTest.assert;
}
return assert.test.push.apply(assert.test, arguments);
},
ok: function (result, message) {
message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
QUnit.dump.parse(result) );
this.push(!!result, result, true, message);
},
notOk: function (result, message) {
message = message || ( !result ? "okay" : "failed, expected argument to be falsy, was: " +
QUnit.dump.parse(result) );
this.push(!result, result, false, message, true);
},
equal: function (actual, expected, message) {
/*jshint eqeqeq:false */
this.push(expected == actual, actual, expected, message);
},
notEqual: function (actual, expected, message) {
/*jshint eqeqeq:false */
this.push(expected != actual, actual, expected, message, true);
},
propEqual: function (actual, expected, message) {
actual = objectValues(actual);
expected = objectValues(expected);
this.push(QUnit.equiv(actual, expected), actual, expected, message);
},
notPropEqual: function (actual, expected, message) {
actual = objectValues(actual);
expected = objectValues(expected);
this.push(!QUnit.equiv(actual, expected), actual, expected, message, true);
},
deepEqual: function (actual, expected, message) {
this.push(QUnit.equiv(actual, expected), actual, expected, message);
},
notDeepEqual: function (actual, expected, message) {
this.push(!QUnit.equiv(actual, expected), actual, expected, message, true);
},
strictEqual: function (actual, expected, message) {
this.push(expected === actual, actual, expected, message);
},
notStrictEqual: function (actual, expected, message) {
this.push(expected !== actual, actual, expected, message, true);
},
"throws": function (block, expected, message) {
var actual, expectedType,
expectedOutput = expected,
ok = false,
currentTest = ( this instanceof Assert && this.test ) || QUnit.config.current;
// 'expected' is optional unless doing string comparison
if (message == null && typeof expected === "string") {
message = expected;
expected = null;
}
currentTest.ignoreGlobalErrors = true;
try {
block.call(currentTest.testEnvironment);
} catch (e) {
actual = e;
}
currentTest.ignoreGlobalErrors = false;
if (actual) {
expectedType = QUnit.objectType(expected);
// we don't want to validate thrown error
if (!expected) {
ok = true;
expectedOutput = null;
// expected is a regexp
} else if (expectedType === "regexp") {
ok = expected.test(errorString(actual));
// expected is a string
} else if (expectedType === "string") {
ok = expected === errorString(actual);
// expected is a constructor, maybe an Error constructor
} else if (expectedType === "function" && actual instanceof expected) {
ok = true;
// expected is an Error object
} else if (expectedType === "object") {
ok = actual instanceof expected.constructor &&
actual.name === expected.name &&
actual.message === expected.message;
// expected is a validation function which returns true if validation passed
} else if (expectedType === "function" && expected.call({}, actual) === true) {
expectedOutput = null;
ok = true;
}
}
currentTest.assert.push(ok, actual, expectedOutput, message);
}
};
// Provide an alternative to assert.throws(), for enviroments that consider throws a reserved word
// Known to us are: Closure Compiler, Narwhal
(function () {
/*jshint sub:true */
Assert.prototype.raises = Assert.prototype["throws"];
}());
function errorString(error) {
var name, message,
resultErrorString = error.toString();
if (resultErrorString.substring(0, 7) === "[object") {
name = error.name ? error.name.toString() : "Error";
message = error.message ? error.message.toString() : "";
if (name && message) {
return name + ": " + message;
} else if (name) {
return name;
} else if (message) {
return message;
} else {
return "Error";
}
} else {
return resultErrorString;
}
}
// Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = (function () {
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = QUnit.objectType(o);
if (prop) {
if (QUnit.objectType(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
// the real equiv function
var innerEquiv,
// stack to decide between skip/abort functions
callers = [],
// stack to avoiding loops from circular referencing
parents = [],
parentsB = [],
getProto = Object.getPrototypeOf || function (obj) {
/* jshint camelcase: false, proto: true */
return obj.__proto__;
},
callbacks = (function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
/*jshint eqeqeq:false */
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotation VS 'new' annotation of a
// declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"nan": function (b) {
return isNaN(b);
},
"date": function (b, a) {
return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf();
},
"regexp": function (b, a) {
return QUnit.objectType(b) === "regexp" &&
// the regex itself
a.source === b.source &&
// and its modifiers
a.global === b.global &&
// (gmi) ...
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline &&
a.sticky === b.sticky;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function": function () {
var caller = callers[callers.length - 1];
return caller !== Object && typeof caller !== "undefined";
},
"array": function (b, a) {
var i, j, len, loop, aCircular, bCircular;
// b could be an object literal here
if (QUnit.objectType(b) !== "array") {
return false;
}
len = a.length;
if (len !== b.length) {
// safe and faster
return false;
}
// track reference to avoid circular references
parents.push(a);
parentsB.push(b);
for (i = 0; i < len; i++) {
loop = false;
for (j = 0; j < parents.length; j++) {
aCircular = parents[j] === a[i];
bCircular = parentsB[j] === b[i];
if (aCircular || bCircular) {
if (a[i] === b[i] || aCircular && bCircular) {
loop = true;
} else {
parents.pop();
parentsB.pop();
return false;
}
}
}
if (!loop && !innerEquiv(a[i], b[i])) {
parents.pop();
parentsB.pop();
return false;
}
}
parents.pop();
parentsB.pop();
return true;
},
"set": function (b, a) {
var aArray, bArray;
// b could be any object here
if (QUnit.objectType(b) !== "set") {
return false;
}
aArray = [];
a.forEach(function (v) {
aArray.push(v);
});
bArray = [];
b.forEach(function (v) {
bArray.push(v);
});
return innerEquiv(bArray, aArray);
},
"map": function (b, a) {
var aArray, bArray;
// b could be any object here
if (QUnit.objectType(b) !== "map") {
return false;
}
aArray = [];
a.forEach(function (v, k) {
aArray.push([k, v]);
});
bArray = [];
b.forEach(function (v, k) {
bArray.push([k, v]);
});
return innerEquiv(bArray, aArray);
},
"object": function (b, a) {
/*jshint forin:false */
var i, j, loop, aCircular, bCircular,
// Default to true
eq = true,
aProperties = [],
bProperties = [];
// comparing constructors is more strict than using
// instanceof
if (a.constructor !== b.constructor) {
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if (!( ( getProto(a) === null && getProto(b) === Object.prototype ) ||
( getProto(b) === null && getProto(a) === Object.prototype ) )) {
return false;
}
}
// stack constructor before traversing properties
callers.push(a.constructor);
// track reference to avoid circular references
parents.push(a);
parentsB.push(b);
// be strict: don't ensure hasOwnProperty and go deep
for (i in a) {
loop = false;
for (j = 0; j < parents.length; j++) {
aCircular = parents[j] === a[i];
bCircular = parentsB[j] === b[i];
if (aCircular || bCircular) {
if (a[i] === b[i] || aCircular && bCircular) {
loop = true;
} else {
eq = false;
break;
}
}
}
aProperties.push(i);
if (!loop && !innerEquiv(a[i], b[i])) {
eq = false;
break;
}
}
parents.pop();
parentsB.pop();
callers.pop(); // unstack, we are done
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq && innerEquiv(aProperties.sort(), bProperties.sort());
}
};
}());
innerEquiv = function () { // can take multiple arguments
var args = [].slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return ( (function (a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined" ||
typeof b === "undefined" ||
QUnit.objectType(a) !== QUnit.objectType(b)) {
// don't lose time with error prone cases
return false;
} else {
return bindCallbacks(a, callbacks, [b, a]);
}
// apply transition with (1..n) arguments
}(args[0], args[1]) ) &&
innerEquiv.apply(this, args.splice(1, args.length - 1)) );
};
return innerEquiv;
}());
// Based on jsDump by Ariel Flesler
// http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html
QUnit.dump = (function () {
function quote(str) {
return "\"" + str.toString().replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
}
function literal(o) {
return o + "";
}
function join(pre, arr, post) {
var s = dump.separator(),
base = dump.indent(),
inner = dump.indent(1);
if (arr.join) {
arr = arr.join("," + s + inner);
}
if (!arr) {
return pre + post;
}
return [pre, inner + arr, base + post].join(s);
}
function array(arr, stack) {
var i = arr.length,
ret = new Array(i);
if (dump.maxDepth && dump.depth > dump.maxDepth) {
return "[object Array]";
}
this.up();
while (i--) {
ret[i] = this.parse(arr[i], undefined, stack);
}
this.down();
return join("[", ret, "]");
}
var reName = /^function (\w+)/,
dump = {
// objType is used mostly internally, you can fix a (custom) type in advance
parse: function (obj, objType, stack) {
stack = stack || [];
var res, parser, parserType,
inStack = inArray(obj, stack);
if (inStack !== -1) {
return "recursion(" + ( inStack - stack.length ) + ")";
}
objType = objType || this.typeOf(obj);
parser = this.parsers[objType];
parserType = typeof parser;
if (parserType === "function") {
stack.push(obj);
res = parser.call(this, obj, stack);
stack.pop();
return res;
}
return ( parserType === "string" ) ? parser : this.parsers.error;
},
typeOf: function (obj) {
var type;
if (obj === null) {
type = "null";
} else if (typeof obj === "undefined") {
type = "undefined";
} else if (QUnit.is("regexp", obj)) {
type = "regexp";
} else if (QUnit.is("date", obj)) {
type = "date";
} else if (QUnit.is("function", obj)) {
type = "function";
} else if (obj.setInterval !== undefined &&
obj.document !== undefined &&
obj.nodeType === undefined) {
type = "window";
} else if (obj.nodeType === 9) {
type = "document";
} else if (obj.nodeType) {
type = "node";
} else if (
// native arrays
toString.call(obj) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && obj.item !== undefined &&
( obj.length ? obj.item(0) === obj[0] : ( obj.item(0) === null &&
obj[0] === undefined ) ) )
) {
type = "array";
} else if (obj.constructor === Error.prototype.constructor) {
type = "error";
} else {
type = typeof obj;
}
return type;
},
separator: function () {
return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " ";
},
// extra can be a number, shortcut for increasing-calling-decreasing
indent: function (extra) {
if (!this.multiline) {
return "";
}
var chr = this.indentChar;
if (this.HTML) {
chr = chr.replace(/\t/g, " ").replace(/ /g, " ");
}
return new Array(this.depth + ( extra || 0 )).join(chr);
},
up: function (a) {
this.depth += a || 1;
},
down: function (a) {
this.depth -= a || 1;
},
setParser: function (name, parser) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote: quote,
literal: literal,
join: join,
//
depth: 1,
maxDepth: QUnit.config.maxDepth,
// This is the list of parsers, to modify them, use dump.setParser
parsers: {
window: "[Window]",
document: "[Document]",
error: function (error) {
return "Error(\"" + error.message + "\")";
},
unknown: "[Unknown]",
"null": "null",
"undefined": "undefined",
"function": function (fn) {
var ret = "function",
// functions never have name in IE
name = "name" in fn ? fn.name : ( reName.exec(fn) || [] )[1];
if (name) {
ret += " " + name;
}
ret += "( ";
ret = [ret, dump.parse(fn, "functionArgs"), "){"].join("");
return join(ret, dump.parse(fn, "functionCode"), "}");
},
array: array,
nodelist: array,
"arguments": array,
object: function (map, stack) {
var keys, key, val, i, nonEnumerableProperties,
ret = [];
if (dump.maxDepth && dump.depth > dump.maxDepth) {
return "[object Object]";
}
dump.up();
keys = [];
for (key in map) {
keys.push(key);
}
// Some properties are not always enumerable on Error objects.
nonEnumerableProperties = ["message", "name"];
for (i in nonEnumerableProperties) {
key = nonEnumerableProperties[i];
if (key in map && inArray(key, keys) < 0) {
keys.push(key);
}
}
keys.sort();
for (i = 0; i < keys.length; i++) {
key = keys[i];
val = map[key];
ret.push(dump.parse(key, "key") + ": " +
dump.parse(val, undefined, stack));
}
dump.down();
return join("{", ret, "}");
},
node: function (node) {
var len, i, val,
open = dump.HTML ? "<" : "<",
close = dump.HTML ? ">" : ">",
tag = node.nodeName.toLowerCase(),
ret = open + tag,
attrs = node.attributes;
if (attrs) {
for (i = 0, len = attrs.length; i < len; i++) {
val = attrs[i].nodeValue;
// IE6 includes all attributes in .attributes, even ones not explicitly
// set. Those have values like undefined, null, 0, false, "" or
// "inherit".
if (val && val !== "inherit") {
ret += " " + attrs[i].nodeName + "=" +
dump.parse(val, "attribute");
}
}
}
ret += close;
// Show content of TextNode or CDATASection
if (node.nodeType === 3 || node.nodeType === 4) {
ret += node.nodeValue;
}
return ret + open + "/" + tag + close;
},
// function calls it internally, it's the arguments part of the function
functionArgs: function (fn) {
var args,
l = fn.length;
if (!l) {
return "";
}
args = new Array(l);
while (l--) {
// 97 is 'a'
args[l] = String.fromCharCode(97 + l);
}
return " " + args.join(", ") + " ";
},
// object calls it internally, the key part of an item in a map
key: quote,
// function calls it internally, it's the content of the function
functionCode: "[code]",
// node calls it internally, it's an html attribute value
attribute: quote,
string: quote,
date: quote,
regexp: literal,
number: literal,
"boolean": literal
},
// if true, entities are escaped ( <, >, \t, space and \n )
HTML: false,
// indentation unit
indentChar: " ",
// if true, items in a collection, are separated by a \n, else just a space.
multiline: true
};
return dump;
}());
// back compat
QUnit.jsDump = QUnit.dump;
// For browser, export only select globals
if (defined.document) {
// Deprecated
// Extend assert methods to QUnit and Global scope through Backwards compatibility
(function () {
var i,
assertions = Assert.prototype;
function applyCurrent(current) {
return function () {
var assert = new Assert(QUnit.config.current);
current.apply(assert, arguments);
};
}
for (i in assertions) {
QUnit[i] = applyCurrent(assertions[i]);
}
})();
(function () {
var i, l,
keys = [
"test",
"module",
"expect",
"asyncTest",
"start",
"stop",
"ok",
"notOk",
"equal",
"notEqual",
"propEqual",
"notPropEqual",
"deepEqual",
"notDeepEqual",
"strictEqual",
"notStrictEqual",
"throws"
];
for (i = 0, l = keys.length; i < l; i++) {
window[keys[i]] = QUnit[keys[i]];
}
})();
window.QUnit = QUnit;
}
// For nodejs
if (typeof module !== "undefined" && module && module.exports) {
module.exports = QUnit;
// For consistency with CommonJS environments' exports
module.exports.QUnit = QUnit;
}
// For CommonJS with exports, but without module.exports, like Rhino
if (typeof exports !== "undefined" && exports) {
exports.QUnit = QUnit;
}
if (typeof define === "function" && define.amd) {
define(function () {
return QUnit;
});
QUnit.config.autostart = false;
}
/*
* This file is a modified version of google-diff-match-patch's JavaScript implementation
* (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
* modifications are licensed as more fully set forth in LICENSE.txt.
*
* The original source of google-diff-match-patch is attributable and licensed as follows:
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* 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.
*
* More Info:
* https://code.google.com/p/google-diff-match-patch/
*
* Usage: QUnit.diff(expected, actual)
*
*/
QUnit.diff = ( function () {
function DiffMatchPatch() {
}
// DIFF FUNCTIONS
/**
* The data structure representing a diff is an array of tuples:
* [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
*/
var DIFF_DELETE = -1,
DIFF_INSERT = 1,
DIFF_EQUAL = 0;
/**
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean=} optChecklines Optional speedup flag. If present and false,
* then don't run a line-level diff first to identify the changed areas.
* Defaults to true, which does a faster, slightly less optimal diff.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
*/
DiffMatchPatch.prototype.DiffMain = function (text1, text2, optChecklines) {
var deadline, checklines, commonlength,
commonprefix, commonsuffix, diffs;
// The diff must be complete in up to 1 second.
deadline = ( new Date() ).getTime() + 1000;
// Check for null inputs.
if (text1 === null || text2 === null) {
throw new Error("Null input. (DiffMain)");
}
// Check for equality (speedup).
if (text1 === text2) {
if (text1) {
return [
[DIFF_EQUAL, text1]
];
}
return [];
}
if (typeof optChecklines === "undefined") {
optChecklines = true;
}
checklines = optChecklines;
// Trim off common prefix (speedup).
commonlength = this.diffCommonPrefix(text1, text2);
commonprefix = text1.substring(0, commonlength);
text1 = text1.substring(commonlength);
text2 = text2.substring(commonlength);
// Trim off common suffix (speedup).
commonlength = this.diffCommonSuffix(text1, text2);
commonsuffix = text1.substring(text1.length - commonlength);
text1 = text1.substring(0, text1.length - commonlength);
text2 = text2.substring(0, text2.length - commonlength);
// Compute the diff on the middle block.
diffs = this.diffCompute(text1, text2, checklines, deadline);
// Restore the prefix and suffix.
if (commonprefix) {
diffs.unshift([DIFF_EQUAL, commonprefix]);
}
if (commonsuffix) {
diffs.push([DIFF_EQUAL, commonsuffix]);
}
this.diffCleanupMerge(diffs);
return diffs;
};
/**
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupEfficiency = function (diffs) {
var changes, equalities, equalitiesLength, lastequality,
pointer, preIns, preDel, postIns, postDel;
changes = false;
equalities = []; // Stack of indices where equalities are found.
equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
pointer = 0; // Index of current position.
// Is there an insertion operation before the last equality.
preIns = false;
// Is there a deletion operation before the last equality.
preDel = false;
// Is there an insertion operation after the last equality.
postIns = false;
// Is there a deletion operation after the last equality.
postDel = false;
while (pointer < diffs.length) {
// Equality found.
if (diffs[pointer][0] === DIFF_EQUAL) {
if (diffs[pointer][1].length < 4 && ( postIns || postDel )) {
// Candidate found.
equalities[equalitiesLength++] = pointer;
preIns = postIns;
preDel = postDel;
lastequality = diffs[pointer][1];
} else {
// Not a candidate, and can never become one.
equalitiesLength = 0;
lastequality = null;
}
postIns = postDel = false;
// An insertion or deletion.
} else {
if (diffs[pointer][0] === DIFF_DELETE) {
postDel = true;
} else {
postIns = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if (lastequality && ( ( preIns && preDel && postIns && postDel ) ||
( ( lastequality.length < 2 ) &&
( preIns + preDel + postIns + postDel ) === 3 ) )) {
// Duplicate record.
diffs.splice(
equalities[equalitiesLength - 1],
0,
[DIFF_DELETE, lastequality]
);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
equalitiesLength--; // Throw away the equality we just deleted;
lastequality = null;
if (preIns && preDel) {
// No changes made which could affect previous entry, keep going.
postIns = postDel = true;
equalitiesLength = 0;
} else {
equalitiesLength--; // Throw away the previous equality.
pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
postIns = postDel = false;
}
changes = true;
}
}
pointer++;
}
if (changes) {
this.diffCleanupMerge(diffs);
}
};
/**
* Convert a diff array into a pretty HTML report.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
* @param {integer} string to be beautified.
* @return {string} HTML representation.
*/
DiffMatchPatch.prototype.diffPrettyHtml = function (diffs) {
var op, data, x,
html = [];
for (x = 0; x < diffs.length; x++) {
op = diffs[x][0]; // Operation (insert, delete, equal)
data = diffs[x][1]; // Text of change.
switch (op) {
case DIFF_INSERT:
html[x] = "<ins>" + data + "</ins>";
break;
case DIFF_DELETE:
html[x] = "<del>" + data + "</del>";
break;
case DIFF_EQUAL:
html[x] = "<span>" + data + "</span>";
break;
}
}
return html.join("");
};
/**
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
*/
DiffMatchPatch.prototype.diffCommonPrefix = function (text1, text2) {
var pointermid, pointermax, pointermin, pointerstart;
// Quick check for common null cases.
if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
pointermin = 0;
pointermax = Math.min(text1.length, text2.length);
pointermid = pointermax;
pointerstart = 0;
while (pointermin < pointermid) {
if (text1.substring(pointerstart, pointermid) ===
text2.substring(pointerstart, pointermid)) {
pointermin = pointermid;
pointerstart = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor(( pointermax - pointermin ) / 2 + pointermin);
}
return pointermid;
};
/**
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
*/
DiffMatchPatch.prototype.diffCommonSuffix = function (text1, text2) {
var pointermid, pointermax, pointermin, pointerend;
// Quick check for common null cases.
if (!text1 || !text2 ||
text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
return 0;
}
// Binary search.
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
pointermin = 0;
pointermax = Math.min(text1.length, text2.length);
pointermid = pointermax;
pointerend = 0;
while (pointermin < pointermid) {
if (text1.substring(text1.length - pointermid, text1.length - pointerend) ===
text2.substring(text2.length - pointermid, text2.length - pointerend)) {
pointermin = pointermid;
pointerend = pointermin;
} else {
pointermax = pointermid;
}
pointermid = Math.floor(( pointermax - pointermin ) / 2 + pointermin);
}
return pointermid;
};
/**
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Speedup flag. If false, then don't run a
* line-level diff first to identify the changed areas.
* If true, then run a faster, slightly less optimal diff.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffCompute = function (text1, text2, checklines, deadline) {
var diffs, longtext, shorttext, i, hm,
text1A, text2A, text1B, text2B,
midCommon, diffsA, diffsB;
if (!text1) {
// Just add some text (speedup).
return [
[DIFF_INSERT, text2]
];
}
if (!text2) {
// Just delete some text (speedup).
return [
[DIFF_DELETE, text1]
];
}
longtext = text1.length > text2.length ? text1 : text2;
shorttext = text1.length > text2.length ? text2 : text1;
i = longtext.indexOf(shorttext);
if (i !== -1) {
// Shorter text is inside the longer text (speedup).
diffs = [
[DIFF_INSERT, longtext.substring(0, i)],
[DIFF_EQUAL, shorttext],
[DIFF_INSERT, longtext.substring(i + shorttext.length)]
];
// Swap insertions for deletions if diff is reversed.
if (text1.length > text2.length) {
diffs[0][0] = diffs[2][0] = DIFF_DELETE;
}
return diffs;
}
if (shorttext.length === 1) {
// Single character string.
// After the previous speedup, the character can't be an equality.
return [
[DIFF_DELETE, text1],
[DIFF_INSERT, text2]
];
}
// Check to see if the problem can be split in two.
hm = this.diffHalfMatch(text1, text2);
if (hm) {
// A half-match was found, sort out the return data.
text1A = hm[0];
text1B = hm[1];
text2A = hm[2];
text2B = hm[3];
midCommon = hm[4];
// Send both pairs off for separate processing.
diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
// Merge the results.
return diffsA.concat([
[DIFF_EQUAL, midCommon]
], diffsB);
}
if (checklines && text1.length > 100 && text2.length > 100) {
return this.diffLineMode(text1, text2, deadline);
}
return this.diffBisect(text1, text2, deadline);
};
/**
* Do the two texts share a substring which is at least half the length of the
* longer text?
* This speedup can produce non-minimal diffs.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or null if there was no match.
* @private
*/
DiffMatchPatch.prototype.diffHalfMatch = function (text1, text2) {
var longtext, shorttext, dmp,
text1A, text2B, text2A, text1B, midCommon,
hm1, hm2, hm;
longtext = text1.length > text2.length ? text1 : text2;
shorttext = text1.length > text2.length ? text2 : text1;
if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
return null; // Pointless.
}
dmp = this; // 'this' becomes 'window' in a closure.
/**
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or null if there was no match.
* @private
*/
function diffHalfMatchI(longtext, shorttext, i) {
var seed, j, bestCommon, prefixLength, suffixLength,
bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
// Start with a 1/4 length substring at position i as a seed.
seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
j = -1;
bestCommon = "";
while (( j = shorttext.indexOf(seed, j + 1) ) !== -1) {
prefixLength = dmp.diffCommonPrefix(longtext.substring(i),
shorttext.substring(j));
suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i),
shorttext.substring(0, j));
if (bestCommon.length < suffixLength + prefixLength) {
bestCommon = shorttext.substring(j - suffixLength, j) +
shorttext.substring(j, j + prefixLength);
bestLongtextA = longtext.substring(0, i - suffixLength);
bestLongtextB = longtext.substring(i + prefixLength);
bestShorttextA = shorttext.substring(0, j - suffixLength);
bestShorttextB = shorttext.substring(j + prefixLength);
}
}
if (bestCommon.length * 2 >= longtext.length) {
return [bestLongtextA, bestLongtextB,
bestShorttextA, bestShorttextB, bestCommon
];
} else {
return null;
}
}
// First check if the second quarter is the seed for a half-match.
hm1 = diffHalfMatchI(longtext, shorttext,
Math.ceil(longtext.length / 4));
// Check again based on the third quarter.
hm2 = diffHalfMatchI(longtext, shorttext,
Math.ceil(longtext.length / 2));
if (!hm1 && !hm2) {
return null;
} else if (!hm2) {
hm = hm1;
} else if (!hm1) {
hm = hm2;
} else {
// Both matched. Select the longest.
hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
}
// A half-match was found, sort out the return data.
text1A, text1B, text2A, text2B;
if (text1.length > text2.length) {
text1A = hm[0];
text1B = hm[1];
text2A = hm[2];
text2B = hm[3];
} else {
text2A = hm[0];
text2B = hm[1];
text1A = hm[2];
text1B = hm[3];
}
midCommon = hm[4];
return [text1A, text1B, text2A, text2B, midCommon];
};
/**
* Do a quick line-level diff on both strings, then rediff the parts for
* greater accuracy.
* This speedup can produce non-minimal diffs.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time when the diff should be complete by.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffLineMode = function (text1, text2, deadline) {
var a, diffs, linearray, pointer, countInsert,
countDelete, textInsert, textDelete, j;
// Scan the text on a line-by-line basis first.
a = this.diffLinesToChars(text1, text2);
text1 = a.chars1;
text2 = a.chars2;
linearray = a.lineArray;
diffs = this.DiffMain(text1, text2, false, deadline);
// Convert the diff back to original text.
this.diffCharsToLines(diffs, linearray);
// Eliminate freak matches (e.g. blank lines)
this.diffCleanupSemantic(diffs);
// Rediff any replacement blocks, this time character-by-character.
// Add a dummy entry at the end.
diffs.push([DIFF_EQUAL, ""]);
pointer = 0;
countDelete = 0;
countInsert = 0;
textDelete = "";
textInsert = "";
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
countInsert++;
textInsert += diffs[pointer][1];
break;
case DIFF_DELETE:
countDelete++;
textDelete += diffs[pointer][1];
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (countDelete >= 1 && countInsert >= 1) {
// Delete the offending records and add the merged ones.
diffs.splice(pointer - countDelete - countInsert,
countDelete + countInsert);
pointer = pointer - countDelete - countInsert;
a = this.DiffMain(textDelete, textInsert, false, deadline);
for (j = a.length - 1; j >= 0; j--) {
diffs.splice(pointer, 0, a[j]);
}
pointer = pointer + a.length;
}
countInsert = 0;
countDelete = 0;
textDelete = "";
textInsert = "";
break;
}
pointer++;
}
diffs.pop(); // Remove the dummy entry at the end.
return diffs;
};
/**
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffBisect = function (text1, text2, deadline) {
var text1Length, text2Length, maxD, vOffset, vLength,
v1, v2, x, delta, front, k1start, k1end, k2start,
k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
// Cache the text lengths to prevent multiple calls.
text1Length = text1.length;
text2Length = text2.length;
maxD = Math.ceil(( text1Length + text2Length ) / 2);
vOffset = maxD;
vLength = 2 * maxD;
v1 = new Array(vLength);
v2 = new Array(vLength);
// Setting all elements to -1 is faster in Chrome & Firefox than mixing
// integers and undefined.
for (x = 0; x < vLength; x++) {
v1[x] = -1;
v2[x] = -1;
}
v1[vOffset + 1] = 0;
v2[vOffset + 1] = 0;
delta = text1Length - text2Length;
// If the total number of characters is odd, then the front path will collide
// with the reverse path.
front = ( delta % 2 !== 0 );
// Offsets for start and end of k loop.
// Prevents mapping of space beyond the grid.
k1start = 0;
k1end = 0;
k2start = 0;
k2end = 0;
for (d = 0; d < maxD; d++) {
// Bail out if deadline is reached.
if (( new Date() ).getTime() > deadline) {
break;
}
// Walk the front path one step.
for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
k1Offset = vOffset + k1;
if (k1 === -d || ( k1 !== d && v1[k1Offset - 1] < v1[k1Offset + 1] )) {
x1 = v1[k1Offset + 1];
} else {
x1 = v1[k1Offset - 1] + 1;
}
y1 = x1 - k1;
while (x1 < text1Length && y1 < text2Length &&
text1.charAt(x1) === text2.charAt(y1)) {
x1++;
y1++;
}
v1[k1Offset] = x1;
if (x1 > text1Length) {
// Ran off the right of the graph.
k1end += 2;
} else if (y1 > text2Length) {
// Ran off the bottom of the graph.
k1start += 2;
} else if (front) {
k2Offset = vOffset + delta - k1;
if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
// Mirror x2 onto top-left coordinate system.
x2 = text1Length - v2[k2Offset];
if (x1 >= x2) {
// Overlap detected.
return this.diffBisectSplit(text1, text2, x1, y1, deadline);
}
}
}
}
// Walk the reverse path one step.
for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
k2Offset = vOffset + k2;
if (k2 === -d || ( k2 !== d && v2[k2Offset - 1] < v2[k2Offset + 1] )) {
x2 = v2[k2Offset + 1];
} else {
x2 = v2[k2Offset - 1] + 1;
}
y2 = x2 - k2;
while (x2 < text1Length && y2 < text2Length &&
text1.charAt(text1Length - x2 - 1) ===
text2.charAt(text2Length - y2 - 1)) {
x2++;
y2++;
}
v2[k2Offset] = x2;
if (x2 > text1Length) {
// Ran off the left of the graph.
k2end += 2;
} else if (y2 > text2Length) {
// Ran off the top of the graph.
k2start += 2;
} else if (!front) {
k1Offset = vOffset + delta - k2;
if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
x1 = v1[k1Offset];
y1 = vOffset + x1 - k1Offset;
// Mirror x2 onto top-left coordinate system.
x2 = text1Length - x2;
if (x1 >= x2) {
// Overlap detected.
return this.diffBisectSplit(text1, text2, x1, y1, deadline);
}
}
}
}
}
// Diff took too long and hit the deadline or
// number of diffs equals number of characters, no commonality at all.
return [
[DIFF_DELETE, text1],
[DIFF_INSERT, text2]
];
};
/**
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {!Array.<!DiffMatchPatch.Diff>} Array of diff tuples.
* @private
*/
DiffMatchPatch.prototype.diffBisectSplit = function (text1, text2, x, y, deadline) {
var text1a, text1b, text2a, text2b, diffs, diffsb;
text1a = text1.substring(0, x);
text2a = text2.substring(0, y);
text1b = text1.substring(x);
text2b = text2.substring(y);
// Compute both diffs serially.
diffs = this.DiffMain(text1a, text2a, false, deadline);
diffsb = this.DiffMain(text1b, text2b, false, deadline);
return diffs.concat(diffsb);
};
/**
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupSemantic = function (diffs) {
var changes, equalities, equalitiesLength, lastequality,
pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1,
lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
changes = false;
equalities = []; // Stack of indices where equalities are found.
equalitiesLength = 0; // Keeping our own length var is faster in JS.
/** @type {?string} */
lastequality = null;
// Always equal to diffs[equalities[equalitiesLength - 1]][1]
pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
lengthInsertions1 = 0;
lengthDeletions1 = 0;
// Number of characters that changed after the equality.
lengthInsertions2 = 0;
lengthDeletions2 = 0;
while (pointer < diffs.length) {
if (diffs[pointer][0] === DIFF_EQUAL) { // Equality found.
equalities[equalitiesLength++] = pointer;
lengthInsertions1 = lengthInsertions2;
lengthDeletions1 = lengthDeletions2;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = diffs[pointer][1];
} else { // An insertion or deletion.
if (diffs[pointer][0] === DIFF_INSERT) {
lengthInsertions2 += diffs[pointer][1].length;
} else {
lengthDeletions2 += diffs[pointer][1].length;
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (lastequality && ( lastequality.length <=
Math.max(lengthInsertions1, lengthDeletions1) ) &&
( lastequality.length <= Math.max(lengthInsertions2,
lengthDeletions2) )) {
// Duplicate record.
diffs.splice(
equalities[equalitiesLength - 1],
0,
[DIFF_DELETE, lastequality]
);
// Change second copy to insert.
diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
// Throw away the equality we just deleted.
equalitiesLength--;
// Throw away the previous equality (it needs to be reevaluated).
equalitiesLength--;
pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
// Reset the counters.
lengthInsertions1 = 0;
lengthDeletions1 = 0;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastequality = null;
changes = true;
}
}
pointer++;
}
// Normalize the diff.
if (changes) {
this.diffCleanupMerge(diffs);
}
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 1;
while (pointer < diffs.length) {
if (diffs[pointer - 1][0] === DIFF_DELETE &&
diffs[pointer][0] === DIFF_INSERT) {
deletion = diffs[pointer - 1][1];
insertion = diffs[pointer][1];
overlapLength1 = this.diffCommonOverlap(deletion, insertion);
overlapLength2 = this.diffCommonOverlap(insertion, deletion);
if (overlapLength1 >= overlapLength2) {
if (overlapLength1 >= deletion.length / 2 ||
overlapLength1 >= insertion.length / 2) {
// Overlap found. Insert an equality and trim the surrounding edits.
diffs.splice(
pointer,
0,
[DIFF_EQUAL, insertion.substring(0, overlapLength1)]
);
diffs[pointer - 1][1] =
deletion.substring(0, deletion.length - overlapLength1);
diffs[pointer + 1][1] = insertion.substring(overlapLength1);
pointer++;
}
} else {
if (overlapLength2 >= deletion.length / 2 ||
overlapLength2 >= insertion.length / 2) {
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diffs.splice(
pointer,
0,
[DIFF_EQUAL, deletion.substring(0, overlapLength2)]
);
diffs[pointer - 1][0] = DIFF_INSERT;
diffs[pointer - 1][1] =
insertion.substring(0, insertion.length - overlapLength2);
diffs[pointer + 1][0] = DIFF_DELETE;
diffs[pointer + 1][1] =
deletion.substring(overlapLength2);
pointer++;
}
}
pointer++;
}
pointer++;
}
};
/**
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
*/
DiffMatchPatch.prototype.diffCommonOverlap = function (text1, text2) {
var text1Length, text2Length, textLength,
best, length, pattern, found;
// Cache the text lengths to prevent multiple calls.
text1Length = text1.length;
text2Length = text2.length;
// Eliminate the null case.
if (text1Length === 0 || text2Length === 0) {
return 0;
}
// Truncate the longer string.
if (text1Length > text2Length) {
text1 = text1.substring(text1Length - text2Length);
} else if (text1Length < text2Length) {
text2 = text2.substring(0, text1Length);
}
textLength = Math.min(text1Length, text2Length);
// Quick check for the worst case.
if (text1 === text2) {
return textLength;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
best = 0;
length = 1;
while (true) {
pattern = text1.substring(textLength - length);
found = text2.indexOf(pattern);
if (found === -1) {
return best;
}
length += found;
if (found === 0 || text1.substring(textLength - length) ===
text2.substring(0, length)) {
best = length;
length++;
}
}
};
/**
* Split two texts into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {{chars1: string, chars2: string, lineArray: !Array.<string>}}
* An object containing the encoded text1, the encoded text2 and
* the array of unique strings.
* The zeroth element of the array of unique strings is intentionally blank.
* @private
*/
DiffMatchPatch.prototype.diffLinesToChars = function (text1, text2) {
var lineArray, lineHash, chars1, chars2;
lineArray = []; // e.g. lineArray[4] === 'Hello\n'
lineHash = {}; // e.g. lineHash['Hello\n'] === 4
// '\x00' is a valid character, but various debuggers don't like it.
// So we'll insert a junk entry to avoid generating a null character.
lineArray[0] = "";
/**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
* @param {string} text String to encode.
* @return {string} Encoded string.
* @private
*/
function diffLinesToCharsMunge(text) {
var chars, lineStart, lineEnd, lineArrayLength, line;
chars = "";
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
lineStart = 0;
lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
lineArrayLength = lineArray.length;
while (lineEnd < text.length - 1) {
lineEnd = text.indexOf("\n", lineStart);
if (lineEnd === -1) {
lineEnd = text.length - 1;
}
line = text.substring(lineStart, lineEnd + 1);
lineStart = lineEnd + 1;
if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
( lineHash[line] !== undefined )) {
chars += String.fromCharCode(lineHash[line]);
} else {
chars += String.fromCharCode(lineArrayLength);
lineHash[line] = lineArrayLength;
lineArray[lineArrayLength++] = line;
}
}
return chars;
}
chars1 = diffLinesToCharsMunge(text1);
chars2 = diffLinesToCharsMunge(text2);
return {
chars1: chars1,
chars2: chars2,
lineArray: lineArray
};
};
/**
* Rehydrate the text in a diff from a string of line hashes to real lines of
* text.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
* @param {!Array.<string>} lineArray Array of unique strings.
* @private
*/
DiffMatchPatch.prototype.diffCharsToLines = function (diffs, lineArray) {
var x, chars, text, y;
for (x = 0; x < diffs.length; x++) {
chars = diffs[x][1];
text = [];
for (y = 0; y < chars.length; y++) {
text[y] = lineArray[chars.charCodeAt(y)];
}
diffs[x][1] = text.join("");
}
};
/**
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {!Array.<!DiffMatchPatch.Diff>} diffs Array of diff tuples.
*/
DiffMatchPatch.prototype.diffCleanupMerge = function (diffs) {
var pointer, countDelete, countInsert, textInsert, textDelete,
commonlength, changes, diffPointer, position;
diffs.push([DIFF_EQUAL, ""]); // Add a dummy entry at the end.
pointer = 0;
countDelete = 0;
countInsert = 0;
textDelete = "";
textInsert = "";
commonlength;
while (pointer < diffs.length) {
switch (diffs[pointer][0]) {
case DIFF_INSERT:
countInsert++;
textInsert += diffs[pointer][1];
pointer++;
break;
case DIFF_DELETE:
countDelete++;
textDelete += diffs[pointer][1];
pointer++;
break;
case DIFF_EQUAL:
// Upon reaching an equality, check for prior redundancies.
if (countDelete + countInsert > 1) {
if (countDelete !== 0 && countInsert !== 0) {
// Factor out any common prefixies.
commonlength = this.diffCommonPrefix(textInsert, textDelete);
if (commonlength !== 0) {
if (( pointer - countDelete - countInsert ) > 0 &&
diffs[pointer - countDelete - countInsert - 1][0] ===
DIFF_EQUAL) {
diffs[pointer - countDelete - countInsert - 1][1] +=
textInsert.substring(0, commonlength);
} else {
diffs.splice(0, 0, [DIFF_EQUAL,
textInsert.substring(0, commonlength)
]);
pointer++;
}
textInsert = textInsert.substring(commonlength);
textDelete = textDelete.substring(commonlength);
}
// Factor out any common suffixies.
commonlength = this.diffCommonSuffix(textInsert, textDelete);
if (commonlength !== 0) {
diffs[pointer][1] = textInsert.substring(textInsert.length -
commonlength) + diffs[pointer][1];
textInsert = textInsert.substring(0, textInsert.length -
commonlength);
textDelete = textDelete.substring(0, textDelete.length -
commonlength);
}
}
// Delete the offending records and add the merged ones.
if (countDelete === 0) {
diffs.splice(pointer - countInsert,
countDelete + countInsert, [DIFF_INSERT, textInsert]);
} else if (countInsert === 0) {
diffs.splice(pointer - countDelete,
countDelete + countInsert, [DIFF_DELETE, textDelete]);
} else {
diffs.splice(
pointer - countDelete - countInsert,
countDelete + countInsert,
[DIFF_DELETE, textDelete], [DIFF_INSERT, textInsert]
);
}
pointer = pointer - countDelete - countInsert +
( countDelete ? 1 : 0 ) + ( countInsert ? 1 : 0 ) + 1;
} else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
// Merge this equality with the previous one.
diffs[pointer - 1][1] += diffs[pointer][1];
diffs.splice(pointer, 1);
} else {
pointer++;
}
countInsert = 0;
countDelete = 0;
textDelete = "";
textInsert = "";
break;
}
}
if (diffs[diffs.length - 1][1] === "") {
diffs.pop(); // Remove the dummy entry at the end.
}
// Second pass: look for single edits surrounded on both sides by equalities
// which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
changes = false;
pointer = 1;
// Intentionally ignore the first and last element (don't need checking).
while (pointer < diffs.length - 1) {
if (diffs[pointer - 1][0] === DIFF_EQUAL &&
diffs[pointer + 1][0] === DIFF_EQUAL) {
diffPointer = diffs[pointer][1];
position = diffPointer.substring(
diffPointer.length - diffs[pointer - 1][1].length
);
// This is a single edit surrounded by equalities.
if (position === diffs[pointer - 1][1]) {
// Shift the edit over the previous equality.
diffs[pointer][1] = diffs[pointer - 1][1] +
diffs[pointer][1].substring(0, diffs[pointer][1].length -
diffs[pointer - 1][1].length);
diffs[pointer + 1][1] =
diffs[pointer - 1][1] + diffs[pointer + 1][1];
diffs.splice(pointer - 1, 1);
changes = true;
} else if (diffPointer.substring(0, diffs[pointer + 1][1].length) ===
diffs[pointer + 1][1]) {
// Shift the edit over the next equality.
diffs[pointer - 1][1] += diffs[pointer + 1][1];
diffs[pointer][1] =
diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
diffs[pointer + 1][1];
diffs.splice(pointer + 1, 1);
changes = true;
}
}
pointer++;
}
// If shifts were made, the diff needs reordering and another shift sweep.
if (changes) {
this.diffCleanupMerge(diffs);
}
};
return function (o, n) {
var diff, output, text;
diff = new DiffMatchPatch();
output = diff.DiffMain(o, n);
diff.diffCleanupEfficiency(output);
text = diff.diffPrettyHtml(output);
return text;
};
}() );
// Get a reference to the global object, like window in browsers
}((function () {
return this;
})()));
(function () {
// Don't load the HTML Reporter on non-Browser environments
if (typeof window === "undefined" || !window.document) {
return;
}
// Deprecated QUnit.init - Ref #530
// Re-initialize the configuration options
QUnit.init = function () {
var tests, banner, result, qunit,
config = QUnit.config;
config.stats = {all: 0, bad: 0};
config.moduleStats = {all: 0, bad: 0};
config.started = 0;
config.updateRate = 1000;
config.blocking = false;
config.autostart = true;
config.autorun = false;
config.filter = "";
config.queue = [];
// Return on non-browser environments
// This is necessary to not break on node tests
if (typeof window === "undefined") {
return;
}
qunit = id("qunit");
if (qunit) {
qunit.innerHTML =
"<h1 id='qunit-header'>" + escapeText(document.title) + "</h1>" +
"<h2 id='qunit-banner'></h2>" +
"<div id='qunit-testrunner-toolbar'></div>" +
"<h2 id='qunit-userAgent'></h2>" +
"<ol id='qunit-tests'></ol>";
}
tests = id("qunit-tests");
banner = id("qunit-banner");
result = id("qunit-testresult");
if (tests) {
tests.innerHTML = "";
}
if (banner) {
banner.className = "";
}
if (result) {
result.parentNode.removeChild(result);
}
if (tests) {
result = document.createElement("p");
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore(result, tests);
result.innerHTML = "Running...<br /> ";
}
};
var config = QUnit.config,
hasOwn = Object.prototype.hasOwnProperty,
defined = {
document: window.document !== undefined,
sessionStorage: (function () {
var x = "qunit-test-string";
try {
sessionStorage.setItem(x, x);
sessionStorage.removeItem(x);
return true;
} catch (e) {
return false;
}
}())
},
modulesList = [];
/**
* Escape text for attribute or text content.
*/
function escapeText(s) {
if (!s) {
return "";
}
s = s + "";
// Both single quotes and double quotes (for attributes)
return s.replace(/['"<>&]/g, function (s) {
switch (s) {
case "'":
return "'";
case "\"":
return """;
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
}
});
}
/**
* @param {HTMLElement} elem
* @param {string} type
* @param {Function} fn
*/
function addEvent(elem, type, fn) {
if (elem.addEventListener) {
// Standards-based browsers
elem.addEventListener(type, fn, false);
} else if (elem.attachEvent) {
// support: IE <9
elem.attachEvent("on" + type, function () {
var event = window.event;
if (!event.target) {
event.target = event.srcElement || document;
}
fn.call(elem, event);
});
}
}
/**
* @param {Array|NodeList} elems
* @param {string} type
* @param {Function} fn
*/
function addEvents(elems, type, fn) {
var i = elems.length;
while (i--) {
addEvent(elems[i], type, fn);
}
}
function hasClass(elem, name) {
return ( " " + elem.className + " " ).indexOf(" " + name + " ") >= 0;
}
function addClass(elem, name) {
if (!hasClass(elem, name)) {
elem.className += ( elem.className ? " " : "" ) + name;
}
}
function toggleClass(elem, name) {
if (hasClass(elem, name)) {
removeClass(elem, name);
} else {
addClass(elem, name);
}
}
function removeClass(elem, name) {
var set = " " + elem.className + " ";
// Class name may appear multiple times
while (set.indexOf(" " + name + " ") >= 0) {
set = set.replace(" " + name + " ", " ");
}
// trim for prettiness
elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
}
function id(name) {
return defined.document && document.getElementById && document.getElementById(name);
}
function getUrlConfigHtml() {
var i, j, val,
escaped, escapedTooltip,
selection = false,
len = config.urlConfig.length,
urlConfigHtml = "";
for (i = 0; i < len; i++) {
val = config.urlConfig[i];
if (typeof val === "string") {
val = {
id: val,
label: val
};
}
escaped = escapeText(val.id);
escapedTooltip = escapeText(val.tooltip);
if (config[val.id] === undefined) {
config[val.id] = QUnit.urlParams[val.id];
}
if (!val.value || typeof val.value === "string") {
urlConfigHtml += "<input id='qunit-urlconfig-" + escaped +
"' name='" + escaped + "' type='checkbox'" +
( val.value ? " value='" + escapeText(val.value) + "'" : "" ) +
( config[val.id] ? " checked='checked'" : "" ) +
" title='" + escapedTooltip + "' /><label for='qunit-urlconfig-" + escaped +
"' title='" + escapedTooltip + "'>" + val.label + "</label>";
} else {
urlConfigHtml += "<label for='qunit-urlconfig-" + escaped +
"' title='" + escapedTooltip + "'>" + val.label +
": </label><select id='qunit-urlconfig-" + escaped +
"' name='" + escaped + "' title='" + escapedTooltip + "'><option></option>";
if (QUnit.is("array", val.value)) {
for (j = 0; j < val.value.length; j++) {
escaped = escapeText(val.value[j]);
urlConfigHtml += "<option value='" + escaped + "'" +
( config[val.id] === val.value[j] ?
( selection = true ) && " selected='selected'" : "" ) +
">" + escaped + "</option>";
}
} else {
for (j in val.value) {
if (hasOwn.call(val.value, j)) {
urlConfigHtml += "<option value='" + escapeText(j) + "'" +
( config[val.id] === j ?
( selection = true ) && " selected='selected'" : "" ) +
">" + escapeText(val.value[j]) + "</option>";
}
}
}
if (config[val.id] && !selection) {
escaped = escapeText(config[val.id]);
urlConfigHtml += "<option value='" + escaped +
"' selected='selected' disabled='disabled'>" + escaped + "</option>";
}
urlConfigHtml += "</select>";
}
}
return urlConfigHtml;
}
// Handle "click" events on toolbar checkboxes and "change" for select menus.
// Updates the URL with the new state of `config.urlConfig` values.
function toolbarChanged() {
var updatedUrl, value,
field = this,
params = {};
// Detect if field is a select menu or a checkbox
if ("selectedIndex" in field) {
value = field.options[field.selectedIndex].value || undefined;
} else {
value = field.checked ? ( field.defaultValue || true ) : undefined;
}
params[field.name] = value;
updatedUrl = setUrl(params);
if ("hidepassed" === field.name && "replaceState" in window.history) {
config[field.name] = value || false;
if (value) {
addClass(id("qunit-tests"), "hidepass");
} else {
removeClass(id("qunit-tests"), "hidepass");
}
// It is not necessary to refresh the whole page
window.history.replaceState(null, "", updatedUrl);
} else {
window.location = updatedUrl;
}
}
function setUrl(params) {
var key,
querystring = "?";
params = QUnit.extend(QUnit.extend({}, QUnit.urlParams), params);
for (key in params) {
if (hasOwn.call(params, key)) {
if (params[key] === undefined) {
continue;
}
querystring += encodeURIComponent(key);
if (params[key] !== true) {
querystring += "=" + encodeURIComponent(params[key]);
}
querystring += "&";
}
}
return location.protocol + "//" + location.host +
location.pathname + querystring.slice(0, -1);
}
function applyUrlParams() {
var selectedModule,
modulesList = id("qunit-modulefilter"),
filter = id("qunit-filter-input").value;
selectedModule = modulesList ?
decodeURIComponent(modulesList.options[modulesList.selectedIndex].value) :
undefined;
window.location = setUrl({
module: ( selectedModule === "" ) ? undefined : selectedModule,
filter: ( filter === "" ) ? undefined : filter,
// Remove testId filter
testId: undefined
});
}
function toolbarUrlConfigContainer() {
var urlConfigContainer = document.createElement("span");
urlConfigContainer.innerHTML = getUrlConfigHtml();
addClass(urlConfigContainer, "qunit-url-config");
// For oldIE support:
// * Add handlers to the individual elements instead of the container
// * Use "click" instead of "change" for checkboxes
addEvents(urlConfigContainer.getElementsByTagName("input"), "click", toolbarChanged);
addEvents(urlConfigContainer.getElementsByTagName("select"), "change", toolbarChanged);
return urlConfigContainer;
}
function toolbarLooseFilter() {
var filter = document.createElement("form"),
label = document.createElement("label"),
input = document.createElement("input"),
button = document.createElement("button");
addClass(filter, "qunit-filter");
label.innerHTML = "Filter: ";
input.type = "text";
input.value = config.filter || "";
input.name = "filter";
input.id = "qunit-filter-input";
button.innerHTML = "Go";
label.appendChild(input);
filter.appendChild(label);
filter.appendChild(button);
addEvent(filter, "submit", function (ev) {
applyUrlParams();
if (ev && ev.preventDefault) {
ev.preventDefault();
}
return false;
});
return filter;
}
function toolbarModuleFilterHtml() {
var i,
moduleFilterHtml = "";
if (!modulesList.length) {
return false;
}
modulesList.sort(function (a, b) {
return a.localeCompare(b);
});
moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label>" +
"<select id='qunit-modulefilter' name='modulefilter'><option value='' " +
( QUnit.urlParams.module === undefined ? "selected='selected'" : "" ) +
">< All Modules ></option>";
for (i = 0; i < modulesList.length; i++) {
moduleFilterHtml += "<option value='" +
escapeText(encodeURIComponent(modulesList[i])) + "' " +
( QUnit.urlParams.module === modulesList[i] ? "selected='selected'" : "" ) +
">" + escapeText(modulesList[i]) + "</option>";
}
moduleFilterHtml += "</select>";
return moduleFilterHtml;
}
function toolbarModuleFilter() {
var toolbar = id("qunit-testrunner-toolbar"),
moduleFilter = document.createElement("span"),
moduleFilterHtml = toolbarModuleFilterHtml();
if (!toolbar || !moduleFilterHtml) {
return false;
}
moduleFilter.setAttribute("id", "qunit-modulefilter-container");
moduleFilter.innerHTML = moduleFilterHtml;
addEvent(moduleFilter.lastChild, "change", applyUrlParams);
toolbar.appendChild(moduleFilter);
}
function appendToolbar() {
var toolbar = id("qunit-testrunner-toolbar");
if (toolbar) {
toolbar.appendChild(toolbarUrlConfigContainer());
toolbar.appendChild(toolbarLooseFilter());
}
}
function appendHeader() {
var header = id("qunit-header");
if (header) {
header.innerHTML = "<a href='" +
setUrl({filter: undefined, module: undefined, testId: undefined}) +
"'>" + header.innerHTML + "</a> ";
}
}
function appendBanner() {
var banner = id("qunit-banner");
if (banner) {
banner.className = "";
}
}
function appendTestResults() {
var tests = id("qunit-tests"),
result = id("qunit-testresult");
if (result) {
result.parentNode.removeChild(result);
}
if (tests) {
tests.innerHTML = "";
result = document.createElement("p");
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore(result, tests);
result.innerHTML = "Running...<br /> ";
}
}
function storeFixture() {
var fixture = id("qunit-fixture");
if (fixture) {
config.fixture = fixture.innerHTML;
}
}
function appendUserAgent() {
var userAgent = id("qunit-userAgent");
if (userAgent) {
userAgent.innerHTML = "";
userAgent.appendChild(
document.createTextNode(
"QUnit " + QUnit.version + "; " + navigator.userAgent
)
);
}
}
function appendTestsList(modules) {
var i, l, x, z, test, moduleObj;
for (i = 0, l = modules.length; i < l; i++) {
moduleObj = modules[i];
if (moduleObj.name) {
modulesList.push(moduleObj.name);
}
for (x = 0, z = moduleObj.tests.length; x < z; x++) {
test = moduleObj.tests[x];
appendTest(test.name, test.testId, moduleObj.name);
}
}
}
function appendTest(name, testId, moduleName) {
var title, rerunTrigger, testBlock, assertList,
tests = id("qunit-tests");
if (!tests) {
return;
}
title = document.createElement("strong");
title.innerHTML = getNameHtml(name, moduleName);
rerunTrigger = document.createElement("a");
rerunTrigger.innerHTML = "Rerun";
rerunTrigger.href = setUrl({testId: testId});
testBlock = document.createElement("li");
testBlock.appendChild(title);
testBlock.appendChild(rerunTrigger);
testBlock.id = "qunit-test-output-" + testId;
assertList = document.createElement("ol");
assertList.className = "qunit-assert-list";
testBlock.appendChild(assertList);
tests.appendChild(testBlock);
}
// HTML Reporter initialization and load
QUnit.begin(function (details) {
var qunit = id("qunit");
// Fixture is the only one necessary to run without the #qunit element
storeFixture();
if (qunit) {
qunit.innerHTML =
"<h1 id='qunit-header'>" + escapeText(document.title) + "</h1>" +
"<h2 id='qunit-banner'></h2>" +
"<div id='qunit-testrunner-toolbar'></div>" +
"<h2 id='qunit-userAgent'></h2>" +
"<ol id='qunit-tests'></ol>";
}
appendHeader();
appendBanner();
appendTestResults();
appendUserAgent();
appendToolbar();
appendTestsList(details.modules);
toolbarModuleFilter();
if (qunit && config.hidepassed) {
addClass(qunit.lastChild, "hidepass");
}
});
QUnit.done(function (details) {
var i, key,
banner = id("qunit-banner"),
tests = id("qunit-tests"),
html = [
"Tests completed in ",
details.runtime,
" milliseconds.<br />",
"<span class='passed'>",
details.passed,
"</span> assertions of <span class='total'>",
details.total,
"</span> passed, <span class='failed'>",
details.failed,
"</span> failed."
].join("");
if (banner) {
banner.className = details.failed ? "qunit-fail" : "qunit-pass";
}
if (tests) {
id("qunit-testresult").innerHTML = html;
}
if (config.altertitle && defined.document && document.title) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
( details.failed ? "\u2716" : "\u2714" ),
document.title.replace(/^[\u2714\u2716] /i, "")
].join(" ");
}
// clear own sessionStorage items if all tests passed
if (config.reorder && defined.sessionStorage && details.failed === 0) {
for (i = 0; i < sessionStorage.length; i++) {
key = sessionStorage.key(i++);
if (key.indexOf("qunit-test-") === 0) {
sessionStorage.removeItem(key);
}
}
}
// scroll back to top to show results
if (config.scrolltop && window.scrollTo) {
window.scrollTo(0, 0);
}
});
function getNameHtml(name, module) {
var nameHtml = "";
if (module) {
nameHtml = "<span class='module-name'>" + escapeText(module) + "</span>: ";
}
nameHtml += "<span class='test-name'>" + escapeText(name) + "</span>";
return nameHtml;
}
QUnit.testStart(function (details) {
var running, testBlock, bad;
testBlock = id("qunit-test-output-" + details.testId);
if (testBlock) {
testBlock.className = "running";
} else {
// Report later registered tests
appendTest(details.name, details.testId, details.module);
}
running = id("qunit-testresult");
if (running) {
bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-test-" + details.module + "-" + details.name);
running.innerHTML = ( bad ?
"Rerunning previously failed test: <br />" :
"Running: <br />" ) +
getNameHtml(details.name, details.module);
}
});
function stripHtml(string) {
// strip tags, html entity and whitespaces
return string.replace(/<\/?[^>]+(>|$)/g, "").replace(/\"/g, "").replace(/\s+/g, "");
}
QUnit.log(function (details) {
var assertList, assertLi,
message, expected, actual, diff,
showDiff = false,
testItem = id("qunit-test-output-" + details.testId);
if (!testItem) {
return;
}
message = escapeText(details.message) || ( details.result ? "okay" : "failed" );
message = "<span class='test-message'>" + message + "</span>";
message += "<span class='runtime'>@ " + details.runtime + " ms</span>";
// pushFailure doesn't provide details.expected
// when it calls, it's implicit to also not show expected and diff stuff
// Also, we need to check details.expected existence, as it can exist and be undefined
if (!details.result && hasOwn.call(details, "expected")) {
if (details.negative) {
expected = escapeText("NOT " + QUnit.dump.parse(details.expected));
} else {
expected = escapeText(QUnit.dump.parse(details.expected));
}
actual = escapeText(QUnit.dump.parse(details.actual));
message += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" +
expected +
"</pre></td></tr>";
if (actual !== expected) {
message += "<tr class='test-actual'><th>Result: </th><td><pre>" +
actual + "</pre></td></tr>";
// Don't show diff if actual or expected are booleans
if (!( /^(true|false)$/.test(actual) ) && !( /^(true|false)$/.test(expected) )) {
diff = QUnit.diff(expected, actual);
showDiff = stripHtml(diff).length !==
stripHtml(expected).length +
stripHtml(actual).length;
}
// Don't show diff if expected and actual are totally different
if (showDiff) {
message += "<tr class='test-diff'><th>Diff: </th><td><pre>" +
diff + "</pre></td></tr>";
}
} else if (expected.indexOf("[object Array]") !== -1 ||
expected.indexOf("[object Object]") !== -1) {
message += "<tr class='test-message'><th>Message: </th><td>" +
"Diff suppressed as the depth of object is more than current max depth (" +
QUnit.config.maxDepth + ").<p>Hint: Use <code>QUnit.dump.maxDepth</code> to " +
" run with a higher max depth or <a href='" + setUrl({maxDepth: -1}) + "'>" +
"Rerun</a> without max depth.</p></td></tr>";
}
if (details.source) {
message += "<tr class='test-source'><th>Source: </th><td><pre>" +
escapeText(details.source) + "</pre></td></tr>";
}
message += "</table>";
// this occours when pushFailure is set and we have an extracted stack trace
} else if (!details.result && details.source) {
message += "<table>" +
"<tr class='test-source'><th>Source: </th><td><pre>" +
escapeText(details.source) + "</pre></td></tr>" +
"</table>";
}
assertList = testItem.getElementsByTagName("ol")[0];
assertLi = document.createElement("li");
assertLi.className = details.result ? "pass" : "fail";
assertLi.innerHTML = message;
assertList.appendChild(assertLi);
});
QUnit.testDone(function (details) {
var testTitle, time, testItem, assertList,
good, bad, testCounts, skipped, sourceName,
tests = id("qunit-tests");
if (!tests) {
return;
}
testItem = id("qunit-test-output-" + details.testId);
assertList = testItem.getElementsByTagName("ol")[0];
good = details.passed;
bad = details.failed;
// store result when possible
if (config.reorder && defined.sessionStorage) {
if (bad) {
sessionStorage.setItem("qunit-test-" + details.module + "-" + details.name, bad);
} else {
sessionStorage.removeItem("qunit-test-" + details.module + "-" + details.name);
}
}
if (bad === 0) {
addClass(assertList, "qunit-collapsed");
}
// testItem.firstChild is the test name
testTitle = testItem.firstChild;
testCounts = bad ?
"<b class='failed'>" + bad + "</b>, " + "<b class='passed'>" + good + "</b>, " :
"";
testTitle.innerHTML += " <b class='counts'>(" + testCounts +
details.assertions.length + ")</b>";
if (details.skipped) {
testItem.className = "skipped";
skipped = document.createElement("em");
skipped.className = "qunit-skipped-label";
skipped.innerHTML = "skipped";
testItem.insertBefore(skipped, testTitle);
} else {
addEvent(testTitle, "click", function () {
toggleClass(assertList, "qunit-collapsed");
});
testItem.className = bad ? "fail" : "pass";
time = document.createElement("span");
time.className = "runtime";
time.innerHTML = details.runtime + " ms";
testItem.insertBefore(time, assertList);
}
// Show the source of the test when showing assertions
if (details.source) {
sourceName = document.createElement("p");
sourceName.innerHTML = "<strong>Source: </strong>" + details.source;
addClass(sourceName, "qunit-source");
if (bad === 0) {
addClass(sourceName, "qunit-collapsed");
}
addEvent(testTitle, "click", function () {
toggleClass(sourceName, "qunit-collapsed");
});
testItem.appendChild(sourceName);
}
});
if (defined.document) {
// Avoid readyState issue with phantomjs
// Ref: #818
var notPhantom = (function (p) {
return !( p && p.version && p.version.major > 0 );
})(window.phantom);
if (notPhantom && document.readyState === "complete") {
QUnit.load();
} else {
addEvent(window, "load", QUnit.load);
}
} else {
config.pageLoaded = true;
config.autorun = true;
}
})();
|
var mongoose = require('mongoose')
console.log("ImageModel");
var image_schema = mongoose.Schema({
event: {
person_name: {
type: String,
required: true,
},
},
});
var ImageModel = mongoose.model('logs_99957758195164324594', image_schema);
module.exports = ImageModel;
|
//----------- Imports -----------//
import Field from './styles'
import moment from 'moment'
import React, { PropTypes, cloneElement } from 'react'
//----------- Component -----------//
const ReduxAntdWrapper = (field) => {
const { label, meta, layout, children, input: { value, checked, ...input }, ...props } = field
const id = (props.id || input.name)
const invalid = !!(meta.touched && meta.error)
const disabled = (props.isLoading || props.disabled)
const validateStatus = invalid ? 'error' : null
const formLayout = ('horizontal' == layout) ? { labelCol: { span: 6 }, wrapperCol: { span: 18 } } : {}
let onBlur = () => input.onBlur()
let onChange = input.onChange
let defaultValue = value
let defaultChecked = !!value
switch (children.props.prefixCls){
case 'ant-calendar':
onChange = (val) => input.onChange(val ? val.toISOString() : null)
defaultValue = (value && moment(value).isValid()) ? moment(value) : undefined
break
case 'ant-checkbox-group':
defaultValue = value ? value : []
break
case 'ant-select':
defaultValue = value ? value.toString() : '0'
break
}
const elState = { id, label, disabled, validateStatus, ...formLayout }
const childProps = { ...input, id, disabled, onBlur, onChange, defaultValue, defaultChecked }
return (
<Field.Wrapper { ...elState }>
<Field.Errors title={meta.error || ''} placement='right' visible={invalid && meta.active}>
{cloneElement(children, childProps)}
</Field.Errors>
</Field.Wrapper>
)
}
//----------- Prop Types -----------//
ReduxAntdWrapper.propTypes = {
// ReduxFormWrapper Props
disabled : PropTypes.bool,
id : PropTypes.string,
icon : PropTypes.string,
label : PropTypes.string,
loading : PropTypes.bool,
prependLabel : PropTypes.bool,
required : PropTypes.bool,
style : PropTypes.object,
className : PropTypes.string,
// Ant Design Props
layout: PropTypes.oneOf(['horizontal', 'vertical', 'inline']),
// ReduxForm Field Props
dirty : PropTypes.bool,
input : PropTypes.shape({
checked : PropTypes.bool,
name : PropTypes.string.isRequired,
onBlur : PropTypes.func.isRequired,
onChange : PropTypes.func.isRequired,
onDragStart : PropTypes.func.isRequired,
onDrop : PropTypes.func.isRequired,
onFocus : PropTypes.func.isRequired,
value : PropTypes.any,
}).isRequired,
meta : PropTypes.shape({
active : PropTypes.bool.isRequired,
asyncValidating : PropTypes.bool.isRequired,
autofilled : PropTypes.bool.isRequired,
dirty : PropTypes.bool.isRequired,
dispatch : PropTypes.func.isRequired,
error : PropTypes.string,
form : PropTypes.string.isRequired,
invalid : PropTypes.bool.isRequired,
pristine : PropTypes.bool.isRequired,
submitFailed : PropTypes.bool.isRequired,
submitting : PropTypes.bool.isRequired,
touched : PropTypes.bool.isRequired,
valid : PropTypes.bool.isRequired,
visited : PropTypes.bool.isRequired,
warning : PropTypes.string,
}).isRequired,
name : PropTypes.string,
pristine : PropTypes.bool,
value : PropTypes.any,
}
ReduxAntdWrapper.defaultProps = {
disabled : false,
layout : 'horizontal',
loading : false,
prependLabel : true,
required : false,
}
//----------- Export -----------//
export default ReduxAntdWrapper
|
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
// page container
frappe.provide('frappe.pages');
frappe.provide('frappe.views');
window.cur_page = null;
frappe.views.Container = class Container {
// Container contains pages inside `#container` and manages page creation, switching
constructor() {
this.container = $('#body').get(0);
this.page = null; // current page
this.pagewidth = $(this.container).width();
this.pagemargin = 50;
var me = this;
$(document).on("page-change", function() {
// set data-route in body
var route_str = frappe.get_route_str();
$("body").attr("data-route", route_str);
$("body").attr("data-sidebar", me.has_sidebar() ? 1 : 0);
});
$(document).bind('rename', function(event, dt, old_name, new_name) {
frappe.breadcrumbs.rename(dt, old_name, new_name);
});
}
add_page(label) {
var page = $('<div class="content page-container"></div>')
.attr('id', "page-" + label)
.attr("data-page-route", label)
.hide()
.appendTo(this.container).get(0);
page.label = label;
frappe.pages[label] = page;
return page;
}
change_to(label) {
cur_page = this;
if(label.tagName) {
// if sent the div, get the table
var page = label;
} else {
var page = frappe.pages[label];
}
if(!page) {
console.log(__('Page not found')+ ': ' + label);
return;
}
// hide dialog
if(window.cur_dialog && cur_dialog.display && !cur_dialog.keep_open) {
if (!cur_dialog.minimizable) {
cur_dialog.hide();
} else if (!cur_dialog.is_minimized) {
cur_dialog.toggle_minimize();
}
}
// hide current
if(this.page && this.page != page) {
$(this.page).hide();
$(this.page).trigger('hide');
}
// show new
if(!this.page || this.page != page) {
this.page = page;
// $(this.page).fadeIn(300);
$(this.page).show();
}
$(document).trigger("page-change");
this.page._route = frappe.router.get_sub_path();
$(this.page).trigger('show');
!this.page.disable_scroll_to_top && frappe.utils.scroll_to(0);
frappe.breadcrumbs.update();
return this.page;
}
has_sidebar() {
var flag = 0;
var route_str = frappe.get_route_str();
// check in frappe.ui.pages
flag = frappe.ui.pages[route_str] && !frappe.ui.pages[route_str].single_column;
// sometimes frappe.ui.pages is updated later,
// so check the dom directly
if(!flag) {
var page_route = route_str.split('/').slice(0, 2).join('/');
flag = $(`.page-container[data-page-route="${page_route}"] .layout-side-section`).length ? 1 : 0;
}
return flag;
}
};
|
/**
* Original implementation of this file by @marudor at https://github.com/marudor/flowInterfaces
* Copied here based on intention to merge with flow-typed expressed here:
* https://github.com/marudor/flowInterfaces/issues/6
*/
// Mostly from https://github.com/yahoo/react-intl/wiki/API#react-intl-api
declare module "react-intl" {
import type { Element, ChildrenArray } from "react";
declare type $npm$ReactIntl$LocaleData = {
locale: string,
[key: string]: any
};
declare type $npm$ReactIntl$MessageDescriptor = {
id: string,
description?: string,
defaultMessage?: string
};
declare type $npm$ReactIntl$IntlConfig = {
locale: string,
formats: Object,
messages: { [id: string]: string },
defaultLocale?: string,
defaultFormats?: Object
};
declare type $npm$ReactIntl$IntlProviderConfig = {
locale?: string,
formats?: Object,
messages?: { [id: string]: string },
defaultLocale?: string,
defaultFormats?: Object
};
declare type $npm$ReactIntl$IntlFormat = {
formatDate: (value: any, options?: Object) => string,
formatTime: (value: any, options?: Object) => string,
formatRelative: (value: any, options?: Object) => string,
formatNumber: (value: any, options?: Object) => string,
formatPlural: (value: any, options?: Object) => string,
formatMessage: (
messageDescriptor: $npm$ReactIntl$MessageDescriptor,
values?: Object
) => string,
formatHTMLMessage: (
messageDescriptor: $npm$ReactIntl$MessageDescriptor,
values?: Object
) => string
};
declare type $npm$ReactIntl$IntlShape = $npm$ReactIntl$IntlConfig &
$npm$ReactIntl$IntlFormat & { now: () => number };
declare type $npm$ReactIntl$DateTimeFormatOptions = {
localeMatcher?: "best fit" | "lookup",
formatMatcher?: "basic" | "best fit",
timeZone?: string,
hour12?: boolean,
weekday?: "narrow" | "short" | "long",
era?: "narrow" | "short" | "long",
year?: "numeric" | "2-digit",
month?: "numeric" | "2-digit" | "narrow" | "short" | "long",
day?: "numeric" | "2-digit",
hour?: "numeric" | "2-digit",
minute?: "numeric" | "2-digit",
second?: "numeric" | "2-digit",
timeZoneName?: "short" | "long"
};
declare type $npm$ReactIntl$RelativeFormatOptions = {
style?: "best fit" | "numeric",
units?: "second" | "minute" | "hour" | "day" | "month" | "year"
};
declare type $npm$ReactIntl$NumberFormatOptions = {
localeMatcher?: "best fit" | "lookup",
style?: "decimal" | "currency" | "percent",
currency?: string,
currencyDisplay?: "symbol" | "code" | "name",
useGrouping?: boolean,
minimumIntegerDigits?: number,
minimumFractionDigits?: number,
maximumFractionDigits?: number,
minimumSignificantDigits?: number,
maximumSignificantDigits?: number
};
declare type $npm$ReactIntl$PluralFormatOptions = {
style?: "cardinal" | "ordinal"
};
declare type $npm$ReactIntl$PluralCategoryString =
| "zero"
| "one"
| "two"
| "few"
| "many"
| "other";
declare type $npm$ReactIntl$DateParseable = number | string | Date;
// PropType checker
declare function intlShape(
props: Object,
propName: string,
componentName: string
): void;
declare function addLocaleData(
data: $npm$ReactIntl$LocaleData | Array<$npm$ReactIntl$LocaleData>
): void;
declare function defineMessages<
T: { [key: string]: $Exact<$npm$ReactIntl$MessageDescriptor> }
>(
messageDescriptors: T
): T;
declare type InjectIntlProvidedProps = {
intl: $npm$ReactIntl$IntlShape
}
declare type InjectIntlVoidProps = {
intl: $npm$ReactIntl$IntlShape | void
}
declare type ComponentWithDefaultProps<DefaultProps: {}, Props: {}> =
| React$ComponentType<Props>
| React$StatelessFunctionalComponent<Props>
| ChildrenArray<void | null | boolean | string | number | Element<any>>;
declare type InjectIntlOptions = {
intlPropName?: string,
withRef?: boolean
}
declare class IntlInjectedComponent<TOwnProps, TDefaultProps> extends React$Component<TOwnProps> {
static WrappedComponent: Class<React$Component<TOwnProps & InjectIntlProvidedProps>>,
static defaultProps: TDefaultProps,
props: TOwnProps
}
declare type IntlInjectedComponentClass<TOwnProps, TDefaultProps: {} = {}> = Class<
IntlInjectedComponent<TOwnProps, TDefaultProps>
>;
declare function injectIntl<P: {}, Component: React$ComponentType<P>>(
WrappedComponent: Component,
options?: InjectIntlOptions,
): React$ComponentType<
$Diff<React$ElementConfig<Component>, InjectIntlVoidProps>
>;
declare function formatMessage(
messageDescriptor: $npm$ReactIntl$MessageDescriptor,
values?: Object
): string;
declare function formatHTMLMessage(
messageDescriptor: $npm$ReactIntl$MessageDescriptor,
values?: Object
): string;
declare function formatDate(
value: any,
options?: $npm$ReactIntl$DateTimeFormatOptions & { format: string }
): string;
declare function formatTime(
value: any,
options?: $npm$ReactIntl$DateTimeFormatOptions & { format: string }
): string;
declare function formatRelative(
value: any,
options?: $npm$ReactIntl$RelativeFormatOptions & {
format: string,
now: any
}
): string;
declare function formatNumber(
value: any,
options?: $npm$ReactIntl$NumberFormatOptions & { format: string }
): string;
declare function formatPlural(
value: any,
options?: $npm$ReactIntl$PluralFormatOptions
): $npm$ReactIntl$PluralCategoryString;
declare class FormattedMessage extends React$Component<
$npm$ReactIntl$MessageDescriptor & {
values?: Object,
tagName?: string,
children?:
| ((...formattedMessage: Array<React$Node>) => React$Node)
| (string => React$Node)
}
> {}
declare class FormattedHTMLMessage extends React$Component<
$npm$ReactIntl$DateTimeFormatOptions & {
values?: Object,
tagName?: string,
children?: (...formattedMessage: Array<React$Node>) => React$Node
}
> {}
declare class FormattedDate extends React$Component<
$npm$ReactIntl$DateTimeFormatOptions & {
value: $npm$ReactIntl$DateParseable,
format?: string,
children?: (formattedDate: string) => React$Node
}
> {}
declare class FormattedTime extends React$Component<
$npm$ReactIntl$DateTimeFormatOptions & {
value: $npm$ReactIntl$DateParseable,
format?: string,
children?: (formattedDate: string) => React$Node
}
> {}
declare class FormattedRelative extends React$Component<
$npm$ReactIntl$RelativeFormatOptions & {
value: $npm$ReactIntl$DateParseable,
format?: string,
updateInterval?: number,
initialNow?: $npm$ReactIntl$DateParseable,
children?: (formattedDate: string) => React$Node
}
> {}
declare class FormattedNumber extends React$Component<
$npm$ReactIntl$NumberFormatOptions & {
value: number | string,
format?: string,
children?: (formattedNumber: string) => React$Node
}
> {}
declare class FormattedPlural extends React$Component<
$npm$ReactIntl$PluralFormatOptions & {
value: number | string,
other: React$Node,
zero?: React$Node,
one?: React$Node,
two?: React$Node,
few?: React$Node,
many?: React$Node,
children?: (formattedPlural: React$Node) => React$Node
}
> {}
declare class IntlProvider extends React$Component<
$npm$ReactIntl$IntlProviderConfig & {
children?: React$Node,
initialNow?: $npm$ReactIntl$DateParseable
}
> {}
declare type IntlShape = $npm$ReactIntl$IntlShape;
declare type MessageDescriptor = $npm$ReactIntl$MessageDescriptor;
}
|
var comb = require("comb");
exports.up = function (db, next) {
comb.when(
db.alterTable("test1", function () {
this.renameColumn("column1", "column2");
}),
db.alterTable("test2", function () {
this.renameColumn("column2", "column3");
}),
db.alterTable("test3", function () {
this.renameColumn("column3", "column4");
}),
db.alterTable("test4", function () {
this.renameColumn("column4", "column5");
})
).classic(next);
};
exports.down = function (db) {
return comb.when(
db.alterTable("test1", function () {
this.renameColumn("column2", "column1");
}),
db.alterTable("test2", function () {
this.renameColumn("column3", "column2");
}),
db.alterTable("test3", function () {
this.renameColumn("column4", "column3");
}),
db.alterTable("test4", function () {
this.renameColumn("column5", "column4");
})
);
}; |
/*
Social Bookmarks Widget
Widget Suite for DotNetNuke
Author - Will Strohl (http://www.WillStrohl.com)
Project Contributors - Will Strohl (http://www.WillStrohl.com), Mark Allan (http://www.dnngarden.com), Armand Datema (http://www.schwingsoft.com)
Support - http://dnnwidgets.codeplex.com
Copyright (c) 2009-2011 by Will Strohl
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Widget Suite for DotNetNuke nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
''' -----------------------------------------------------------------------------
''' <summary>
''' This widget script adds social bookmarks into a DNN 5+ page.
''' </summary>
''' <remarks>
''' Implement in your skins like this:
''' <object id="AnyName" codetype="dotnetnuke/client" codebase="WillStrohl.Widgets.SocialBookmarkWidget" declare="declare">
''' <param name="widgetType" value="Vertical400px" />
''' </object>
''' </remarks>
''' <history>
''' [WillStrohl] - 20090111 - Created
''' </history>
''' -----------------------------------------------------------------------------
*/
/* BEGIN: Namespace management */
Type.registerNamespace("WillStrohl.Widgets");
/* END: Namespace management */
WillStrohl.Widgets.SocialBookmarkWidget = function (widget) {
WillStrohl.Widgets.SocialBookmarkWidget.initializeBase(this, [widget]);
}
WillStrohl.Widgets.SocialBookmarkWidget.prototype =
{
/* BEGIN: render */
render:
function () {
var params = this._widget.childNodes;
if (params != null) {
var baseUrl = '';
var setStyle = 'false';
var valWidth = '500px';
var valHeight = '35px';
var sbDigg = 'false';
var sbDelicious = 'false';
var sbDotNetKicks = 'false';
var sbFacebook = 'false';
var sbStumbleUpon = 'false';
var debugEnabled = 'false';
for (var p = 0; p < params.length; p++) {
try {
var paramName = params[p].name.toLowerCase();
switch (paramName) {
case 'baseurl': baseUrl = params[p].value; break;
case 'width': valWidth = params[p].value; break;
case 'height': valHeight = params[p].value; break;
case 'setstyle': setStyle = params[p].value; break;
case 'showdigg': sbDigg = params[p].value; break;
case 'showdelicious': sbDelicious = params[p].value; break;
case 'showdotnetkicks': sbDotNetKicks = params[p].value; break;
case 'showfacebook': sbFacebook = params[p].value; break;
case 'showstumbleupon': sbStumbleUpon = params[p].value; break;
case 'debug': debugEnabled = params[p].value; break;
}
}
catch (e) {
//alert('An Error Occurred: ' + e);
}
}
}
/* INITIATE THE DEBUGGER */
var runDebug = false;
if (debugEnabled == 'true') {
runDebug = true;
}
if (runDebug) {
if ($('#DebugConsole').length == 0) $('body').append('<div id="DebugConsole" class="DebugConsole"></div>');
$DEBUGLINE('<span class="Head">Widget Suite: SocialBookmarks Debug Report</span><br />');
$DEBUGLINE('<span class="SubHead">Parameter Values:</span>');
$DEBUGLINE('baseUrl = ' + baseUrl);
$DEBUGLINE('width = ' + valWidth);
$DEBUGLINE('height = ' + valHeight);
$DEBUGLINE('setStyle = ' + setStyle);
$DEBUGLINE('showDigg = ' + sbDigg);
$DEBUGLINE('showDelicious = ' + sbDelicious);
$DEBUGLINE('showDotNetKicks = ' + sbDotNetKicks);
$DEBUGLINE('showFacebook = ' + sbFacebook);
$DEBUGLINE('showStumbleUpon = ' + sbStumbleUpon);
$DEBUGLINE('debug = ' + debugEnabled);
$DEBUGLINE('<br /><span class="SubHead">Activity Log:</span>');
}
try {
if (baseUrl == '') baseUrl = location.hostname;
if (runDebug) $DEBUGLINE('baseUrl value is: ' + baseUrl);
if (baseUrl != '') {
if (baseUrl.indexOf('http') == -1) {
var httpHost = (("https:" == document.location.protocol) ? 'https:/' : 'http:/');
baseUrl = httpHost + '/' + baseUrl;
if (runDebug) $DEBUGLINE('baseUrl after parsing for SSL is: ' + baseUrl);
}
baseUrl = baseUrl + '/Resources/Widgets/User/WillStrohl/';
var div = document.createElement('div');
div.setAttribute('class', 'WillStrohlSBWrapper');
/*
DIGG
*/
if (sbDigg == 'true') {
div.innerHTML = div.innerHTML + ' ';
var aDigg = document.createElement('a');
aDigg.setAttribute('href', 'http://digg.com/submit?url=' + document.location + '&title=' + document.title);
aDigg.setAttribute('target', '_blank');
var imgDigg = document.createElement('img');
imgDigg.setAttribute('src', 'http://digg.com/img/badges/16x16-digg-guy.gif');
imgDigg.setAttribute('alt', 'Digg this');
imgDigg.setAttribute('border', '0');
imgDigg.setAttribute('style', 'width:16px;width:16px;');
imgDigg.setAttribute('class', 'WillStrohlSBImage');
aDigg.appendChild(imgDigg);
div.appendChild(aDigg);
div.innerHTML = div.innerHTML + ' ';
}
/*
DELICIOUS
*/
if (sbDelicious == 'true') {
// <img src="http://static.delicious.com/img/delicious.small.gif" height="10" width="10" alt="Delicious" />
// <a href="http://delicious.com/save" onclick="window.open('http://delicious.com/save?v=5&noui&jump=close&url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550'); return false;"> Bookmark this on Delicious</a>
div.innerHTML = div.innerHTML + ' ';
var aDelicious = document.createElement('a');
aDelicious.setAttribute('href', 'http://delicious.com/save');
aDelicious.setAttribute('onclick', 'window.open(\'http://delicious.com/save?v=5&noui&jump=close&url=\'+encodeURIComponent(location.href)+\'&title=\'+encodeURIComponent(document.title), \'delicious\',\'toolbar=no,width=550,height=550\'); return false;');
var imgDelicious = document.createElement('img');
imgDelicious.setAttribute('src', 'http://static.delicious.com/img/delicious.small.gif');
imgDelicious.setAttribute('alt', 'Delicious');
imgDelicious.setAttribute('border', '0');
imgDelicious.setAttribute('style', 'width:10px;height:10px;border:none;');
imgDelicious.setAttribute('class', 'WillStrohlSBImage');
aDelicious.appendChild(imgDelicious);
div.appendChild(aDelicious);
div.innerHTML = div.innerHTML + ' ';
}
/*
DOTNETKICKS
*/
if (sbDotNetKicks == 'true') {
div.innerHTML = div.innerHTML + ' ';
var aDnk = document.createElement('a');
aDnk.setAttribute('href', 'http://www.dotnetkicks.com/kick/?url=' + document.location + '&title=' + document.title + '&r=Will+Strohl');
aDnk.setAttribute('target', '_blank');
var imgDnk = document.createElement('img');
imgDnk.setAttribute('src', 'http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=' + document.location);
imgDnk.setAttribute('alt', 'DotNetKicks');
imgDnk.setAttribute('border', '0');
imgDnk.setAttribute('style', 'border:none;');
imgDnk.setAttribute('class', 'WillStrohlSBImage');
aDnk.appendChild(imgDnk);
div.appendChild(aDnk);
div.innerHTML = div.innerHTML + ' ';
}
/*
FACEBOOK
*/
if (sbFacebook == 'true') {
div.innerHTML = div.innerHTML + ' ';
var aFacebook = document.createElement('a');
aFacebook.setAttribute('href', 'http://www.facebook.com/sharer.php?u=' + document.location + '&t=' + document.title);
aFacebook.setAttribute('target', '_blank');
var imgFacebook = document.createElement('img');
imgFacebook.setAttribute('src', baseUrl + 'images/i_facebook.gif');
imgFacebook.setAttribute('alt', 'Facebook');
imgFacebook.setAttribute('border', '0');
imgFacebook.setAttribute('style', 'width:16px;height:16px;');
imgFacebook.setAttribute('class', 'WillStrohlSBImage');
aFacebook.appendChild(imgFacebook);
div.appendChild(aFacebook);
div.innerHTML = div.innerHTML + ' ';
}
/*
STUMBLEUPON
*/
if (sbStumbleUpon == 'true') {
// <a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.yoursite.com%2Farticle.php%26title%3DThe%2BArticle%2BTitle">
// <img border=0 src="http://cdn.stumble-upon.com/images/16x16_su_round.gif" alt=""> Stumble It!</a>
div.innerHTML = div.innerHTML + ' ';
var aStumbleUpon = document.createElement('a');
aStumbleUpon.setAttribute('href', 'http://www.stumbleupon.com/submit?url=' + document.location + '&=title=' + document.title);
aStumbleUpon.setAttribute('target', '_blank');
var imgStumbleUpon = document.createElement('img');
imgStumbleUpon.setAttribute('src', 'http://cdn.stumble-upon.com/images/16x16_su_round.gif');
imgStumbleUpon.setAttribute('alt', 'Facebook');
imgStumbleUpon.setAttribute('border', '0');
imgStumbleUpon.setAttribute('style', 'width:16px;height:16px;');
imgStumbleUpon.setAttribute('class', 'WillStrohlSBImage');
aStumbleUpon.appendChild(imgStumbleUpon);
div.appendChild(aStumbleUpon);
div.innerHTML = div.innerHTML + ' ';
}
WillStrohl.Widgets.SocialBookmarkWidget.callBaseMethod(this, 'render', [div]);
if (setStyle != 'false') {
$('.WillStrohlSBWrapper').attr('style', 'width:' + valWidth + ';height:' + valHeight + ';display:block;');
// possible additions to the above styles: border:1px solid #000000;background-color:#ffffff;vertical-align:middle;margin-top:auto;margin-bottom:auto;
$('.WillStrohlSBImage').css('border', '0px solid #ffffff');
}
if (runDebug) $DEBUGLINE('<br /><span class="NormalRed">Widget Suite: SocialBookmarks Debug Report Complete</span>');
}
}
catch (e) {
alert('An Error Occurred: ' + e);
}
}
/* END: render */
}
WillStrohl.Widgets.SocialBookmarkWidget.inheritsFrom(DotNetNuke.UI.WebControls.Widgets.BaseWidget);
WillStrohl.Widgets.SocialBookmarkWidget.registerClass('WillStrohl.Widgets.SocialBookmarkWidget', DotNetNuke.UI.WebControls.Widgets.BaseWidget);
DotNetNuke.UI.WebControls.Widgets.renderWidgetType('WillStrohl.Widgets.SocialBookmarkWidget');
/* END: WillStrohlWidget class */
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require ./lib/jquery.js
//= require ./lib/jquery.brbanks.js
//= require jquery_ujs
//= require ./lib/jquery-ui.js
//= require best_in_place
//= require ./lib/underscore.js
//= require ./lib/backbone.js
//= require ./lib/skull.js
//= require ./app/app.js
//= require ./lib/jquery.sticky.js
//= require ./lib/jquery.smooth-scroll.js
//= require ./lib/auto_campaign_url.js
//= require cocoon
//= require_tree ./lib
//= require_tree ./app
|
var classtesting_1_1internal_1_1_assert_helper =
[
[ "AssertHelper", "classtesting_1_1internal_1_1_assert_helper.html#ac2c9334518fd4087189b4505567a3c90", null ],
[ "~AssertHelper", "classtesting_1_1internal_1_1_assert_helper.html#a51c640785d4ed4a0155cc9aa857d8931", null ],
[ "operator=", "classtesting_1_1internal_1_1_assert_helper.html#ab721be11cb9aca8a361ca1f014ca5f80", null ]
]; |
import { NumberInput, LabelElement } from '../../libs/flow.module.js';
import { BaseNode } from '../core/BaseNode.js';
import { Vector4Node } from '../../renderers/nodes/Nodes.js';
export class Vector4Editor extends BaseNode {
constructor() {
const node = new Vector4Node();
super( 'Vector 4', 4, node, 350 );
const onUpdate = () => {
node.value.x = fieldX.getValue();
node.value.y = fieldY.getValue();
node.value.z = fieldZ.getValue();
node.value.w = fieldW.getValue();
};
const fieldX = new NumberInput().setTagColor( 'red' ).onChange( onUpdate );
const fieldY = new NumberInput().setTagColor( 'green' ).onChange( onUpdate );
const fieldZ = new NumberInput().setTagColor( 'blue' ).onChange( onUpdate );
const fieldW = new NumberInput().setTagColor( 'white' ).onChange( onUpdate );
this.add( new LabelElement( 'XYZW' )
.add( fieldX )
.add( fieldY )
.add( fieldZ )
.add( fieldW )
);
}
}
|
import BaseModel from './BaseModel';
import LocalStorageSync from '../utils/backboneLocalStorage';
import is from 'is_js';
export default class extends BaseModel {
localStorage() {
return new LocalStorageSync('__serverConfigs');
}
sync(...args) {
return LocalStorageSync.sync.apply(this, args);
}
defaults() {
return {
serverIp: 'localhost',
port: 4002,
SSL: false,
default: false,
};
}
validate(attrs) {
const errObj = {};
const addError = (fieldName, error) => {
errObj[fieldName] = errObj[fieldName] || [];
errObj[fieldName].push(error);
};
if (!is.existy(attrs.name) || is.empty(attrs.name)) {
addError('name', 'Please provide a value.');
} else {
// Slight hack since backbone doesn't document Model.collection and
// it will only refer to the first collection that a Model belongs.
// http://stackoverflow.com/a/15962917/632806
if (this.collection) {
const models = this.collection.where({ name: attrs.name });
if (models && models.length && (models.length > 1 || models[0].id !== attrs.id)) {
addError('name', 'There is already a configuration with that name.');
}
}
}
if (!is.existy(attrs.serverIp) || is.empty(attrs.serverIp)) {
addError('serverIp', 'Please provide a value.');
} else {
if (!is.ip(attrs.serverIp)) {
addError('serverIp', 'This does not appear to be a valid IP address.');
}
}
if (!this.isLocalServer()) {
if (!attrs.username) {
addError('username', 'Please provide a value.');
}
if (!attrs.password) {
addError('password', 'Please provide a value.');
}
if (!attrs.SSL) {
addError('SSL', 'SSL must be turned on for remote servers.');
}
}
if (!attrs.default) {
if (!is.number(attrs.port)) {
addError('port', 'Please provide a number.');
} else {
if (!is.within(attrs.port, -1, 65536)) {
addError('port', 'Please provide a number between 0 and 65535.');
}
}
} else {
if (is.existy(attrs.port) && attrs.port !== this.defaults().port) {
// For now, not allowing the port to be changed on the default server,
// since there is currently no way to set the port as an option
// on the command line, the local bundled server will always be started
// with the default port.
addError('port', `On the default server, the port can only be ${this.defaults().port}.`);
}
}
if (Object.keys(errObj).length) return errObj;
return undefined;
}
get httpUrl() {
const prefix = this.get('SSL') ? 'https' : 'http';
return `${prefix}://${this.get('serverIp')}:${this.get('port')}/`;
}
get socketUrl() {
const prefix = this.get('SSL') ? 'wss' : 'ws';
return `${prefix}://${this.get('serverIp')}:${this.get('port')}/ws`;
}
/**
* Indicates if we need to authenticate when connecting to this server.
*/
needsAuthentication() {
let needsAuth = false;
if (!this.isLocalServer()) {
needsAuth = true;
} else {
if (this.get('username') || this.get('password')) {
needsAuth = true;
}
}
return needsAuth;
}
/**
* Based on the ip, indicates whether this is a server running locally on
* your machine. It may be the local bundled server or it may be a locally
* run stand-alone server.
*/
isLocalServer() {
const ip = this.get('serverIp');
return ip === 'localhost' || ip === '127.0.0.1';
}
}
|
/*
* Stub the relevent parts of the request API
*/
exports.dummyReq = function(authorized, cert, headers) {
return {
client: {
authorized: authorized
},
connection: {
getPeerCertificate: function() {
return cert;
}
},
headers: headers
};
};
|
Meteor.methods({
togglePlay : function(){
var state = State.findOne({name: 'state'});
var pause = Boolean((state.controller.pause + 1 ) % 2);
// pause
if ( pause) { Meteor.call('pause'); }
// play
else{ Meteor.call('play'); }
},
pause : function(){
console.log("-- pause");
var state = State.findOne({name: 'state'});
Meteor.call('updateState', {"controller.pause": true } );
if (typeof footageTime !== 'undefined') {
Meteor.clearInterval(footageTime);
};
},
play : function(){
console.log("-- play");
var state = State.findOne({name: 'state'});
Meteor.call('updateState', {"controller.pause": false} );
if (typeof footageTime !== 'undefined') {
Meteor.clearInterval(footageTime);
}
Meteor.call( 'loadEvents' );
},
loadEvents : function(){
var interval = 25;
//Master timeline
console.log("-- loadEvent");
var state = State.findOne({name: 'state'});
var eventIndex = 0;
var events = Events.find(
{scenarioId: state.status.scenario, arriveTime: {$gte: state.status.currentTime}},
{sort: { arriveTime: 1 }}
).fetch();
var step = state.status.currentTime;
_.each(events, function(element, index, list){
if (events[index].type === 'street') {
events[index].duration = events[index].arriveTime - step;
tempStep = step;
step = events[index].arriveTime;
events[index].arriveTime = tempStep;
}
});
_.sortBy(events, "arriveTime");
console.log("-----");
console.log(events );
console.log("-----");
var ct = State.findOne({name: 'state'}).status.currentTime;
footageTime = Meteor.setInterval( function(){
//Master timeline
var duration = State.findOne({name: 'state'}).status.duration;
// console.log("ct:" + ct + "duration:" + duration);
Meteor.call('updateState',{"status.currentTime" : ct });
ct += interval / 100;
if ( ct > duration ) {
Meteor.call("goTo", 0);
}
if ( events.length > eventIndex && ct>events[eventIndex].arriveTime ) {
//LEDs events
if (events[eventIndex].type === 'led') {
var zones = [
"000196", /*none*/
"151161", /*top left*/
"138150", /*mid left*/
"105137", /*bottom left*/
"083104", /*middle left*/
"060082", /*middle right*/
"026059", /*bottom right*/
"013025", /*mid right*/
"000012", /*top right*/
"162171", /*left mirror*/
"172185", /*rear mirror*/
"186196" /*right mirror*/
];
var colors = [
"050000000000", /*red*/
"050000000050", /*orange*/
"000050000000", /*green*/
"050000000050" /*white*/
];
//Creating Serial message
console.log("LED event : ");
console.log(events[eventIndex]);
var pad = "000"
var animation = "" + events[eventIndex].animation;
var zone = "" + zones[events[eventIndex].zone];
var duration = "" + events[eventIndex].duration * 10;
duration = pad.substring(0, pad.length - duration.length) + duration;
var color = "" + colors[events[eventIndex].color];
var message = animation + zone + duration + color + ".";
Meteor.call("sendToLed", message );
//Defining LED zone
var activeZone = events[eventIndex].zone;
Meteor.call('updateState',{"status.ledZone" : activeZone });
Meteor.setTimeout(function(){
Meteor.call('updateState',{"status.ledZone" : 0 });
}, events[eventIndex].duration * 1000 );
}
//Street names events
if (events[eventIndex].type === 'street') {
console.log("street event : ");
console.log(events[eventIndex]);
Meteor.call('updateState',{
"status.street" : {
name : events[eventIndex].name,
src : events[eventIndex].filename,
visible : true,
animationLength : events[eventIndex].duration,
change : true,
}
});
Meteor.setTimeout(function(){
Meteor.call('updateState',{"status.street.visible" : false });
},
events[eventIndex].duration * 1000
);
}
eventIndex++;
}
var state = State.findOne({name: 'state'})
var speed = state && state.status.speed;
speed += Math.floor(Math.random() * 5) - 2;
Meteor.call('updateState',{"status.speed" : speed });
return speed;
}, interval * 10 );
},
goTo : function(timeIndex){
Meteor.call('updateState', { "controller.goToTime": true, "status.currentTime" : timeIndex} );
Meteor.call('pause');
Meteor.call('updateState', { "status.speed": 30} );
Meteor.setTimeout(function(){
Meteor.call('updateState', { "controller.goToTime": false} );
}, 250);
console.log('-- goTo : ' + timeIndex);
},
loadScenario : function(scenario, duration){
Meteor.call('updateState', {
"status": {
scenario : scenario,
currentTime : 0,
ledZone : 0,
duration : duration,
speed : 30,
street : {
name : "default",
src : "",
visible : false,
}
},
"controller": {
scenario : scenario,
pause : true,
goToTime : false,
}
});
Meteor.call('goTo', 0);
console.log('-- load scenario : ' + scenario);
},
}); |
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import {
Card,
CardBody,
CardContent,
CardHeader,
CardTitle,
CardSubtitle,
CardBadge,
} from '@strapi/design-system/Card';
import { Typography } from '@strapi/design-system/Typography';
import { Stack } from '@strapi/design-system/Stack';
import { Box } from '@strapi/design-system/Box';
import { useIntl } from 'react-intl';
import { getTrad } from '../../utils';
import { AssetType } from '../../constants';
import { useUpload } from '../../hooks/useUpload';
import { UploadProgress } from '../UploadProgress';
const UploadProgressWrapper = styled.div`
height: ${88 / 16}rem;
width: 100%;
`;
const Extension = styled.span`
text-transform: uppercase;
`;
export const UploadingAssetCard = ({ asset, onCancel, onStatusChange, addUploadedFiles }) => {
const { upload, cancel, error, progress, status } = useUpload(asset);
const { formatMessage } = useIntl();
let badgeContent;
if (asset.type === AssetType.Image) {
badgeContent = formatMessage({
id: getTrad('settings.section.image.label'),
defaultMessage: 'Image',
});
} else if (asset.type === AssetType.Video) {
badgeContent = formatMessage({
id: getTrad('settings.section.video.label'),
defaultMessage: 'Video',
});
} else if (asset.type === AssetType.Audio) {
badgeContent = formatMessage({
id: getTrad('settings.section.audio.label'),
defaultMessage: 'Audio',
});
} else {
badgeContent = formatMessage({
id: getTrad('settings.section.doc.label'),
defaultMessage: 'Doc',
});
}
useEffect(() => {
const uploadFile = async () => {
const files = await upload(asset);
if (addUploadedFiles) {
addUploadedFiles(files);
}
};
uploadFile();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
onStatusChange(status);
}, [status, onStatusChange]);
const handleCancel = () => {
cancel();
onCancel(asset.rawFile);
};
return (
<Stack size={1}>
<Card borderColor={error ? 'danger600' : undefined}>
<CardHeader>
<UploadProgressWrapper>
<UploadProgress error={error} onCancel={handleCancel} progress={progress} />
</UploadProgressWrapper>
</CardHeader>
<CardBody>
<CardContent>
<Box paddingTop={1}>
<CardTitle as="h2">{asset.name}</CardTitle>
</Box>
<CardSubtitle>
<Extension>{asset.ext}</Extension>
</CardSubtitle>
</CardContent>
<CardBadge>{badgeContent}</CardBadge>
</CardBody>
</Card>
{error ? (
<Typography variant="pi" fontWeight="bold" textColor="danger600">
{error.message}
</Typography>
) : (
undefined
)}
</Stack>
);
};
UploadingAssetCard.defaultProps = {
addUploadedFiles: undefined,
};
UploadingAssetCard.propTypes = {
addUploadedFiles: PropTypes.func,
asset: PropTypes.shape({
name: PropTypes.string,
ext: PropTypes.string,
rawFile: PropTypes.instanceOf(File),
type: PropTypes.oneOf(Object.values(AssetType)),
}).isRequired,
onCancel: PropTypes.func.isRequired,
onStatusChange: PropTypes.func.isRequired,
};
|
var hyperstream = require('../');
var test = require('tap').test;
var concat = require('concat-stream');
var through = require('through2');
test('string _html', function (t) {
t.plan(1);
var hs = hyperstream({
'.row': { _html: '<b>beep boop</b>' }
});
hs.pipe(concat(function (body) {
t.equal(
body.toString('utf8'),
'<div class="row"><b>beep boop</b></div>'
);
}));
hs.end('<div class="row"></div>');
});
test('stream _html', function (t) {
t.plan(1);
var stream = through();
stream.push('<b>beep boop</b>');
stream.push(null);
var hs = hyperstream({
'.row': { _html: stream }
});
hs.pipe(concat(function (body) {
t.equal(
body.toString('utf8'),
'<div class="row"><b>beep boop</b></div>'
);
}));
hs.end('<div class="row"></div>');
});
|
import invariant from "@octetstream/invariant"
import isFunction from "lodash/isFunction"
import wrapAction from "./wrapAction"
function setCommand(
commander, env, command, {alias, description, action, option} = {}
) {
invariant(
!isFunction(action), TypeError,
"Command action should be a function."
)
commander
.command(command)
.description(description)
.action(wrapAction(action, env))
if (alias) {
commander.alias(alias)
}
if (option) {
commander.option(option)
}
return commander
}
export default setCommand
|
/*!
* Bootstrap-select v1.13.12 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2019 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Nič izbranega',
noneResultsText: 'Ni zadetkov za {0}',
countSelectedText: '{0} od {1} izbranih',
maxOptionsText: function (numAll, numGroup) {
return [
'Omejitev dosežena (max. izbranih: {n})',
'Omejitev skupine dosežena (max. izbranih: {n})'
];
},
selectAllText: 'Izberi vse',
deselectAllText: 'Počisti izbor',
multipleSeparator: ', '
};
})(jQuery);
}));
//# sourceMappingURL=defaults-sl_SI.js.map |
// Returns function that returns deferred or promise object.
//
// 1. If invoked without arguments then deferred object is returned
// Deferred object consist of promise (unresolved) function and resolve
// function through which we resolve promise
// 2. If invoked with one argument then promise is returned which resolved value
// is given argument. Argument may be any value (even undefined),
// if it's promise then same promise is returned
// 3. If invoked with more than one arguments then promise that resolves with
// array of all resolved arguments is returned.
'use strict';
var isError = require('es5-ext/error/is-error')
, noop = require('es5-ext/function/noop')
, isPromise = require('./is-promise')
, every = Array.prototype.every, push = Array.prototype.push
, Deferred, createDeferred, count = 0, timeout, extendShim, ext
, protoSupported = Boolean(isPromise.__proto__)
, resolve, assimilate;
extendShim = function (promise) {
ext._names.forEach(function (name) {
promise[name] = function () {
return promise.__proto__[name].apply(promise, arguments);
};
});
promise.returnsPromise = true;
promise.resolved = promise.__proto__.resolved;
};
resolve = function (value, failed) {
var promise = function (win, fail) { return promise.then(win, fail); };
promise.value = value;
promise.failed = failed;
promise.__proto__ = ext._resolved;
if (!protoSupported) { extendShim(promise); }
if (createDeferred._profile) createDeferred._profile(true);
return promise;
};
Deferred = function () {
var promise = function (win, fail) { return promise.then(win, fail); };
if (!count) timeout = setTimeout(noop, 1e9);
++count;
if (createDeferred._monitor) promise.monitor = createDeferred._monitor();
promise.__proto__ = ext._unresolved;
if (!protoSupported) extendShim(promise);
(createDeferred._profile && createDeferred._profile());
this.promise = promise;
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
};
Deferred.prototype = {
resolved: false,
_settle: function (value) {
var i, name, data, deps, dPromise, nuDeps;
this.promise.value = value;
this.promise.__proto__ = ext._resolved;
if (!protoSupported) this.promise.resolved = true;
deps = this.promise.dependencies;
delete this.promise.dependencies;
while (deps) {
for (i = 0; (dPromise = deps[i]); ++i) {
dPromise.value = value;
dPromise.failed = this.failed;
dPromise.__proto__ = ext._resolved;
if (!protoSupported) dPromise.resolved = true;
delete dPromise.pending;
if (dPromise.dependencies) {
if (!nuDeps) nuDeps = dPromise.dependencies;
else push.apply(nuDeps, dPromise.dependencies);
delete dPromise.dependencies;
}
}
deps = nuDeps;
nuDeps = null;
}
if ((data = this.promise.pending)) {
for (i = 0; (name = data[i]); ++i) {
ext._onresolve[name].apply(this.promise, data[++i]);
}
delete this.promise.pending;
}
return this.promise;
},
resolve: function (value) {
if (this.resolved) return this.promise;
this.resolved = true;
if (!--count) clearTimeout(timeout);
if (this.promise.monitor) clearTimeout(this.promise.monitor);
value = assimilate(value);
if (isPromise(value)) {
if (!value.resolved) {
if (!value.dependencies) {
value.dependencies = [];
}
value.dependencies.push(this.promise);
if (this.promise.pending) {
if (value.pending) {
this.promise.pending.forEach(function (promise) { value.pending.push(promise); });
this.promise.pending = value.pending;
if (this.promise.dependencies) {
this.promise.dependencies.forEach(function self(dPromise) {
dPromise.pending = value.pending;
if (dPromise.dependencies) {
dPromise.dependencies.forEach(self);
}
});
}
} else {
value.pending = this.promise.pending;
}
} else if (value.pending) {
this.promise.pending = value.pending;
} else {
this.promise.pending = value.pending = [];
}
return this.promise;
}
this.promise.failed = value.failed;
value = value.value;
}
return this._settle(value);
},
reject: function (error) {
if (this.resolved) return this.promise;
this.resolved = true;
if (!--count) clearTimeout(timeout);
if (this.promise.monitor) clearTimeout(this.promise.monitor);
this.promise.failed = true;
return this._settle(error);
}
};
module.exports = createDeferred = function (value) {
var l = arguments.length, d, waiting, initialized, result;
if (!l) return new Deferred();
if (l > 1) {
d = new Deferred();
waiting = 0;
result = new Array(l);
every.call(arguments, function (value, index) {
value = assimilate(value);
if (!isPromise(value)) {
result[index] = value;
return true;
}
if (value.resolved) {
if (value.failed) {
d.reject(value.value);
return false;
}
result[index] = value.value;
return true;
}
++waiting;
value.done(function (value) {
result[index] = value;
if (!--waiting && initialized) d.resolve(result);
}, d.reject);
return true;
});
initialized = true;
if (!waiting) d.resolve(result);
return d.promise;
}
value = assimilate(value);
if (isPromise(value)) return value;
return resolve(value, isError(value));
};
createDeferred.Deferred = Deferred;
createDeferred.reject = function (value) { return resolve(value, true); };
createDeferred.resolve = function (value) {
value = assimilate(value);
if (isPromise(value)) return value;
return resolve(value, false);
};
ext = require('./_ext');
assimilate = require('./assimilate');
|
function reader2Promise(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
}
reader.onerror = function() {
reject(reader.error);
}
});
}
function blob2ArrayBuffer(blob) {
let reader = new FileReader();
reader.readAsArrayBuffer(blob);
return reader2Promise(reader);
}
function blob2text(blob) {
let reader = new FileReader();
reader.readAsText(blob);
return reader2Promise(reader);
}
function bodyType(body) {
if (typeof body === 'string') {
return 'text';
} else if (Blob.prototype.isPrototypeOf(body)) {
return 'blob';
} else if (FormData.prototype.isPrototypeOf(body)) {
return 'formData';
} else if (body && typeof body === 'object') {
return 'json';
} else {
return null;
}
}
function parseJSON(body) {
try {
return JSON.parse(body);
} catch(ex) {
throw 'Invalid JSON';
}
}
const map = {
text: {
json: (body) => Promise.resolve(JSON.stringify(body)),
blob: (body) => blob2text(body),
},
json: {
text: (body) => Promise.resolve(parseJSON(body)),
blob: (body) => blob2text(body).then(parseJSON)
},
blob: {
text: (body) => Promise.resolve(new Blob([body])),
json: (body) => Promise.resolve(new Blob([JSON.stringify(body)]))
},
arrayBuffer: {
blob: (body) => blob2ArrayBuffer(body),
}
};
export function convertBody(body, to) {
let from = bodyType(body);
if(body===null || body===undefined || !from || from===to) {
return Promise.resolve(body);
} else if(map[to] && map[to][from]) {
return map[to][from](body);
} else {
return Promise.reject(`Convertion from ${from} to ${to} not supported`);
}
}
export default class Body {
constructor() {
this.bodyUsed = false;
}
text() {
return this.consumeBody().then(body=>convertBody(body, 'text'));
}
blob() {
return this.consumeBody().then(body=>convertBody(body, 'blob'));
}
formData() {
return this.consumeBody().then(body=>convertBody(body, 'formData'));
}
json() {
return this.consumeBody().then(body=>convertBody(body, 'json'));
}
arrayBuffer() {
return this.consumeBody().then(body=>convertBody(body, 'ArrayBuffer'));
}
consumeBody() {
if(this.bodyUsed) {
// TODO: Reject when body was used?
// return Promise.reject(...);
return Promise.resolve(this._body);
} else {
this.bodyUsed = true;
return Promise.resolve(this._body);
}
}
}
|
import { GraphQLInt, GraphQLObjectType, GraphQLString } from 'graphql';
export default new GraphQLObjectType({
name: 'Analytics',
fields: () => ({
date: { type: GraphQLString },
lineUser: { type: GraphQLInt },
lineVisit: { type: GraphQLInt },
webUser: { type: GraphQLInt },
webVisit: { type: GraphQLInt },
}),
});
|
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var editable_text_base_common_1 = require("./editable-text-base-common");
__export(require("./editable-text-base-common"));
var EditableTextBase = (function (_super) {
__extends(EditableTextBase, _super);
function EditableTextBase() {
return _super !== null && _super.apply(this, arguments) || this;
}
EditableTextBase.prototype.dismissSoftInput = function () {
this.nativeView.resignFirstResponder();
this.notify({ eventName: EditableTextBase.blurEvent, object: this });
};
EditableTextBase.prototype[editable_text_base_common_1.keyboardTypeProperty.getDefault] = function () {
var keyboardType = this.nativeView.keyboardType;
switch (keyboardType) {
case 2:
return "number";
case 5:
return "phone";
case 3:
return "url";
case 7:
return "email";
default:
return keyboardType.toString();
}
};
EditableTextBase.prototype[editable_text_base_common_1.keyboardTypeProperty.setNative] = function (value) {
var newKeyboardType;
switch (value) {
case "datetime":
newKeyboardType = 2;
break;
case "phone":
newKeyboardType = 5;
break;
case "number":
newKeyboardType = 2;
break;
case "url":
newKeyboardType = 3;
break;
case "email":
newKeyboardType = 7;
break;
default:
var kt = +value;
if (!isNaN(kt)) {
newKeyboardType = kt;
}
else {
newKeyboardType = 0;
}
break;
}
this.nativeView.keyboardType = newKeyboardType;
};
EditableTextBase.prototype[editable_text_base_common_1.returnKeyTypeProperty.getDefault] = function () {
var returnKeyType = this.nativeView.returnKeyType;
switch (returnKeyType) {
case 9:
return "done";
case 1:
return "go";
case 4:
return "next";
case 6:
return "search";
case 7:
return "send";
default:
return returnKeyType.toString();
}
};
EditableTextBase.prototype[editable_text_base_common_1.returnKeyTypeProperty.setNative] = function (value) {
var newValue;
switch (value) {
case "done":
newValue = 9;
break;
case "go":
newValue = 1;
break;
case "next":
newValue = 4;
break;
case "search":
newValue = 6;
break;
case "send":
newValue = 7;
break;
default:
var rkt = +value;
if (!isNaN(rkt)) {
newValue = rkt;
}
else {
newValue = 0;
}
break;
}
this.nativeView.returnKeyType = newValue;
};
EditableTextBase.prototype[editable_text_base_common_1.autocapitalizationTypeProperty.getDefault] = function () {
var autocapitalizationType = this.nativeView.autocapitalizationType;
switch (autocapitalizationType) {
case 0:
return "none";
case 1:
return "words";
case 2:
return "sentences";
case 3:
return "allcharacters";
default:
throw new Error("Invalid autocapitalizationType value:" + autocapitalizationType);
}
};
EditableTextBase.prototype[editable_text_base_common_1.autocapitalizationTypeProperty.setNative] = function (value) {
var newValue;
switch (value) {
case "none":
newValue = 0;
break;
case "words":
newValue = 1;
break;
case "sentences":
newValue = 2;
break;
case "allcharacters":
newValue = 3;
break;
default:
newValue = 2;
break;
}
this.nativeView.autocapitalizationType = newValue;
};
EditableTextBase.prototype[editable_text_base_common_1.autocorrectProperty.getDefault] = function () {
var autocorrectionType = this.nativeView.autocorrectionType;
switch (autocorrectionType) {
case 2:
return true;
case 1:
return false;
case 0:
return autocorrectionType;
}
};
EditableTextBase.prototype[editable_text_base_common_1.autocorrectProperty.setNative] = function (value) {
var newValue;
if (typeof value === "number") {
newValue = 0;
}
else if (value) {
newValue = 2;
}
else {
newValue = 1;
}
this.nativeView.autocorrectionType = newValue;
};
return EditableTextBase;
}(editable_text_base_common_1.EditableTextBase));
exports.EditableTextBase = EditableTextBase;
function _updateCharactersInRangeReplacementString(formattedText, rangeLocation, rangeLength, replacementString) {
var deletingText = !replacementString;
var currentLocation = 0;
for (var i = 0, length_1 = formattedText.spans.length; i < length_1; i++) {
var span = formattedText.spans.getItem(i);
if (currentLocation <= rangeLocation && rangeLocation < (currentLocation + span.text.length)) {
var newText = splice(span.text, rangeLocation - currentLocation, deletingText ? rangeLength : 0, replacementString);
span._setTextInternal(newText);
return;
}
currentLocation += span.text.length;
}
}
exports._updateCharactersInRangeReplacementString = _updateCharactersInRangeReplacementString;
function splice(value, start, delCount, newSubStr) {
return value.slice(0, start) + newSubStr + value.slice(start + Math.abs(delCount));
}
//# sourceMappingURL=editable-text-base.ios.js.map |
function addScriptTag(src) {
var script = document.createElement('script')
script.setAttribute("type", "text/javascript")
script.src = src
document.body.appendChild(script)
}
window.onload = function () {
addScriptTag('http://res.wx.qq.com/open/js/jweixin-1.2.0.js');
}
|
function createNodeObservable(fn, ctx, selector, args) {
var o = new AsyncSubject();
args.push(createNodeHandler(o, ctx, selector));
fn.apply(ctx, args);
return o.asObservable();
}
function createNodeHandler(o, ctx, selector) {
return function handler () {
var err = arguments[0];
if (err) { return o.onError(err); }
var len = arguments.length, results = [];
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (isFunction(selector)) {
var results = tryCatch(selector).apply(ctx, results);
if (results === errorObj) { return o.onError(results.e); }
o.onNext(results);
} else {
if (results.length <= 1) {
o.onNext(results[0]);
} else {
o.onNext(results);
}
}
o.onCompleted();
};
}
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} fn The function to call
* @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (fn, ctx, selector) {
return function () {
typeof ctx === 'undefined' && (ctx = this);
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return createNodeObservable(fn, ctx, selector, args);
};
};
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
gulp.task('partials', function ()
{
return gulp.src([
path.join(conf.paths.src, '/app/**/*.html'),
path.join(conf.paths.tmp, '/serve/app/**/*.html')
])
.pipe($.htmlmin({
collapseWhitespace: true,
maxLineLength : 120,
removeComments : true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'cvapp',
root : 'app'
}))
.pipe(gulp.dest(conf.paths.tmp + '/partials/'));
});
gulp.task('html', ['inject', 'partials'], function ()
{
var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), {read: false});
var partialsInjectOptions = {
starttag : '<!-- inject:partials -->',
ignorePath : path.join(conf.paths.tmp, '/partials'),
addRootSlash: false
};
var cssFilter = $.filter('**/*.css', {restore: true});
var jsFilter = $.filter('**/*.js', {restore: true});
var htmlFilter = $.filter('*.html', {restore: true});
return gulp.src(path.join(conf.paths.tmp, '/serve/*.html'))
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe($.useref())
.pipe(jsFilter)
.pipe($.sourcemaps.init())
.pipe($.ngAnnotate())
.pipe($.uglify({preserveComments: $.uglifySaveLicense})).on('error', conf.errorHandler('Uglify'))
.pipe($.rev())
.pipe($.sourcemaps.write('maps'))
.pipe(jsFilter.restore)
.pipe(cssFilter)
.pipe($.sourcemaps.init())
.pipe($.cleanCss())
.pipe($.rev())
.pipe($.sourcemaps.write('maps'))
.pipe(cssFilter.restore)
.pipe($.revReplace())
.pipe(htmlFilter)
.pipe($.htmlmin({
collapseWhitespace: true,
maxLineLength : 120,
removeComments : true
}))
.pipe(htmlFilter.restore)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')))
.pipe($.size({
title : path.join(conf.paths.dist, '/'),
showFiles: true
}));
});
// Only applies for fonts from bower dependencies
// Custom fonts are handled by the "other" task
gulp.task('fonts', function ()
{
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/')));
});
gulp.task('other', function ()
{
var fileFilter = $.filter(function (file)
{
return file.stat.isFile();
});
return gulp.src([
path.join(conf.paths.src, '/**/*'),
path.join('!' + conf.paths.src, '/**/*.{html,css,js,scss}')
])
.pipe(fileFilter)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')));
});
gulp.task('clean', function ()
{
return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]);
});
gulp.task('build', ['html', 'fonts', 'other']); |
/**
* Map
*/
var $map = $('#map'), $googleMap;
function buildMap() {
$('<div class="map-container"/>').prependTo($map);
var $node = $('#map .map-container')[0];
$googleMap = new google.maps.Map($node, {
center: {lat: -16.707196, lng: -49.275969},
zoom: 15,
scrollwheel: false,
streetViewControl: false,
mapTypeControl: false
});
var service = new google.maps.places.PlacesService($googleMap);
service.getDetails({ placeId: 'ChIJ9UUMqi_xXpMR7ze2ZnSuX1Y' }, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: $googleMap,
position: place.geometry.location,
title: 'CCBEU Matriz - Novo Prédio'
});
setInfoWindow = function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'<br>' + place.formatted_address);
infowindow.open($googleMap, marker);
};
google.maps.event.addListener(marker, 'click', function() {
setInfoWindow();
});
setInfoWindow();
}
});
};
$(document).ready(function(){
$(window).resize(function() {
jQuery("#map .map-container").remove();
buildMap();
});
});
|
const { client } = require('nightwatch-cucumber')
const { Given, Then, When } = require('cucumber')
Given(/^I open Google`s search page$/, () => {
return client
.url('http://google.com')
.waitForElementVisible('body', 1000)
})
Then(/^the title is "(.*?)"$/, (text) => {
return client.assert.title(text)
})
Then(/^the Google search form exists$/, () => {
return client.assert.visible('input[name="q"]')
})
|
const path = require('path');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
return `module.exports = ${JSON.stringify(path.basename(filename))};`;
}
};
|
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
VERSION: '0.1',
LANGUAGE: 'None',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
}; |
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/ControlPictures.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* 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.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXGeneral,{9251:[16,120,500,40,460]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/Regular/ControlPictures.js");
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles,
* Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will
* be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example:
*
* ```
* graphics.beginFill(0xff0000);
* graphics.drawCircle(50, 50, 100);
* graphics.endFill();
* ```
*
* This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50.
*
* When a Graphics object is rendered it will render differently based on if the game is running under Canvas or
* WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the
* graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes.
*
* If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help
* performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it.
* You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then
* you should avoid doing this, as it will constantly generate new textures, which will consume memory.
*
* As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful
* in their complexity and quantity of them in your game.
*
* @class Phaser.Graphics
* @constructor
* @extends PIXI.DisplayObjectContainer
* @extends Phaser.Component.Core
* @extends Phaser.Component.Angle
* @extends Phaser.Component.AutoCull
* @extends Phaser.Component.Bounds
* @extends Phaser.Component.Destroy
* @extends Phaser.Component.FixedToCamera
* @extends Phaser.Component.InputEnabled
* @extends Phaser.Component.InWorld
* @extends Phaser.Component.LifeSpan
* @extends Phaser.Component.PhysicsBody
* @extends Phaser.Component.Reset
* @param {Phaser.Game} game - Current game instance.
* @param {number} [x=0] - X position of the new graphics object.
* @param {number} [y=0] - Y position of the new graphics object.
*/
Phaser.Graphics = function (game, x, y) {
if (x === undefined) { x = 0; }
if (y === undefined) { y = 0; }
/**
* @property {number} type - The const type of this object.
* @default
*/
this.type = Phaser.GRAPHICS;
/**
* @property {number} physicsType - The const physics body type of this object.
* @readonly
*/
this.physicsType = Phaser.SPRITE;
/**
* @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value.
* @private
*/
this.anchor = new Phaser.Point();
PIXI.DisplayObjectContainer.call(this);
this.renderable = true;
/**
* The alpha value used when filling the Graphics object.
*
* @property fillAlpha
* @type Number
*/
this.fillAlpha = 1;
/**
* The width (thickness) of any lines drawn.
*
* @property lineWidth
* @type Number
*/
this.lineWidth = 0;
/**
* The color of any lines drawn.
*
* @property lineColor
* @type String
* @default 0
*/
this.lineColor = 0;
/**
* Graphics data
*
* @property graphicsData
* @type Array
* @private
*/
this.graphicsData = [];
/**
* The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint.
*
* @property tint
* @type Number
* @default 0xFFFFFF
*/
this.tint = 0xFFFFFF;
/**
* The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode.
*
* @property blendMode
* @type Number
* @default PIXI.blendModes.NORMAL;
*/
this.blendMode = PIXI.blendModes.NORMAL;
/**
* Current path
*
* @property currentPath
* @type Object
* @private
*/
this.currentPath = null;
/**
* Array containing some WebGL-related properties used by the WebGL renderer.
*
* @property _webGL
* @type Array
* @private
*/
this._webGL = [];
/**
* Whether this shape is being used as a mask.
*
* @property isMask
* @type Boolean
*/
this.isMask = false;
/**
* The bounds' padding used for bounds calculation.
*
* @property boundsPadding
* @type Number
*/
this.boundsPadding = 0;
this._localBounds = new Phaser.Rectangle(0, 0, 1, 1);
/**
* Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated.
*
* @property dirty
* @type Boolean
* @private
*/
this.dirty = true;
/**
* Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to.
* If this is set to true then the updateLocalBounds is called once in the postUpdate method.
*
* @property _boundsDirty
* @type Boolean
* @private
*/
this._boundsDirty = false;
/**
* Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated.
*
* @property webGLDirty
* @type Boolean
* @private
*/
this.webGLDirty = false;
/**
* Used to detect if the cached sprite object needs to be updated.
*
* @property cachedSpriteDirty
* @type Boolean
* @private
*/
this.cachedSpriteDirty = false;
Phaser.Component.Core.init.call(this, game, x, y, '', null);
};
Phaser.Graphics.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
Phaser.Graphics.prototype.constructor = Phaser.Graphics;
Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [
'Angle',
'AutoCull',
'Bounds',
'Destroy',
'FixedToCamera',
'InputEnabled',
'InWorld',
'LifeSpan',
'PhysicsBody',
'Reset'
]);
Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
/**
* Automatically called by World.preUpdate.
*
* @method Phaser.Graphics#preUpdate
*/
Phaser.Graphics.prototype.preUpdate = function () {
if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
{
return false;
}
return this.preUpdateCore();
};
/**
* Automatically called by World
*
* @method Phaser.Graphics#postUpdate
*/
Phaser.Graphics.prototype.postUpdate = function () {
Phaser.Component.PhysicsBody.postUpdate.call(this);
Phaser.Component.FixedToCamera.postUpdate.call(this);
if (this._boundsDirty)
{
this.updateLocalBounds();
this._boundsDirty = false;
}
for (var i = 0; i < this.children.length; i++)
{
this.children[i].postUpdate();
}
};
/**
* Destroy this Graphics instance.
*
* @method Phaser.Graphics#destroy
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.Graphics.prototype.destroy = function (destroyChildren) {
this.clear();
Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
};
/**
* Draws a single {Phaser.Polygon} triangle from a {Phaser.Point} array
*
* @method Phaser.Graphics#drawTriangle
* @param {Array<Phaser.Point>} points - An array of Phaser.Points that make up the three vertices of this triangle
* @param {boolean} [cull=false] - Should we check if the triangle is back-facing
*/
Phaser.Graphics.prototype.drawTriangle = function (points, cull) {
if (cull === undefined) { cull = false; }
var triangle = new Phaser.Polygon(points);
if (cull)
{
var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y);
var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y);
var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y);
var faceNormal = cb.cross(ab);
if (cameraToFace.dot(faceNormal) > 0)
{
this.drawPolygon(triangle);
}
}
else
{
this.drawPolygon(triangle);
}
};
/**
* Draws {Phaser.Polygon} triangles
*
* @method Phaser.Graphics#drawTriangles
* @param {Array<Phaser.Point>|Array<number>} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles
* @param {Array<number>} {indices=null} - An array of numbers that describe what order to draw the vertices in
* @param {boolean} [cull=false] - Should we check if the triangle is back-facing
*/
Phaser.Graphics.prototype.drawTriangles = function (vertices, indices, cull) {
if (cull === undefined) { cull = false; }
var point1 = new Phaser.Point();
var point2 = new Phaser.Point();
var point3 = new Phaser.Point();
var points = [];
var i;
if (!indices)
{
if (vertices[0] instanceof Phaser.Point)
{
for (i = 0; i < vertices.length / 3; i++)
{
this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull);
}
}
else
{
for (i = 0; i < vertices.length / 6; i++)
{
point1.x = vertices[i * 6 + 0];
point1.y = vertices[i * 6 + 1];
point2.x = vertices[i * 6 + 2];
point2.y = vertices[i * 6 + 3];
point3.x = vertices[i * 6 + 4];
point3.y = vertices[i * 6 + 5];
this.drawTriangle([point1, point2, point3], cull);
}
}
}
else
{
if (vertices[0] instanceof Phaser.Point)
{
for (i = 0; i < indices.length /3; i++)
{
points.push(vertices[indices[i * 3 ]]);
points.push(vertices[indices[i * 3 + 1]]);
points.push(vertices[indices[i * 3 + 2]]);
if (points.length === 3)
{
this.drawTriangle(points, cull);
points = [];
}
}
}
else
{
for (i = 0; i < indices.length; i++)
{
point1.x = vertices[indices[i] * 2];
point1.y = vertices[indices[i] * 2 + 1];
points.push(point1.copyTo({}));
if (points.length === 3)
{
this.drawTriangle(points, cull);
points = [];
}
}
}
}
};
/**
* Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
*
* @method Phaser.Graphics#lineStyle
* @param lineWidth {Number} width of the line to draw, will update the objects stored style
* @param color {Number} color of the line to draw, will update the objects stored style
* @param alpha {Number} alpha of the line to draw, will update the objects stored style
* @return {Graphics}
*/
Phaser.Graphics.prototype.lineStyle = function (lineWidth, color, alpha) {
this.lineWidth = lineWidth || 0;
this.lineColor = color || 0;
this.lineAlpha = (alpha === undefined) ? 1 : alpha;
if (this.currentPath)
{
if (this.currentPath.shape.points.length)
{
// halfway through a line? start a new one!
this.drawShape(new Phaser.Polygon(this.currentPath.shape.points.slice(-2)));
}
else
{
// otherwise its empty so lets just set the line properties
this.currentPath.lineWidth = this.lineWidth;
this.currentPath.lineColor = this.lineColor;
this.currentPath.lineAlpha = this.lineAlpha;
}
}
return this;
};
/**
* Moves the current drawing position to x, y.
*
* @method Phaser.Graphics#moveTo
* @param x {Number} the X coordinate to move to
* @param y {Number} the Y coordinate to move to
* @return {Graphics}
*/
Phaser.Graphics.prototype.moveTo = function (x, y) {
this.drawShape(new Phaser.Polygon([ x, y ]));
return this;
};
/**
* Draws a line using the current line style from the current drawing position to (x, y);
* The current drawing position is then set to (x, y).
*
* @method Phaser.Graphics#lineTo
* @param x {Number} the X coordinate to draw to
* @param y {Number} the Y coordinate to draw to
* @return {Graphics}
*/
Phaser.Graphics.prototype.lineTo = function (x, y) {
if (!this.currentPath)
{
this.moveTo(0, 0);
}
this.currentPath.shape.points.push(x, y);
this.dirty = true;
this._boundsDirty = true;
return this;
};
/**
* Calculate the points for a quadratic bezier curve and then draws it.
* Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
*
* @method Phaser.Graphics#quadraticCurveTo
* @param cpX {Number} Control point x
* @param cpY {Number} Control point y
* @param toX {Number} Destination point x
* @param toY {Number} Destination point y
* @return {Graphics}
*/
Phaser.Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) {
if (this.currentPath)
{
if (this.currentPath.shape.points.length === 0)
{
this.currentPath.shape.points = [ 0, 0 ];
}
}
else
{
this.moveTo(0,0);
}
var xa,
ya,
n = 20,
points = this.currentPath.shape.points;
if (points.length === 0)
{
this.moveTo(0, 0);
}
var fromX = points[points.length - 2];
var fromY = points[points.length - 1];
var j = 0;
for (var i = 1; i <= n; ++i)
{
j = i / n;
xa = fromX + ((cpX - fromX) * j);
ya = fromY + ((cpY - fromY) * j);
points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ),
ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) );
}
this.dirty = true;
this._boundsDirty = true;
return this;
};
/**
* Calculate the points for a bezier curve and then draws it.
*
* @method Phaser.Graphics#bezierCurveTo
* @param cpX {Number} Control point x
* @param cpY {Number} Control point y
* @param cpX2 {Number} Second Control point x
* @param cpY2 {Number} Second Control point y
* @param toX {Number} Destination point x
* @param toY {Number} Destination point y
* @return {Graphics}
*/
Phaser.Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) {
if (this.currentPath)
{
if (this.currentPath.shape.points.length === 0)
{
this.currentPath.shape.points = [0, 0];
}
}
else
{
this.moveTo(0,0);
}
var n = 20,
dt,
dt2,
dt3,
t2,
t3,
points = this.currentPath.shape.points;
var fromX = points[points.length-2];
var fromY = points[points.length-1];
var j = 0;
for (var i = 1; i <= n; ++i)
{
j = i / n;
dt = (1 - j);
dt2 = dt * dt;
dt3 = dt2 * dt;
t2 = j * j;
t3 = t2 * j;
points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX,
dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY);
}
this.dirty = true;
this._boundsDirty = true;
return this;
};
/**
* The arcTo() method creates an arc/curve between two tangents on the canvas.
*
* "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
*
* @method Phaser.Graphics#arcTo
* @param x1 {Number} The x-coordinate of the beginning of the arc
* @param y1 {Number} The y-coordinate of the beginning of the arc
* @param x2 {Number} The x-coordinate of the end of the arc
* @param y2 {Number} The y-coordinate of the end of the arc
* @param radius {Number} The radius of the arc
* @return {Graphics}
*/
Phaser.Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) {
if (this.currentPath)
{
if (this.currentPath.shape.points.length === 0)
{
this.currentPath.shape.points.push(x1, y1);
}
}
else
{
this.moveTo(x1, y1);
}
var points = this.currentPath.shape.points,
fromX = points[points.length-2],
fromY = points[points.length-1],
a1 = fromY - y1,
b1 = fromX - x1,
a2 = y2 - y1,
b2 = x2 - x1,
mm = Math.abs(a1 * b2 - b1 * a2);
if (mm < 1.0e-8 || radius === 0)
{
if (points[points.length-2] !== x1 || points[points.length-1] !== y1)
{
points.push(x1, y1);
}
}
else
{
var dd = a1 * a1 + b1 * b1,
cc = a2 * a2 + b2 * b2,
tt = a1 * a2 + b1 * b2,
k1 = radius * Math.sqrt(dd) / mm,
k2 = radius * Math.sqrt(cc) / mm,
j1 = k1 * tt / dd,
j2 = k2 * tt / cc,
cx = k1 * b2 + k2 * b1,
cy = k1 * a2 + k2 * a1,
px = b1 * (k2 + j1),
py = a1 * (k2 + j1),
qx = b2 * (k1 + j2),
qy = a2 * (k1 + j2),
startAngle = Math.atan2(py - cy, px - cx),
endAngle = Math.atan2(qy - cy, qx - cx);
this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1);
}
this.dirty = true;
this._boundsDirty = true;
return this;
};
/**
* The arc method creates an arc/curve (used to create circles, or parts of circles).
*
* @method Phaser.Graphics#arc
* @param cx {Number} The x-coordinate of the center of the circle
* @param cy {Number} The y-coordinate of the center of the circle
* @param radius {Number} The radius of the circle
* @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
* @param endAngle {Number} The ending angle, in radians
* @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
* @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number.
* @return {Graphics}
*/
Phaser.Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise, segments) {
// If we do this we can never draw a full circle
if (startAngle === endAngle)
{
return this;
}
if (anticlockwise === undefined) { anticlockwise = false; }
if (segments === undefined) { segments = 40; }
if (!anticlockwise && endAngle <= startAngle)
{
endAngle += Math.PI * 2;
}
else if (anticlockwise && startAngle <= endAngle)
{
startAngle += Math.PI * 2;
}
var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle);
var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments;
// Sweep check - moved here because we don't want to do the moveTo below if the arc fails
if (sweep === 0)
{
return this;
}
var startX = cx + Math.cos(startAngle) * radius;
var startY = cy + Math.sin(startAngle) * radius;
if (anticlockwise && this.filling)
{
this.moveTo(cx, cy);
}
else
{
this.moveTo(startX, startY);
}
// currentPath will always exist after calling a moveTo
var points = this.currentPath.shape.points;
var theta = sweep / (segs * 2);
var theta2 = theta * 2;
var cTheta = Math.cos(theta);
var sTheta = Math.sin(theta);
var segMinus = segs - 1;
var remainder = (segMinus % 1) / segMinus;
for (var i = 0; i <= segMinus; i++)
{
var real = i + remainder * i;
var angle = ((theta) + startAngle + (theta2 * real));
var c = Math.cos(angle);
var s = -Math.sin(angle);
points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx,
( (cTheta * -s) + (sTheta * c) ) * radius + cy);
}
this.dirty = true;
this._boundsDirty = true;
return this;
};
/**
* Specifies a simple one-color fill that subsequent calls to other Graphics methods
* (such as lineTo() or drawCircle()) use when drawing.
*
* @method Phaser.Graphics#beginFill
* @param color {Number} the color of the fill
* @param alpha {Number} the alpha of the fill
* @return {Graphics}
*/
Phaser.Graphics.prototype.beginFill = function (color, alpha) {
this.filling = true;
this.fillColor = color || 0;
this.fillAlpha = (alpha === undefined) ? 1 : alpha;
if (this.currentPath)
{
if (this.currentPath.shape.points.length <= 2)
{
this.currentPath.fill = this.filling;
this.currentPath.fillColor = this.fillColor;
this.currentPath.fillAlpha = this.fillAlpha;
}
}
return this;
};
/**
* Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
*
* @method Phaser.Graphics#endFill
* @return {Graphics}
*/
Phaser.Graphics.prototype.endFill = function () {
this.filling = false;
this.fillColor = null;
this.fillAlpha = 1;
return this;
};
/**
* @method Phaser.Graphics#drawRect
*
* @param x {Number} The X coord of the top-left of the rectangle
* @param y {Number} The Y coord of the top-left of the rectangle
* @param width {Number} The width of the rectangle
* @param height {Number} The height of the rectangle
* @return {Graphics}
*/
Phaser.Graphics.prototype.drawRect = function (x, y, width, height) {
this.drawShape(new Phaser.Rectangle(x, y, width, height));
return this;
};
/**
* @method Phaser.Graphics#drawRoundedRect
* @param x {Number} The X coord of the top-left of the rectangle
* @param y {Number} The Y coord of the top-left of the rectangle
* @param width {Number} The width of the rectangle
* @param height {Number} The height of the rectangle
* @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9.
*/
Phaser.Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) {
this.drawShape(new Phaser.RoundedRectangle(x, y, width, height, radius));
return this;
};
/**
* Draws a circle.
*
* @method Phaser.Graphics#drawCircle
* @param x {Number} The X coordinate of the center of the circle
* @param y {Number} The Y coordinate of the center of the circle
* @param diameter {Number} The diameter of the circle
* @return {Graphics}
*/
Phaser.Graphics.prototype.drawCircle = function (x, y, diameter) {
this.drawShape(new Phaser.Circle(x, y, diameter));
return this;
};
/**
* Draws an ellipse.
*
* @method Phaser.Graphics#drawEllipse
* @param x {Number} The X coordinate of the center of the ellipse
* @param y {Number} The Y coordinate of the center of the ellipse
* @param width {Number} The half width of the ellipse
* @param height {Number} The half height of the ellipse
* @return {Graphics}
*/
Phaser.Graphics.prototype.drawEllipse = function (x, y, width, height) {
this.drawShape(new Phaser.Ellipse(x, y, width, height));
return this;
};
/**
* Draws a polygon using the given path.
*
* @method Phaser.Graphics#drawPolygon
* @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object.
* @return {Graphics}
*/
Phaser.Graphics.prototype.drawPolygon = function (path) {
if (path instanceof Phaser.Polygon)
{
path = path.points;
}
// prevents an argument assignment deopt
// see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
var points = path;
if (!Array.isArray(points))
{
// prevents an argument leak deopt
// see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
points = new Array(arguments.length);
for (var i = 0; i < points.length; ++i)
{
points[i] = arguments[i];
}
}
this.drawShape(new Phaser.Polygon(points));
return this;
};
/**
* Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
*
* @method Phaser.Graphics#clear
* @return {Graphics}
*/
Phaser.Graphics.prototype.clear = function () {
this.lineWidth = 0;
this.filling = false;
this.dirty = true;
this._boundsDirty = true;
this.clearDirty = true;
this.graphicsData = [];
this.updateLocalBounds();
return this;
};
/**
* Useful function that returns a texture of the graphics object that can then be used to create sprites
* This can be quite useful if your geometry is complicated and needs to be reused multiple times.
*
* Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}).
*
* @method Phaser.Graphics#generateTexture
* @param [resolution=1] {Number} The resolution of the texture being generated
* @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts
* @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0)
* @return {Texture} a texture of the graphics object
*/
Phaser.Graphics.prototype.generateTexture = function (resolution, scaleMode, padding) {
if (resolution === undefined) { resolution = 1; }
if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; }
if (padding === undefined) { padding = 0; }
var bounds = this.getBounds();
bounds.width += padding;
bounds.height += padding;
var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution);
var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode);
texture.baseTexture.resolution = resolution;
canvasBuffer.context.scale(resolution, resolution);
canvasBuffer.context.translate(-bounds.x, -bounds.y);
PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context);
return texture;
};
/**
* Renders the object using the WebGL renderer
*
* @method Phaser.Graphics#_renderWebGL
* @param renderSession {RenderSession}
* @private
*/
Phaser.Graphics.prototype._renderWebGL = function (renderSession) {
// if the sprite is not visible or the alpha is 0 then no need to render this element
if (this.visible === false || this.alpha === 0 || this.isMask === true)
{
return;
}
if (this._cacheAsBitmap)
{
if (this.dirty || this.cachedSpriteDirty)
{
this._generateCachedSprite();
// we will also need to update the texture on the gpu too!
this.updateCachedSpriteTexture();
this.cachedSpriteDirty = false;
this.dirty = false;
}
this._cachedSprite.worldAlpha = this.worldAlpha;
PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
return;
}
else
{
renderSession.spriteBatch.stop();
renderSession.blendModeManager.setBlendMode(this.blendMode);
if (this._mask)
{
renderSession.maskManager.pushMask(this._mask, renderSession);
}
if (this._filters)
{
renderSession.filterManager.pushFilter(this._filterBlock);
}
// check blend mode
if (this.blendMode !== renderSession.spriteBatch.currentBlendMode)
{
renderSession.spriteBatch.currentBlendMode = this.blendMode;
var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode];
renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
}
// check if the webgl graphic needs to be updated
if (this.webGLDirty)
{
this.dirty = true;
this.webGLDirty = false;
}
PIXI.WebGLGraphics.renderGraphics(this, renderSession);
// only render if it has children!
if (this.children.length)
{
renderSession.spriteBatch.start();
// simple render children!
for (var i = 0; i < this.children.length; i++)
{
this.children[i]._renderWebGL(renderSession);
}
renderSession.spriteBatch.stop();
}
if (this._filters)
{
renderSession.filterManager.popFilter();
}
if (this._mask)
{
renderSession.maskManager.popMask(this.mask, renderSession);
}
renderSession.drawCount++;
renderSession.spriteBatch.start();
}
};
/**
* Renders the object using the Canvas renderer
*
* @method Phaser.Graphics#_renderCanvas
* @param renderSession {RenderSession}
* @private
*/
Phaser.Graphics.prototype._renderCanvas = function (renderSession) {
// if the sprite is not visible or the alpha is 0 then no need to render this element
if (this.visible === false || this.alpha === 0 || this.isMask === true)
{
return;
}
// if the tint has changed, set the graphics object to dirty.
if (this._prevTint !== this.tint)
{
this.dirty = true;
this._prevTint = this.tint;
}
if (this._cacheAsBitmap)
{
if (this.dirty || this.cachedSpriteDirty)
{
this._generateCachedSprite();
// we will also need to update the texture
this.updateCachedSpriteTexture();
this.cachedSpriteDirty = false;
this.dirty = false;
}
this._cachedSprite.alpha = this.alpha;
PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
return;
}
else
{
var context = renderSession.context;
var transform = this.worldTransform;
if (this.blendMode !== renderSession.currentBlendMode)
{
renderSession.currentBlendMode = this.blendMode;
context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
}
if (this._mask)
{
renderSession.maskManager.pushMask(this._mask, renderSession);
}
var resolution = renderSession.resolution;
var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX;
var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY;
context.setTransform(transform.a * resolution,
transform.b * resolution,
transform.c * resolution,
transform.d * resolution,
tx,
ty);
PIXI.CanvasGraphics.renderGraphics(this, context);
// simple render children!
for (var i = 0; i < this.children.length; i++)
{
this.children[i]._renderCanvas(renderSession);
}
if (this._mask)
{
renderSession.maskManager.popMask(renderSession);
}
}
};
/**
* Retrieves the bounds of the graphic shape as a rectangle object
*
* @method Phaser.Graphics#getBounds
* @return {Rectangle} the rectangular bounding area
*/
Phaser.Graphics.prototype.getBounds = function (matrix) {
if (this._currentBounds)
{
return this._currentBounds;
}
// Return an empty object if the item is a mask!
if (!this.renderable)
{
return Phaser.EmptyRectangle;
}
if (this.dirty)
{
this.updateLocalBounds();
this.webGLDirty = true;
this.cachedSpriteDirty = true;
this.dirty = false;
}
var bounds = this._localBounds;
var w0 = bounds.x;
var w1 = bounds.width + bounds.x;
var h0 = bounds.y;
var h1 = bounds.height + bounds.y;
var worldTransform = matrix || this.worldTransform;
var a = worldTransform.a;
var b = worldTransform.b;
var c = worldTransform.c;
var d = worldTransform.d;
var tx = worldTransform.tx;
var ty = worldTransform.ty;
var x1 = a * w1 + c * h1 + tx;
var y1 = d * h1 + b * w1 + ty;
var x2 = a * w0 + c * h1 + tx;
var y2 = d * h1 + b * w0 + ty;
var x3 = a * w0 + c * h0 + tx;
var y3 = d * h0 + b * w0 + ty;
var x4 = a * w1 + c * h0 + tx;
var y4 = d * h0 + b * w1 + ty;
var maxX = x1;
var maxY = y1;
var minX = x1;
var minY = y1;
minX = x2 < minX ? x2 : minX;
minX = x3 < minX ? x3 : minX;
minX = x4 < minX ? x4 : minX;
minY = y2 < minY ? y2 : minY;
minY = y3 < minY ? y3 : minY;
minY = y4 < minY ? y4 : minY;
maxX = x2 > maxX ? x2 : maxX;
maxX = x3 > maxX ? x3 : maxX;
maxX = x4 > maxX ? x4 : maxX;
maxY = y2 > maxY ? y2 : maxY;
maxY = y3 > maxY ? y3 : maxY;
maxY = y4 > maxY ? y4 : maxY;
this._bounds.x = minX;
this._bounds.width = maxX - minX;
this._bounds.y = minY;
this._bounds.height = maxY - minY;
this._currentBounds = this._bounds;
return this._currentBounds;
};
/**
* Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration.
*
* @method Phaser.Graphics#getLocalBounds
* @return {Rectangle} The rectangular bounding area
*/
Phaser.Graphics.prototype.getLocalBounds = function () {
var matrixCache = this.worldTransform;
this.worldTransform = Phaser.identityMatrix;
for (var i = 0; i < this.children.length; i++)
{
this.children[i].updateTransform();
}
var bounds = this.getBounds();
this.worldTransform = matrixCache;
for (i = 0; i < this.children.length; i++)
{
this.children[i].updateTransform();
}
return bounds;
};
/**
* Tests if a point is inside this graphics object
*
* @param point {Point} the point to test
* @return {boolean} the result of the test
*/
Phaser.Graphics.prototype.containsPoint = function (point, tempPoint) {
if (tempPoint === undefined) { tempPoint = new Phaser.Point(); }
this.worldTransform.applyInverse(point, tempPoint);
var graphicsData = this.graphicsData;
for (var i = 0; i < graphicsData.length; i++)
{
var data = graphicsData[i];
if (!data.fill)
{
continue;
}
// only deal with fills..
if (data.shape)
{
if (data.shape.contains(tempPoint.x, tempPoint.y))
{
return true;
}
}
}
return false;
};
/**
* Update the bounds of the object
*
* @method Phaser.Graphics#updateLocalBounds
*/
Phaser.Graphics.prototype.updateLocalBounds = function () {
var minX = Infinity;
var maxX = -Infinity;
var minY = Infinity;
var maxY = -Infinity;
if (this.graphicsData.length)
{
var shape, points, x, y, w, h;
for (var i = 0; i < this.graphicsData.length; i++)
{
var data = this.graphicsData[i];
var type = data.type;
var lineWidth = data.lineWidth;
shape = data.shape;
if (type === Phaser.RECTANGLE || type === Phaser.ROUNDEDRECTANGLE)
{
x = shape.x - lineWidth / 2;
y = shape.y - lineWidth / 2;
w = shape.width + lineWidth;
h = shape.height + lineWidth;
minX = x < minX ? x : minX;
maxX = x + w > maxX ? x + w : maxX;
minY = y < minY ? y : minY;
maxY = y + h > maxY ? y + h : maxY;
}
else if (type === Phaser.CIRCLE)
{
x = shape.x;
y = shape.y;
w = shape.radius + lineWidth / 2;
h = shape.radius + lineWidth / 2;
minX = x - w < minX ? x - w : minX;
maxX = x + w > maxX ? x + w : maxX;
minY = y - h < minY ? y - h : minY;
maxY = y + h > maxY ? y + h : maxY;
}
else if (type === Phaser.ELLIPSE)
{
x = shape.x;
y = shape.y;
w = shape.width + lineWidth / 2;
h = shape.height + lineWidth / 2;
minX = x - w < minX ? x - w : minX;
maxX = x + w > maxX ? x + w : maxX;
minY = y - h < minY ? y - h : minY;
maxY = y + h > maxY ? y + h : maxY;
}
else
{
// POLY - assumes points are sequential, not Point objects
points = shape.points;
for (var j = 0; j < points.length; j++)
{
if (points[j] instanceof Phaser.Point)
{
x = points[j].x;
y = points[j].y;
}
else
{
x = points[j];
y = points[j + 1];
if (j < points.length - 1)
{
j++;
}
}
minX = x - lineWidth < minX ? x - lineWidth : minX;
maxX = x + lineWidth > maxX ? x + lineWidth : maxX;
minY = y - lineWidth < minY ? y - lineWidth : minY;
maxY = y + lineWidth > maxY ? y + lineWidth : maxY;
}
}
}
}
else
{
minX = 0;
maxX = 0;
minY = 0;
maxY = 0;
}
var padding = this.boundsPadding;
this._localBounds.x = minX - padding;
this._localBounds.width = (maxX - minX) + padding * 2;
this._localBounds.y = minY - padding;
this._localBounds.height = (maxY - minY) + padding * 2;
};
/**
* Generates the cached sprite when the sprite has cacheAsBitmap = true
*
* @method Phaser.Graphics#_generateCachedSprite
* @private
*/
Phaser.Graphics.prototype._generateCachedSprite = function () {
var bounds = this.getLocalBounds();
if (!this._cachedSprite)
{
var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
this._cachedSprite = new PIXI.Sprite(texture);
this._cachedSprite.buffer = canvasBuffer;
this._cachedSprite.worldTransform = this.worldTransform;
}
else
{
this._cachedSprite.buffer.resize(bounds.width, bounds.height);
}
// leverage the anchor to account for the offset of the element
this._cachedSprite.anchor.x = -(bounds.x / bounds.width);
this._cachedSprite.anchor.y = -(bounds.y / bounds.height);
// this._cachedSprite.buffer.context.save();
this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y);
// make sure we set the alpha of the graphics to 1 for the render..
this.worldAlpha = 1;
// now render the graphic..
PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context);
this._cachedSprite.alpha = this.alpha;
};
/**
* Updates texture size based on canvas size
*
* @method Phaser.Graphics#updateCachedSpriteTexture
* @private
*/
Phaser.Graphics.prototype.updateCachedSpriteTexture = function () {
var cachedSprite = this._cachedSprite;
var texture = cachedSprite.texture;
var canvas = cachedSprite.buffer.canvas;
texture.baseTexture.width = canvas.width;
texture.baseTexture.height = canvas.height;
texture.crop.width = texture.frame.width = canvas.width;
texture.crop.height = texture.frame.height = canvas.height;
cachedSprite._width = canvas.width;
cachedSprite._height = canvas.height;
// update the dirty base textures
texture.baseTexture.dirty();
};
/**
* Destroys a previous cached sprite.
*
* @method Phaser.Graphics#destroyCachedSprite
*/
Phaser.Graphics.prototype.destroyCachedSprite = function () {
this._cachedSprite.texture.destroy(true);
this._cachedSprite = null;
};
/**
* Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
*
* @method Phaser.Graphics#drawShape
* @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw.
* @return {GraphicsData} The generated GraphicsData object.
*/
Phaser.Graphics.prototype.drawShape = function (shape) {
if (this.currentPath)
{
// check current path!
if (this.currentPath.shape.points.length <= 2)
{
this.graphicsData.pop();
}
}
this.currentPath = null;
// Handle mixed-type polygons
if (shape instanceof Phaser.Polygon)
{
shape = shape.clone();
shape.flatten();
}
var data = new Phaser.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape);
this.graphicsData.push(data);
if (data.type === Phaser.POLYGON)
{
data.shape.closed = this.filling;
this.currentPath = data;
}
this.dirty = true;
this._boundsDirty = true;
return data;
};
/**
* When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. Transparent areas adjoining the edges may be removed ({@link https://github.com/photonstorm/phaser-ce/issues/283 #283}).
* This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory.
* It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas.
* This is not recommended if you are constantly redrawing the graphics element.
*
* @property cacheAsBitmap
* @type Boolean
* @default false
* @private
*/
Object.defineProperty(Phaser.Graphics.prototype, 'cacheAsBitmap', {
get: function () {
return this._cacheAsBitmap;
},
set: function (value) {
this._cacheAsBitmap = value;
if (this._cacheAsBitmap)
{
this._generateCachedSprite();
}
else
{
this.destroyCachedSprite();
}
this.dirty = true;
this.webGLDirty = true;
}
});
|
let addEmp83 = (employees) => {
employees.push(
{id:83, name: 'Jeff George'}
)
return employees;
};
export {addEmp83};
|
window.onload = function(e) {
window.setInterval(_main,16.6)
}
|
const displayedFilters = [
{
name: 'firstname',
metadatas: { label: 'Firstname' },
fieldSchema: { type: 'string' },
},
{
name: 'lastname',
metadatas: { label: 'Lastname' },
fieldSchema: { type: 'string' },
},
{
name: 'email',
metadatas: { label: 'Email' },
fieldSchema: { type: 'email' },
},
{
name: 'username',
metadatas: { label: 'Username' },
fieldSchema: { type: 'string' },
},
{
name: 'isActive',
metadatas: { label: 'Active user' },
fieldSchema: { type: 'boolean' },
},
];
export default displayedFilters;
|
(function() {
'use strict';
/* Constants */
var doc = document.currentScript.ownerDocument;
var template = doc.querySelector('#card-base');
var CardProto = Object.create(HTMLDivElement.prototype);
/**
* @description Returns a Globally Unique Identifer as string
* @return {String}
*/
CardProto.GUID = function () {
var perf = performance.now();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (perf + Math.random() * 16) % 16 | 0;
perf = Math.floor(perf / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
/**
* @description Sets an UUID to host element.
*/
CardProto.setGUID = function (guid) {
let _guid = guid ? guid : this.GUID();
this.getHost().setAttribute('data-guid', _guid);
};
/**
* @description An instance of the element is created.
*/
CardProto.createdCallback = function () {
this.root = this.createShadowRoot();
this.root.appendChild( document.importNode(template.content, true) );
this.edit = this.root.querySelector('.settings__edit');
this.save = this.root.querySelector('.settings__save');
this.remove = this.root.querySelector('.settings__remove');
this.addEvents();
};
/**
* @description Sets eventListener on current card element.
*/
CardProto.addEvents = function () {
this.edit.addEventListener('click', this.editCard.bind(this));
this.save.addEventListener('click', this.saveCard.bind(this));
this.remove.addEventListener('click', this.removeCard.bind(this));
};
/**
* @description Checks if <card-base> is inside another host.
*/
CardProto.getHost = function () {
let _host = this;
if (!!this.parentNode.host) {
_host = this.parentNode.host;
}
return _host;
};
/**
* @description Gets the 'data-theme' value of clicked element and sends an event.
*/
CardProto.modifyTheme = function () {
var theme = null;
if (event.target.hasAttribute('data-theme')) {
theme = event.target.getAttribute('data-theme');
}
window.dispatchEvent(
new CustomEvent('theme-change', { detail: theme })
);
};
/**
* @description Adds 'is-edit' class to host and dispatches 'edit' event.
*/
CardProto.editCard = function () {
let host = this.getHost();
let detail = { detail: host.getAttribute('data-guid') };
let editEvent = new CustomEvent('card-edit', detail);
host.classList.add('fx', 'is-edit');
window.dispatchEvent(editEvent);
};
/**
* @description Removes 'is-edit' class to host and dispatches 'save' event.
*/
CardProto.saveCard = function () {
let host = this.getHost();
let detail = { detail: host.getAttribute('data-guid') };
let saveEvent = new CustomEvent('card-save', detail);
host.saveToStorage();
window.dispatchEvent(saveEvent);
host.classList.remove('is-edit', 'edit-theme');
host.addEventListener('transitionend',
function () { host.classList.remove('fx'); }
);
};
/**
* @description Adds 'is-delete' class to host, dispatches 'card-remove' event
* and removes it from localStorage.
*/
CardProto.removeCard = function () {
let host = this.getHost();
let detail = { detail: host.getAttribute('data-guid') };
let removeEvent = new CustomEvent('card-remove', detail);
host.classList.add('fx', 'is-delete');
host.addEventListener('transitionend', function (event) {
if (event.propertyName === 'transform') {
window.dispatchEvent(removeEvent);
localStorage.removeItem( detail.detail );
}
});
};
/* Register element in document */
document.registerElement('card-base', { prototype: CardProto });
})(); |
import utils from 'osg/utils';
import Object from 'osg/Object';
var StateAttribute = function() {
Object.call(this);
};
utils.createPrototypeStateAttribute(
StateAttribute,
utils.objectInherit(Object.prototype, {
_attributeTypeIndex: undefined,
getType: function() {
return this.attributeType;
},
// basically, if you want two StateAttribute with the same attributeType in a stateSet/State
// their typeMember should be different
getTypeMember: function() {
return this.attributeType;
},
apply: function() {},
// getHash is used by the compiler to know if a change in a StateAttribute
// must trigger a shader build
// If you create your own attribute you will have to customize this function
// a good rule is to that if you change uniform it should not rebuild a shader
// but if you change a type or representation of your StateAttribute, then it should
// if it impact the rendering.
// check other attributes for examples
getHash: function() {
return this.getType();
}
}),
'osg',
'StateAttribute'
);
StateAttribute.OFF = 0;
StateAttribute.ON = 1;
StateAttribute.OVERRIDE = 2;
StateAttribute.PROTECTED = 4;
StateAttribute.INHERIT = 8;
export default StateAttribute;
|
var _ = require('underscore'),
changeCase = require('change-case'),
gutil = require('gulp-util'),
jsonfile = require('jsonfile'),
pluralize = require('pluralize');
/**
* Mapper class (used for restructuring data across different formats)
**/
var mapper =
{
/*
* Trial and error data type matching based on transformation that lead to direct matches
*/
direct_datatype_transformation_match: function(valid_data_types, provided_data_type)
{
var transformation = null;
for (transform in changeCase)
{
var transformed = changeCase[transform](provided_data_type);
if (valid_data_types.indexOf(transformed) > -1)
{
transformation = transform;
}
}
return transformation;
},
/*
* Check if humanized class exists in array of humanized terms
*/
humanized_class_transformation_match: function(valid_humanized_things, provided_class)
{
var humanized_thing = changeCase.upperCaseFirst( changeCase.sentenceCase(provided_class) );
if (valid_humanized_things.indexOf(humanized_thing) > -1)
{
return humanized_thing;
}
else
{
return null;
}
}
};
module.exports = mapper;
|
{
"metadata" :
{
"formatVersion" : 3.1,
"sourceFile" : "us_police_car.obj",
"generatedBy" : "OBJConverter",
"vertices" : 2110,
"faces" : 4332,
"normals" : 2350,
"uvs" : 3394,
"materials" : 6
},
"materials": [ {
"DbgColor" : 15658734,
"DbgIndex" : 0,
"DbgName" : "material4",
"colorAmbient" : [0.64, 0.64, 0.64],
"colorDiffuse" : [0.64, 0.64, 0.64],
"colorSpecular" : [0.165, 0.165, 0.165],
"illumination" : 2,
"mapDiffuse" : "texture3.JPG",
"opticalDensity" : 1.0,
"specularCoef" : 37.254902,
"transparency" : 1.0
},
{
"DbgColor" : 15597568,
"DbgIndex" : 1,
"DbgName" : "FrontColorNoCulling",
"colorAmbient" : [0.8, 0.8, 0.8],
"colorDiffuse" : [0.8, 0.8, 0.8],
"colorSpecular" : [0.165, 0.165, 0.165],
"illumination" : 2,
"opticalDensity" : 1.0,
"specularCoef" : 37.254902,
"transparency" : 1.0
},
{
"DbgColor" : 60928,
"DbgIndex" : 2,
"DbgName" : "material1",
"colorAmbient" : [0.0, 0.0, 0.0],
"colorDiffuse" : [0.0, 0.0, 0.0],
"colorSpecular" : [0.165, 0.165, 0.165],
"illumination" : 2,
"opticalDensity" : 1.0,
"specularCoef" : 37.254902,
"transparency" : 1.0
},
{
"DbgColor" : 238,
"DbgIndex" : 3,
"DbgName" : "material0",
"colorAmbient" : [0.64, 0.64, 0.64],
"colorDiffuse" : [0.64, 0.64, 0.64],
"colorSpecular" : [0.165, 0.165, 0.165],
"illumination" : 2,
"mapDiffuse" : "texture0.JPG",
"opticalDensity" : 1.0,
"specularCoef" : 37.254902,
"transparency" : 1.0
},
{
"DbgColor" : 15658496,
"DbgIndex" : 4,
"DbgName" : "material3",
"colorAmbient" : [0.64, 0.64, 0.64],
"colorDiffuse" : [0.64, 0.64, 0.64],
"colorSpecular" : [0.165, 0.165, 0.165],
"illumination" : 2,
"mapDiffuse" : "texture2.JPG",
"opticalDensity" : 1.0,
"specularCoef" : 37.254902,
"transparency" : 1.0
},
{
"DbgColor" : 61166,
"DbgIndex" : 5,
"DbgName" : "material2",
"colorAmbient" : [0.64, 0.64, 0.64],
"colorDiffuse" : [0.64, 0.64, 0.64],
"colorSpecular" : [0.165, 0.165, 0.165],
"illumination" : 2,
"mapDiffuse" : "texture1.JPG",
"opticalDensity" : 1.0,
"specularCoef" : 37.254902,
"transparency" : 1.0
}],
"buffers": "us_police_car_bin.bin"
}
|
(function() {
'use strict';
describe('DatepickerServiceSpec', function() {
var DatepickerService;
beforeEach(module('ionic-datepicker'));
beforeEach(inject(function(_DatepickerService_) {
DatepickerService = _DatepickerService_;
}));
it('#getDaysOfWeek', function() {
var daysOfWeek = DatepickerService.getDaysOfWeek();
expect(daysOfWeek.length).to.eq(7);
});
it('#getMonths', function() {
var months = DatepickerService.getMonths();
expect(months.length).to.eq(12);
});
it('#getYears', function() {
var years = DatepickerService.getYears();
expect(years.length).to.eq(201);
});
it('#createDateList', function() {
var date = new Date(2015, 6, 1);
var dateList = DatepickerService.createDateList(date);
expect(dateList.length).to.eq(34);
expect(dateList[0]).to.be.undefined;
expect(dateList[1]).to.be.undefined;
expect(dateList[2]).to.be.undefined;
expect(dateList[3].getDate()).to.be.eq(1);
});
});
})();
|
function fruitOrVegetable([input]) {
switch(input){
case "banana":
case "apple":
case "kiwi":
case "cherry":
case "lemon":
case "grapes":
case "peach":
console.log("fruit");
break;
case "tomato":
case "cucumber":
case "pepper":
case "onion":
case "garlic":
case "parsley":
console.log("vegetable");
break;
default:
console.log("unknown");
break;
}
}
|
/**
* @fileOverview
*
* This transform retrieves from storage by "field" from options.fields and combines into array
*/
const Transform = require('./Transform');
class TransformCombine extends Transform {
doTransform() {
const fields = this._options.fields || [];
const type = this._options.dataType || 'string';
return fields.map(field => {
const value = this._storage.get(field);
switch (type) {
case 'int':
case 'integer':
return parseInt(value);
case 'number':
case 'float':
case 'double':
return parseFloat(value);
}
return value;
});
}
}
module.exports = TransformCombine;
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
Since a function is an object, it might be set to [[Prototype]] property
of a new created object through [[Construct]] property
es5id: 13.2.2_A1_T1
description: Declaring a function with "function __func()"
---*/
var __MONSTER="monster";
var __PREDATOR="predator";
function __PROTO(){};
try{
__PROTO.type=__MONSTER;
}
catch(e){
$ERROR('#0: __PROTO.type=__MONSTER does not lead to throwing exception')
}
function __FACTORY(){this.name=__PREDATOR};
__FACTORY.prototype=__PROTO;
var __monster = new __FACTORY();
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (!(__PROTO.isPrototypeOf(__monster))) {
$ERROR('#1: __PROTO.isPrototypeOf(__monster) must be true');
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__monster.type !==__MONSTER) {
$ERROR('#2: __monster.type ===__MONSTER. Actual: __monster.type ==='+__monster.type);
}
//
//////////////////////////////////////////////////////////////////////////////
|
import { Accounts } from 'meteor/accounts-base';
import { TAPi18n } from 'meteor/tap:i18n';
import { getSiteTitle, getFromEmail } from '/core/helper_functions/mail_helpers';
Accounts.emailTemplates.siteName = getSiteTitle();
Accounts.emailTemplates.from = getFromEmail(true); // Get email in SMTP format
Accounts.emailTemplates.verifyEmail = {
subject () {
return TAPi18n.__('emailTemplates_verifyEmail_title');
},
text (user, url) {
// Take out hash from url to use custom route behaviour
const urlWithoutHash = url.replace('#/', '');
const emailMessage = TAPi18n.__('emailTemplates_verifyEmail_message');
// Construct emailBody
const emailBody = `${emailMessage}\n\n${urlWithoutHash}`;
return emailBody;
},
};
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "m19.21 12.04-1.53-.11-.3-1.5C16.88 7.86 14.62 6 12 6 9.94 6 8.08 7.14 7.12 8.96l-.5.95-1.07.11C3.53 10.24 2 11.95 2 14c0 2.21 1.79 4 4 4h13c1.65 0 3-1.35 3-3 0-1.55-1.22-2.86-2.79-2.96zM10 17l-3.5-3.5 1.41-1.41L10 14.18l4.6-4.6 1.41 1.41L10 17z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4 0-2.05 1.53-3.76 3.56-3.97l1.07-.11.5-.95C8.08 7.14 9.94 6 12 6c2.62 0 4.88 1.86 5.39 4.43l.3 1.5 1.53.11c1.56.1 2.78 1.41 2.78 2.96 0 1.65-1.35 3-3 3zm-9-3.82-2.09-2.09L6.5 13.5 10 17l6.01-6.01-1.41-1.41z"
}, "1")], 'CloudDoneTwoTone'); |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 12.2.1-5-s
description: >
Strict Mode - a Function declaring var named 'eval' does not throw
SyntaxError
flags: [onlyStrict]
includes: [runTestCase.js]
---*/
function testcase() {
'use strict';
Function('var eval;');
return true;
}
runTestCase(testcase);
|
steal("can/util", function( can ) {
// ## view.js
// `can.view`
// _Templating abstraction._
var isFunction = can.isFunction,
makeArray = can.makeArray,
// Used for hookup `id`s.
hookupId = 1,
/**
* @add can.view
*/
$view = can.view = function(view, data, helpers, callback){
// Get the result.
var result = $view.render(view, data, helpers, callback);
if(isFunction(result)) {
return result;
}
if(can.isDeferred(result)){
return result.pipe(function(result){
return $view.frag(result);
});
}
// Convert it into a dom frag.
return $view.frag(result);
};
can.extend( $view, {
// creates a frag and hooks it up all at once
frag: function(result, parentNode ){
return $view.hookup( $view.fragment(result), parentNode );
},
// simply creates a frag
// this is used internally to create a frag
// insert it
// then hook it up
fragment: function(result){
var frag = can.buildFragment(result,document.body);
// If we have an empty frag...
if(!frag.childNodes.length) {
frag.appendChild(document.createTextNode(''));
}
return frag;
},
// Convert a path like string into something that's ok for an `element` ID.
toId : function( src ) {
return can.map(src.toString().split(/\/|\./g), function( part ) {
// Dont include empty strings in toId functions
if ( part ) {
return part;
}
}).join("_");
},
hookup: function(fragment, parentNode ){
var hookupEls = [],
id,
func;
// Get all `childNodes`.
can.each(fragment.childNodes ? can.makeArray(fragment.childNodes) : fragment, function(node){
if(node.nodeType === 1){
hookupEls.push(node);
hookupEls.push.apply(hookupEls, can.makeArray( node.getElementsByTagName('*')));
}
});
// Filter by `data-view-id` attribute.
can.each( hookupEls, function( el ) {
if ( el.getAttribute && (id = el.getAttribute('data-view-id')) && (func = $view.hookups[id]) ) {
func(el, parentNode, id);
delete $view.hookups[id];
el.removeAttribute('data-view-id');
}
});
return fragment;
},
/**
* @function ejs
*
* `can.view.ejs([id,] template)` registers an EJS template string
* for a given id programatically. The following
* registers `myViewEJS` and renders it into a documentFragment.
*
* can.view.ejs('myViewEJS', '<h2><%= message %></h2>');
*
* var frag = can.view('myViewEJS', {
* message : 'Hello there!'
* });
*
* frag // -> <h2>Hello there!</h2>
*
* To convert the template into a render function, just pass
* the template. Call the render function with the data
* you want to pass to the template and it returns the
* documentFragment.
*
* var renderer = can.view.ejs('<div><%= message %></div>');
* renderer({
* message : 'EJS'
* }); // -> <div>EJS</div>
*
* @param {String} [id] The template id
* @param {String} template The EJS template string
*/
//
/**
* @function mustache
*
* `can.view.mustache([id,] template)` registers an Mustache template string
* for a given id programatically. The following
* registers `myStache` and renders it into a documentFragment.
*
* can.view.ejs('myStache', '<h2>{{message}}</h2>');
*
* var frag = can.view('myStache', {
* message : 'Hello there!'
* });
*
* frag // -> <h2>Hello there!</h2>
*
* To convert the template into a render function, just pass
* the template. Call the render function with the data
* you want to pass to the template and it returns the
* documentFragment.
*
* var renderer = can.view.mustache('<div>{{message}}</div>');
* renderer({
* message : 'Mustache'
* }); // -> <div>Mustache</div>
*
* @param {String} [id] The template id
* @param {String} template The Mustache template string
*/
//
/**
* @attribute hookups
* @hide
* A list of pending 'hookups'
*/
hookups: {},
/**
* @function hook
* Registers a hookup function that can be called back after the html is
* put on the page. Typically this is handled by the template engine. Currently
* only EJS supports this functionality.
*
* var id = can.View.hookup(function(el){
* //do something with el
* }),
* html = "<div data-view-id='"+id+"'>"
* $('.foo').html(html);
*
*
* @param {Function} cb a callback function to be called with the element
* @param {Number} the hookup number
*/
hook: function( cb ) {
$view.hookups[++hookupId] = cb;
return " data-view-id='"+hookupId+"'";
},
/**
* @attribute cached
* @hide
* Cached are put in this object
*/
cached: {},
cachedRenderers: {},
/**
* @attribute cache
* By default, views are cached on the client. If you'd like the
* the views to reload from the server, you can set the `cache` attribute to `false`.
*
* //- Forces loads from server
* can.view.cache = false;
*
*/
cache: true,
/**
* @function register
* Registers a template engine to be used with
* view helpers and compression.
*
* ## Example
*
* @codestart
* can.View.register({
* suffix : "tmpl",
* plugin : "jquery/view/tmpl",
* renderer: function( id, text ) {
* return function(data){
* return jQuery.render( text, data );
* }
* },
* script: function( id, text ) {
* var tmpl = can.tmpl(text).toString();
* return "function(data){return ("+
* tmpl+
* ").call(jQuery, jQuery, data); }";
* }
* })
* @codeend
* Here's what each property does:
*
* * plugin - the location of the plugin
* * suffix - files that use this suffix will be processed by this template engine
* * renderer - returns a function that will render the template provided by text
* * script - returns a string form of the processed template function.
*
* @param {Object} info a object of method and properties
*
* that enable template integration:
* <ul>
* <li>plugin - the location of the plugin. EX: 'jquery/view/ejs'</li>
* <li>suffix - the view extension. EX: 'ejs'</li>
* <li>script(id, src) - a function that returns a string that when evaluated returns a function that can be
* used as the render (i.e. have func.call(data, data, helpers) called on it).</li>
* <li>renderer(id, text) - a function that takes the id of the template and the text of the template and
* returns a render function.</li>
* </ul>
*/
register: function( info ) {
this.types["." + info.suffix] = info;
},
types: {},
/**
* @attribute ext
* The default suffix to use if none is provided in the view's url.
* This is set to `.ejs` by default.
*
* // Changes view ext to 'txt'
* can.view.ext = 'txt';
*
*/
ext: ".ejs",
/**
* Returns the text that
* @hide
* @param {Object} type
* @param {Object} id
* @param {Object} src
*/
registerScript: function() {},
/**
* @hide
* Called by a production script to pre-load a renderer function
* into the view cache.
* @param {String} id
* @param {Function} renderer
*/
preload: function( ) {},
/**
* @function render
* `can.view.render(view, [data], [helpers], callback)` returns the rendered markup produced by the corresponding template
* engine as String. If you pass a deferred object in as data, render returns
* a deferred resolving to the rendered markup.
*
* `can.view.render` is commonly used for sub-templates.
*
* ## Example
*
* _welcome.ejs_ looks like:
*
* <h1>Hello <%= hello %></h1>
*
* Render it to a string like:
*
* can.view.render("welcome.ejs",{hello: "world"})
* //-> <h1>Hello world</h1>
*
* ## Use as a Subtemplate
*
* If you have a template like:
*
* <ul>
* <% list(items, function(item){ %>
* <%== can.view.render("item.ejs",item) %>
* <% }) %>
* </ul>
*
* ## Using renderer functions
*
* If you only pass the view path, `can.view will return a renderer function that can be called with
* the data to render:
*
* var renderer = can.view.render("welcome.ejs");
* // Do some more things
* renderer({hello: "world"}) // -> Document Fragment
*
* @param {String|Object} view the path of the view template or a view object
* @param {Object} [data] the object passed to a template
* @param {Object} [helpers] additional helper methods to be passed to the view template
* @param {Function} [callback] function executed after template has been processed
* @param {String|Object|Function} returns a string of processed text or a deferred
* that resolves to the processed text or a renderer function when no data are passed.
*
*/
render: function( view, data, helpers, callback ) {
// If helpers is a `function`, it is actually a callback.
if ( isFunction( helpers )) {
callback = helpers;
helpers = undefined;
}
// See if we got passed any deferreds.
var deferreds = getDeferreds(data);
if ( deferreds.length ) { // Does data contain any deferreds?
// The deferred that resolves into the rendered content...
var deferred = new can.Deferred();
// Add the view request to the list of deferreds.
deferreds.push(get(view, true))
// Wait for the view and all deferreds to finish...
can.when.apply(can, deferreds).then(function( resolved ) {
// Get all the resolved deferreds.
var objs = makeArray(arguments),
// Renderer is the last index of the data.
renderer = objs.pop(),
// The result of the template rendering with data.
result;
// Make data look like the resolved deferreds.
if ( can.isDeferred(data) ) {
data = usefulPart(resolved);
}
else {
// Go through each prop in data again and
// replace the defferreds with what they resolved to.
for ( var prop in data ) {
if ( can.isDeferred(data[prop]) ) {
data[prop] = usefulPart(objs.shift());
}
}
}
// Get the rendered result.
result = renderer(data, helpers);
// Resolve with the rendered view.
deferred.resolve(result);
// If there's a `callback`, call it back with the result.
callback && callback(result);
});
// Return the deferred...
return deferred;
}
else {
// No deferreds! Render this bad boy.
var response,
// If there's a `callback` function
async = isFunction( callback ),
// Get the `view` type
deferred = get(view, async);
// If we are `async`...
if ( async ) {
// Return the deferred
response = deferred;
// And fire callback with the rendered result.
deferred.then(function( renderer ) {
callback(data ? renderer(data, helpers) : renderer);
})
} else {
// if the deferred is resolved, call the cached renderer instead
// this is because it's possible, with recursive deferreds to
// need to render a view while its deferred is _resolving_. A _resolving_ deferred
// is a deferred that was just resolved and is calling back it's success callbacks.
// If a new success handler is called while resoliving, it does not get fired by
// jQuery's deferred system. So instead of adding a new callback
// we use the cached renderer.
// We also add __view_id on the deferred so we can look up it's cached renderer.
// In the future, we might simply store either a deferred or the cached result.
if(deferred.state() === "resolved" && deferred.__view_id ){
var currentRenderer = $view.cachedRenderers[ deferred.__view_id ];
return data ? currentRenderer(data, helpers) : currentRenderer;
} else {
// Otherwise, the deferred is complete, so
// set response to the result of the rendering.
deferred.then(function( renderer ) {
response = data ? renderer(data, helpers) : renderer;
});
}
}
return response;
}
},
registerView: function( id, text, type, def ) {
// Get the renderer function.
var func = (type || $view.types[$view.ext]).renderer(id, text);
def = def || new can.Deferred();
// Cache if we are caching.
if ( $view.cache ) {
$view.cached[id] = def;
def.__view_id = id;
$view.cachedRenderers[id] = func;
}
// Return the objects for the response's `dataTypes`
// (in this case view).
return def.resolve(func);
}
});
// Makes sure there's a template, if not, have `steal` provide a warning.
var checkText = function( text, url ) {
if ( ! text.length ) {
//!steal-remove-start
steal.dev.log("There is no template or an empty template at " + url);
//!steal-remove-end
throw "can.view: No template or empty template:" + url;
}
},
// `Returns a `view` renderer deferred.
// `url` - The url to the template.
// `async` - If the ajax request should be asynchronous.
// Returns a deferred.
get = function( url, async ) {
var suffix = url.match(/\.[\w\d]+$/),
type,
// If we are reading a script element for the content of the template,
// `el` will be set to that script element.
el,
// A unique identifier for the view (used for caching).
// This is typically derived from the element id or
// the url for the template.
id,
// The ajax request used to retrieve the template content.
jqXHR;
//If the url has a #, we assume we want to use an inline template
//from a script element and not current page's HTML
if( url.match(/^#/) ) {
url = url.substr(1);
}
// If we have an inline template, derive the suffix from the `text/???` part.
// This only supports `<script>` tags.
if ( el = document.getElementById(url) ) {
suffix = "."+el.type.match(/\/(x\-)?(.+)/)[2];
}
// If there is no suffix, add one.
if (!suffix && !$view.cached[url] ) {
url += ( suffix = $view.ext );
}
if ( can.isArray( suffix )) {
suffix = suffix[0]
}
// Convert to a unique and valid id.
id = $view.toId(url);
// If an absolute path, use `steal` to get it.
// You should only be using `//` if you are using `steal`.
if ( url.match(/^\/\//) ) {
var sub = url.substr(2);
url = ! window.steal ?
sub :
steal.config().root.mapJoin(sub);
}
// Set the template engine type.
type = $view.types[suffix];
// If it is cached,
if ( $view.cached[id] ) {
// Return the cached deferred renderer.
return $view.cached[id];
// Otherwise if we are getting this from a `<script>` element.
} else if ( el ) {
// Resolve immediately with the element's `innerHTML`.
return $view.registerView(id, el.innerHTML, type);
} else {
// Make an ajax request for text.
var d = new can.Deferred();
can.ajax({
async: async,
url: url,
dataType: "text",
error: function(jqXHR) {
checkText("", url);
d.reject(jqXHR);
},
success: function( text ) {
// Make sure we got some text back.
checkText(text, url);
$view.registerView(id, text, type, d)
}
});
return d;
}
},
// Gets an `array` of deferreds from an `object`.
// This only goes one level deep.
getDeferreds = function( data ) {
var deferreds = [];
// pull out deferreds
if ( can.isDeferred(data) ) {
return [data]
} else {
for ( var prop in data ) {
if ( can.isDeferred(data[prop]) ) {
deferreds.push(data[prop]);
}
}
}
return deferreds;
},
// Gets the useful part of a resolved deferred.
// This is for `model`s and `can.ajax` that resolve to an `array`.
usefulPart = function( resolved ) {
return can.isArray(resolved) && resolved[1] === 'success' ? resolved[0] : resolved
};
if ( window.steal ) {
steal.type("view js", function( options, success, error ) {
var type = $view.types["." + options.type],
id = $view.toId(options.id);
/**
* should return something like steal("dependencies",function(EJS){
* return can.view.preload("ID", options.text)
* })
*/
options.text = "steal('" + (type.plugin || "can/view/" + options.type) + "',function(can){return " + "can.view.preload('" + id + "'," + options.text + ");\n})";
success();
})
}
//!steal-pluginify-remove-start
can.extend($view, {
register: function( info ) {
this.types["." + info.suffix] = info;
if ( window.steal ) {
steal.type(info.suffix + " view js", function( options, success, error ) {
var type = $view.types["." + options.type],
id = $view.toId(options.id+'');
options.text = type.script(id, options.text)
success();
})
};
$view[info.suffix] = function(id, text){
if(!text) {
// Return a nameless renderer
return info.renderer(null, id);
}
$view.preload(id, info.renderer(id, text));
return can.view(id);
}
},
registerScript: function( type, id, src ) {
return "can.view.preload('" + id + "'," + $view.types["." + type].script(id, src) + ");";
},
preload: function( id, renderer ) {
$view.cached[id] = new can.Deferred().resolve(function( data, helpers ) {
return renderer.call(data, data, helpers);
});
return function(){
return $view.frag(renderer.apply(this,arguments))
};
}
});
//!steal-pluginify-remove-end
return can;
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const path = require("path");
function run(name, from, projectfile) {
if (!fs.existsSync(path.join(from, projectfile))) {
fs.writeFileSync(path.join(from, projectfile), 'let project = new Project(\'New Project\', __dirname);\n'
+ '\n'
+ 'project.addFile(\'Sources/**\');\n'
+ 'project.setDebugDir(\'Deployment\');\n'
+ '\n'
+ 'Project.createProject(\'Kore\', __dirname).then((subproject) => {\n'
+ '\tproject.addSubProject(subproject);\n'
+ '\tresolve(project);\n'
+ '});\n', { encoding: 'utf8' });
}
if (!fs.existsSync(path.join(from, 'Sources')))
fs.mkdirSync(path.join(from, 'Sources'));
let friendlyName = name;
friendlyName = friendlyName.replace(/ /g, '_');
friendlyName = friendlyName.replace(/-/g, '_');
if (!fs.existsSync(path.join(from, 'Sources', 'main.cpp'))) {
let mainsource = '#include <Kore/pch.h>\n\n'
+ '\n'
+ 'int kore(int argc, char** argv) {\n'
+ '\treturn 0;\n'
+ '}\n';
fs.writeFileSync(path.join(from, 'Sources', 'main.cpp'), mainsource, { encoding: 'utf8' });
}
}
exports.run = run;
//# sourceMappingURL=init.js.map |
var port = params.port;
var base = params.server.replace(/[\/]+$/, '') + (port ? (':' + port) : '');
var accountsUrl = base + '/AIMWebService/api/Accounts';
var authUrl = base + '/PasswordVault/WebServices/auth/Cyberark/CyberArkAuthenticationService.svc/';
var credentialsUrl = base + '/PasswordVault/WebServices/PIMServices.svc/Accounts';
var insecure = params.insecure;
var proxy = params.proxy;
var appid = params.appid;
var username = params.username;
var password = params.password;
var token;
var sendRequest = function(method, url, args) {
var res = http(
url + (method === 'GET' ? encodeToURLQuery(args) : ''),
{
Method: method,
Body: method !== 'GET' ? JSON.stringify(args) : ''
},
insecure,
proxy,
false,
false,
30000
);
if (res.StatusCode !== 400 && (res.StatusCode < 200 || res.StatusCode >= 300)) {
if (res.StatusCode === 404) {
return undefined;
}
// if timeout, throw.
if (res.StatusCode === -1) {
throw 'Request credentials from CyberArk returned Timeout. Error: ' + res.Status;
}
throw 'Failed to reach ' + url + ' , request status code: ' + res.StatusCode + ' and Body: ' + res.Body + '.';
}
return JSON.parse(res.Body);
}
var sendRequestWithToken = function(method, url, args, returnPlainResponse) {
var headers = {};
headers["Content-Type"] = ["application/json"];
if (!token) {
var data = {
username: username,
password: password,
useRadiusAuthentication: false,
connectionNumber: 1
};
var tokenRes = http(
authUrl + 'Logon',
{
Method: 'POST',
Headers: headers,
Body: JSON.stringify(data)
},
insecure,
proxy
);
if (tokenRes.StatusCode !== 200) {
throw 'Could not authenticate user ' + tokenRes.Body;
}
var tokenResObject = JSON.parse(tokenRes.Body);
token = tokenResObject.CyberArkLogonResult;
}
headers["Authorization"] = [token];
if (args.ImmediateChangeByCPM) {
headers["ImmediateChangeByCPM"] = [args.ImmediateChangeByCPM];
delete args.ImmediateChangeByCPM;
}
var res = http(
url + (method === 'GET' ? encodeToURLQuery(args) : ''),
{
Method: method,
Headers: headers,
Body: method !== 'GET' ? JSON.stringify(args) : ''
},
insecure,
proxy,
false,
false,
30000
);
if (res.StatusCode !== 200) {
throw 'Failed to receive valid answer: ' + res.Status;
}
return returnPlainResponse ? res : JSON.parse(res.Body);
};
var parseAccountsFromErrorMessage = function(message) {
var credentials = [];
// format: Too many password objects matching query [Folder=...;Safe=...] were found: (Safe=...;Folder=...;Object=... and Safe=...;Folder=...;Object=...) (Diagnostic Info: 41)
var accounts = message.split("were found: (")[1];
// format: Safe=...;Folder=...;Object=... and Safe=...;Folder=...;Object=...) (Diagnostic Info: 41)
accounts = accounts.split(")")[0];
// format: Safe=...;Folder=...;Object=... and Safe=...;Folder=...;Object=...
accounts = accounts.split(" and ");
accounts.forEach(function(accountString) {
var crednetialDetails = {};
crednetialDetails.name = accountString.split(";Object=")[1];
credentials.push(crednetialDetails);
});
return credentials;
}
var resetCredentials = function(args) {
sendRequestWithToken('PUT', credentialsUrl + '/' + args.accountId + '/ChangeCredentials', args, true);
return {
Type: entryTypes.note,
ContentsFormat: formats.json,
Contents: "Operation succeeded.",
ReadableContentsFormat: formats.markdown
};
};
var getAccountDetails = function(args) {
var result = sendRequestWithToken('GET', credentialsUrl, args);
if (!result) {
return 'No results found';
}
return {
Type: entryTypes.note,
ContentsFormat: formats.json,
Contents: result,
EntryContext: {'CyberArk.AIM(val.Name==obj.Name).Accounts': result.accounts},
ReadableContentsFormat: formats.markdown,
HumanReadable: tableToMarkdown('Found ' + result.Count + ' accounts matching "' + args.Keywords + '". Displaying only the first:', result.accounts)
};
};
var getCredentials = function(asList) {
args.AppID = appid;
args.Folder = params.folder;
args.Safe = params.safe;
var credsToFetch = [];
if (args.identifier) {
credsToFetch.push(args.identifier);
delete args.identifier;
} else if (params.credentialNames) {
credsToFetch = params.credentialNames.split(',');
}
var credentials = [];
for (var i = 0; i < credsToFetch.length; i++) {
args.Object = credsToFetch[i].trim();
var result = sendRequest('GET', accountsUrl, args);
if (result) {
var itemToAdd = asList ? result : {
'user': result.UserName,
'password': result.Content,
'name': result.Name
};
credentials.push(itemToAdd);
}
}
if (credentials.length === 0) {
// no creds were fetched - log to server
logInfo('No credentials were fetched for [' + credsToFetch.join(', ') + ']');
}
return asList ? credentials : JSON.stringify(credentials);
}
var queryCredentials = function() {
args.AppID = appid;
if (!args.folder) {
args.Folder = params.folder;
} else {
args.Folder = args.folder;
}
if (!args.safe) {
args.Safe = params.safe;
} else {
args.Safe = args.safe;
}
var argsKeys = Object.keys(args);
cleanArgs = {};
argsKeys.forEach(function(key) {
var upperKey = key.charAt(0).toUpperCase() + key.substr(1);
cleanArgs[upperKey] = args[key];
delete args[key];
});
var result = sendRequest('GET', accountsUrl, cleanArgs);
var res = result;
var humanReadable = null;
// If we received too many (limited by CyberArk) then return a warning.
if (result && result.ErrorMsg && result.ErrorMsg.indexOf("Too many") > -1) {
var accounts = parseAccountsFromErrorMessage(result.ErrorMsg);
res = "Found " + accounts.length + " results or more, while can only get one. Please try to narrow down the search by adding more filters.";
humanReadable = res;
} else if (result && result.ErrorMsg) {
res = "Error: " + result.ErrorMsg;
humanReadable = res;
} else {
humanReadable = tableToMarkdown('Credentials Results', result);
}
return {
Type: entryTypes.note,
ContentsFormat: formats.json,
Contents: res,
ReadableContentsFormat: formats.markdown,
HumanReadable: humanReadable
};
}
var listCredentials = function() {
var creds = getCredentials(true);
for (var i = 0; i < creds.length; i++) {
// delete password
delete creds[i].Content;
}
return {
Type: entryTypes.note,
ContentsFormat: formats.json,
Contents: creds,
EntryContext: {'CyberArk.AIM(val.Name==obj.name)': creds},
ReadableContentsFormat: formats.markdown,
HumanReadable: tableToMarkdown('Credentials fetched from CyberArk AIM vault:', creds)
};
}
function testModuleAndCredentials() {
args.AppID = appid;
args.Folder = params.folder;
args.Safe = params.safe;
var paramCredsString = params.credentialNames;
if (!paramCredsString) {
sendRequest('GET', accountsUrl, args);
} else {
var names = paramCredsString.split(',');
for (var i = 0; i < names.length; i++) {
var name = names[i].trim()
args.Object = name
// exception would be thrown if identifier (Object) does not exists
var result = sendRequest('GET', accountsUrl, args);
if (!result) {
throw 'Could not find object for: "' + name + '"'
}
}
}
return 'ok';
}
switch (command) {
case 'test-module':
return testModuleAndCredentials();
case 'fetch-credentials':
return getCredentials();
case 'cyber-ark-aim-query':
return queryCredentials();
case 'reset-credentials':
return resetCredentials(args);
case 'account-details':
args.Safe = args.safe || params.safe;
delete args.safe;
args.Keywords = args.keywords;
delete args.keywords;
return getAccountDetails(args);
case 'list-credentials':
return listCredentials();
default:
throw 'Command "' + command + '" is not supported.';
}
|
/* jshint expr:true */
import {
describe,
it,
beforeEach,
afterEach
} from 'mocha';
import { expect } from 'chai';
import Ember from 'ember';
import startApp from '../../helpers/start-app';
import Pretender from 'pretender';
import initializeTestHelpers from 'simple-auth-testing/test-helpers';
initializeTestHelpers();
const { run } = Ember,
// TODO: Pull this into a fixture or similar when required elsewhere
requiredSettings = [{
created_at: '2015-09-11T09:44:30.805Z',
created_by: 1,
id: 5,
key: 'title',
type: 'blog',
updated_at: '2015-10-04T16:26:05.195Z',
updated_by: 1,
uuid: '39e16daf-43fa-4bf0-87d4-44948ba8bf4c',
value: 'The Daily Awesome'
}, {
created_at: '2015-09-11T09:44:30.806Z',
created_by: 1,
id: 6,
key: 'description',
type: 'blog',
updated_at: '2015-10-04T16:26:05.198Z',
updated_by: 1,
uuid: 'e6c8b636-6925-4c4a-a5d9-1dc0870fb8ea',
value: 'Thoughts, stories and ideas.'
}, {
created_at: '2015-09-11T09:44:30.809Z',
created_by: 1,
id: 10,
key: 'postsPerPage',
type: 'blog',
updated_at: '2015-10-04T16:26:05.211Z',
updated_by: 1,
uuid: '775e6ca1-bcc3-4347-a53d-15d5d76c04a4',
value: '5'
}, {
created_at: '2015-09-11T09:44:30.809Z',
created_by: 1,
id: 13,
key: 'ghost_head',
type: 'blog',
updated_at: '2015-09-23T13:32:49.858Z',
updated_by: 1,
uuid: 'df7f3151-bc08-4a77-be9d-dd315b630d51',
value: ''
}, {
created_at: '2015-09-11T09:44:30.809Z',
created_by: 1,
id: 14,
key: 'ghost_foot',
type: 'blog',
updated_at: '2015-09-23T13:32:49.858Z',
updated_by: 1,
uuid: '0649d45e-828b-4dd0-8381-3dff6d1d5ddb',
value: ''
}];
describe('Acceptance: Settings - Navigation', function () {
var application,
store,
server;
beforeEach(function () {
application = startApp();
store = application.__container__.lookup('store:main');
server = new Pretender(function () {
this.get('/ghost/api/v0.1/settings/', function (_request) {
var response = {meta: {filters: 'blog,theme'}};
response.settings = [{
created_at: '2015-09-11T09:44:30.810Z',
created_by: 1,
id: 16,
key: 'navigation',
type: 'blog',
updated_at: '2015-09-23T13:32:49.868Z',
updated_by: 1,
uuid: '4cc51d1c-fcbd-47e6-a71b-fdd1abb223fc',
value: JSON.stringify([
{label: 'Home', url: '/'},
{label: 'About', url: '/about'}
])
}];
response.settings.pushObjects(requiredSettings);
return [200, {'Content-Type': 'application/json'}, JSON.stringify(response)];
});
// TODO: This will be needed for all authenticated page loads
// - is there some way to make this a default?
this.get('/ghost/api/v0.1/notifications/', function (_request) {
return [200, {'Content-Type': 'application/json'}, JSON.stringify({notifications: []})];
});
this.put('/ghost/api/v0.1/settings/', function (_request) {
var response = {meta: {}};
response.settings = [{
created_at: '2015-09-11T09:44:30.810Z',
created_by: 1,
id: 16,
key: 'navigation',
type: 'blog',
updated_at: '2015-09-23T13:32:49.868Z',
updated_by: 1,
uuid: '4cc51d1c-fcbd-47e6-a71b-fdd1abb223fc',
value: JSON.stringify([
{label: 'Test', url: '/test'},
{label: 'About', url: '/about'}
])
}];
response.settings.pushObjects(requiredSettings);
return [200, {'Content-Type': 'application/json'}, JSON.stringify(response)];
});
});
});
afterEach(function () {
Ember.run(application, 'destroy');
});
it('redirects to signin when not authenticated', function () {
invalidateSession();
visit('/settings/navigation');
andThen(function () {
expect(currentPath()).to.not.equal('settings.navigation');
});
});
it('redirects to team page when authenticated as author', function () {
run(() => {
let role = store.createRecord('role', {name: 'Author'});
store.createRecord('user', {id: 'me', roles: [role]});
});
authenticateSession();
visit('/settings/navigation');
andThen(function () {
expect(currentPath()).to.equal('team.user');
});
});
describe('when logged in', function () {
beforeEach(function () {
run(() => {
let role = store.createRecord('role', {name: 'Administrator'});
store.createRecord('user', {id: 'me', roles: [role]});
});
authenticateSession();
});
it('can visit /settings/navigation', function () {
visit('/settings/navigation');
andThen(function () {
expect(currentPath()).to.equal('settings.navigation');
// test has expected number of rows
expect($('.gh-blognav-item').length).to.equal(3);
});
});
it('saves settings', function () {
visit('/settings/navigation');
fillIn('.gh-blognav-label:first input', 'Test');
fillIn('.gh-blognav-url:first input', '/test');
triggerEvent('.gh-blognav-url:first input', 'blur');
click('.btn-blue');
andThen(function () {
// TODO: Test for successful save here once we have a visual
// indication. For now we know the save happened because
// Pretender doesn't complain about an unknown URL
expect($('.error').length).to.equal(0);
expect($('.gh-alert').length).to.equal(0);
});
});
it('clears unsaved settings when navigating away', function () {
visit('/settings/navigation');
andThen(function () {
$('.gh-blognav-label input').val('Test');
expect($('.gh-blognav-label:first input').val()).to.equal('Test');
});
visit('/settings/code-injection');
visit('/settings/navigation');
andThen(function () {
expect($('.gh-blognav-label:first input').val()).to.equal('Home');
});
});
});
});
|
'use strict';
module.exports = function generate_allOf(it, $keyword) {
var out = ' ';
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $currentBaseId = $it.baseId,
$allSchemasEmpty = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$sch = arr1[$i += 1];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
$allSchemasEmpty = false;
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
}
}
if ($breakOnError) {
if ($allSchemasEmpty) {
out += ' if (true) { ';
} else {
out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
}
}
out = it.util.cleanUpCode(out);
return out;
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:7558918cda348197d99ad133aaf18f123b43ad1eee1e92ed90b2e2d4520f3757
size 3729
|
"use strict";
exports.__esModule = true;
exports.default = Repeater;
// my tests in ie11/chrome/FF indicate that keyDown repeats
// at about 35ms+/- 5ms after an initial 500ms delay. callback fires on the leading edge
function Repeater(callback) {
var id,
cancel = function cancel() {
return clearInterval(id);
};
id = setInterval(function () {
cancel();
id = setInterval(callback, 35);
callback(); //fire after everything in case the user cancels on the first call
}, 500);
return cancel;
}
module.exports = exports['default']; |
var mongoose = require('mongoose');
var TodoSchema = new mongoose.Schema({
name: String,
completed: Boolean,
note: String
});
module.exports = mongoose.model('Todo', TodoSchema); |
import React from 'react'
import Icon from 'react-icon-base'
const TiLocationArrowOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m18.5 34.9c-0.6 0-2.1-0.3-2.8-2.5l-2-6.1-6.1-2c-2-0.7-2.4-2-2.5-2.6s0.2-2 2.2-3l19-8.8c1.7-0.8 3.2-0.5 3.9 0.6 0.4 0.6 0.6 1.6-0.1 3.2l-8.8 19c-0.9 1.9-2.2 2.2-2.8 2.2z m-9-13.5l6.8 2.3 2.3 6.8 8-17.1-17.1 8z"/></g>
</Icon>
)
export default TiLocationArrowOutline
|
var webpack = require("webpack");
module.exports = {
entry: './src/Delay.js',
output: {
path: __dirname,
filename: 'dist/delay.min.js',
library: 'Delay',
libraryTarget: 'umd'
},
externals: {
'react': 'react',
'prop-types': 'prop-types'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
presets: ['latest', 'react', 'stage-0']
}
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
};
|
/*
* Inspector text editor class.
*/
+function ($) { "use strict";
var Base = $.oc.inspector.propertyEditors.popupBase,
BaseProto = Base.prototype
var TextEditor = function(inspector, propertyDefinition, containerCell, group) {
Base.call(this, inspector, propertyDefinition, containerCell, group)
}
TextEditor.prototype = Object.create(BaseProto)
TextEditor.prototype.constructor = Base
TextEditor.prototype.setLinkText = function(link, value) {
var value = value !== undefined ? value
: this.inspector.getPropertyValue(this.propertyDefinition.property)
if (value === undefined) {
value = this.propertyDefinition.default
}
if (!value) {
value = this.propertyDefinition.placeholder
$.oc.foundation.element.addClass(link, 'placeholder')
}
else {
$.oc.foundation.element.removeClass(link, 'placeholder')
}
if (typeof value === 'string') {
value = value.replace(/(?:\r\n|\r|\n)/g, ' ');
value = $.trim(value)
value = value.substring(0, 300);
}
link.textContent = value
}
TextEditor.prototype.getPopupContent = function() {
return '<form> \
<div class="modal-header"> \
<button type="button" class="close" data-dismiss="popup">×</button> \
<h4 class="modal-title">{{property}}</h4> \
</div> \
<div class="modal-body"> \
<div class="form-group"> \
<p class="inspector-field-comment"></p> \
<textarea class="form-control size-small field-textarea" name="name" value=""/> \
</div> \
</div> \
<div class="modal-footer"> \
<button type="submit" class="btn btn-primary">OK</button> \
<button type="button" class="btn btn-default" data-dismiss="popup">Cancel</button> \
</div> \
</form>'
}
TextEditor.prototype.configureComment = function(popup) {
if (!this.propertyDefinition.description) {
return
}
var descriptionElement = $(popup).find('p.inspector-field-comment')
descriptionElement.text(this.propertyDefinition.description)
}
TextEditor.prototype.configurePopup = function(popup) {
var $textarea = $(popup).find('textarea'),
value = this.inspector.getPropertyValue(this.propertyDefinition.property)
if (this.propertyDefinition.placeholder) {
$textarea.attr('placeholder', this.propertyDefinition.placeholder)
}
if (value === undefined) {
value = this.propertyDefinition.default
}
$textarea.val(value)
$textarea.focus()
this.configureComment(popup)
}
TextEditor.prototype.handleSubmit = function($form) {
var $textarea = $form.find('textarea'),
link = this.getLink(),
value = $.trim($textarea.val())
this.inspector.setPropertyValue(this.propertyDefinition.property, value)
}
$.oc.inspector.propertyEditors.text = TextEditor
}(window.jQuery); |
import request from 'request-promise';
const utils = {
/**
* @param getAttributeList provides List of attributes
*
* @calls action on success or failure
*/
getMappingList: () => {
return request({
url: 'http://localhost:4000/api/csv/getMappingList',
method: 'GET',
json: true
});
}
};
export default utils;
|
function *outer(n) {
yield n;
yield* middle(n - 1, inner(n + 10));
yield n + 1;
}
function *middle(n, plusTen) {
yield n;
yield* inner(n - 1);
yield n + 1;
yield* plusTen;
}
function *inner(n) {
yield n;
}
genHelpers.check(outer(5), [5, 4, 3, 5, 15, 6]);
|
/**
* TODO: Currently, the order of execution of these tests matters!
* These are not really seperate tests but a single test script, and it could
* do with some tidying up.
*/
var db = require('../lib/transports/db'),
filesystem = require('../lib/transports/filesystem'),
repository = require('../lib/transports/repository'),
couchdb = require('../lib/couchdb'),
logger = require('../lib/logger'),
async = require('../deps/async'),
child_process = require('child_process');
logger.level = 'error';
var ins = 'http://admin:password@localhost:5984/cpm_test_db';
var repo_ins = 'http://admin:password@localhost:5984/cpm_test_repository';
var repo_ins2 = 'http://admin:password@localhost:5984/cpm_test_repository2';
var expected = require(__dirname + '/fixtures/testpackage_loaded');
var check_pkg = function(pkg, test) {
test.same(Object.keys(pkg).sort(), Object.keys(expected).sort());
test.same(
Object.keys(pkg.cpm).sort(),
Object.keys(expected.cpm).sort()
);
test.same(pkg.cpm.files.sort(), expected.cpm.files.sort());
test.same(pkg.cpm.properties_files, expected.cpm.properties_files);
// just test the keys, the values will be different
test.same(
Object.keys(pkg._attachments).sort(),
Object.keys(expected._attachments).sort()
);
test.same(pkg.validate_doc_update, expected.validate_doc_update);
test.same(pkg.shows, expected.shows);
test.same(pkg.views, expected.views);
test.same(pkg.lib, expected.lib);
test.same(pkg.templates, expected.templates);
test.same(pkg.package, expected.package);
test.same(pkg.language, expected.language);
test.same(pkg.lists, expected.lists);
test.same(pkg.updates, expected.updates);
test.same(pkg.rewrites.sort(), expected.rewrites.sort());
};
var clear_test_db = function (callback) {
// remove any old test data
couchdb(ins).delete('', null, function (err) {
if (err && err.message !== 'missing') throw err;
couchdb(ins).ensureDB(function (err) {
if (err) throw err;
callback();
});
});
};
var delete_test_files = function (p, callback) {
var rm = child_process.spawn('rm', ['-rf', p]);
rm.on('exit', function (code) {
callback();
});
}
var reset_repository = function (repo_ins, callback) {
// remove any old test data
couchdb(repo_ins).delete('', null, function (err) {
if (err && err.message !== 'missing') return callback(err);
couchdb(repo_ins).ensureDB(function (err) {
if (err) return callback(err);
var p = __dirname + '/../repository';
filesystem.getPackage(settings, p, function (err, pkg) {
if (err) return callback(err);
// put package to cpm_test_repository
db.putPackage(settings, repo_ins, pkg, callback);
});
});
});
};
var settings = {
repositories: [repo_ins, repo_ins2],
instances: {},
ignore: ['.*\.swp$']
};
var diff_paths = function (a, b, test, callback) {
var diff = child_process.spawn('diff', [a, b]);
diff.on('exit', function (code) {
test.equals(code, 0, 'there should be no differences');
callback();
});
};
// push
exports['filesystem.getPackage -> db.putPackage'] = function (test) {
clear_test_db(function () {
var p = __dirname + '/fixtures/testpackage';
filesystem.getPackage(settings, p, function (err, pkg) {
if (err) throw err;
// put package to cpm_test_db
db.putPackage(settings, ins, pkg, function (err) {
if (err) throw err;
couchdb(ins).get('_design/testpackage', function (err, pkg) {
if (err) throw err;
delete pkg._id;
delete pkg._rev;
check_pkg(pkg, test);
test.done();
});
});
});
});
};
// clone
exports['db.getPackage -> filesystem.putPackage'] = function (test) {
var orig = __dirname + '/fixtures/testpackage';
var p = __dirname + '/fixtures/cpm_test_db_clone';
var loc = ins + '/_design/testpackage';
db.getPackage(settings, loc, function (err, pkg) {
if (err) throw err;
delete_test_files(p, function () {
// put package to fixtures/cpm_test_db_clone
filesystem.putPackage(settings, p, pkg, function (err) {
if (err) throw err;
diff_paths(orig, p, test, test.done);
});
});
});
};
// publish
exports['filesystem.getPackage -> repository.putPackage'] = function (test) {
reset_repository(repo_ins, function (err) {
if (err) throw err;
var id = 'dep_test_lib-0.0.3';
var p = __dirname + '/fixtures/dep_test_lib';
filesystem.getPackage(settings, p, function (err, pkg) {
if (err) throw err;
repository.putPackage(settings, repo_ins, pkg, function (err) {
if (err) throw err;
couchdb(repo_ins).get(id, function (err, pkg) {
if (err) throw err;
test.equals(pkg.package.name, 'dep_test_lib');
test.done();
});
});
});
});
};
// publish to repository 2
exports['filesystem.getPackage -> repository.putPackage 2'] = function (test) {
reset_repository(repo_ins2, function (err) {
if (err) throw err;
var id = 'dep_test_lib-0.0.4';
var p = __dirname + '/fixtures/dep_test_lib';
filesystem.getPackage(settings, p, function (err, pkg) {
if (err) throw err;
pkg.package.version = '0.0.4';
repository.putPackage(settings, repo_ins2, pkg, function (err) {
if (err) throw err;
couchdb(repo_ins2).get(id, function (err, pkg) {
if (err) throw err;
test.equals(pkg.package.name, 'dep_test_lib');
test.done();
});
});
});
});
};
// clone from repository
exports['repository.getPackage -> filesystem.putPackage'] = function (test) {
var orig = __dirname + '/fixtures/dep_test_lib';
var p = __dirname + '/fixtures/cpm_test_repository_clone';
var loc = 'dep_test_lib@0.0.3';
repository.getPackage(settings, loc, function (err, pkg) {
if (err) throw err;
delete_test_files(p, function () {
filesystem.putPackage(settings, p, pkg, function (err) {
if (err) throw err;
diff_paths(orig, p, test, test.done);
});
});
});
};
// push with dependencies
exports['filesystem.getPackageFull -> db.putPackage'] = function (test) {
clear_test_db(function () {
var p = __dirname + '/fixtures/dep_test';
var lib_id = '_design/dep_test_lib';
var app_id = '_design/dep_test';
filesystem.getPackageFull(settings, p, function (err, pkg, pkgs) {
if (err) throw err;
async.forEach(Object.keys(pkgs), function (k, cb) {
db.putPackage(settings, ins, pkgs[k], cb);
},
function (err) {
if (err) throw err;
couchdb(ins).get(app_id, function (err, pkg) {
test.equals(err, null);
test.equals(pkg.package.name, 'dep_test');
couchdb(ins).get(lib_id, function (err, pkg) {
test.equals(err, null);
test.equals(pkg.package.name, 'dep_test_lib');
test.done();
});
});
});
});
});
};
// push with dependencies 2
exports['filesystem.getPackageFull -> db.putPackage 2'] = function (test) {
clear_test_db(function () {
var p = __dirname + '/fixtures/dep_test2';
var lib_id = '_design/dep_test_lib';
var app_id = '_design/dep_test2';
filesystem.getPackageFull(settings, p, function (err, pkg, pkgs) {
if (err) throw err;
async.forEach(Object.keys(pkgs), function (k, cb) {
db.putPackage(settings, ins, pkgs[k], cb);
},
function (err) {
if (err) throw err;
couchdb(ins).get(app_id, function (err, pkg) {
test.equals(err, null);
test.equals(pkg.package.name, 'dep_test2');
couchdb(ins).get(lib_id, function (err, pkg) {
test.equals(err, null);
test.equals(pkg.package.name, 'dep_test_lib');
test.equals(pkg.package.version, '0.0.4');
test.done();
});
});
});
});
});
};
// list
exports['repository.list'] = function (test) {
var loc = '';
repository.list(settings, loc, function (err, pkgs) {
if (err) throw err;
test.same(pkgs, {'dep_test_lib': ['0.0.3']});
test.done();
});
};
exports['db.list'] = function (test) {
db.list(settings, ins, function (err, pkgs) {
if (err) throw err;
test.same(pkgs, {
'dep_test_lib': ['0.0.4'],
'dep_test2': ['0.1.0']
});
test.done();
});
};
// unpublish
exports['repository.deletePackage'] = function (test) {
var loc = 'dep_test_lib@0.0.3';
repository.deletePackage(settings, loc, function (err) {
if (err) throw err;
var p = repo_ins + '/dep_test_lib-0.0.3';
couchdb(repo_ins).exists(p, function (err, exists) {
if (err) throw err;
test.equals(exists, false);
test.done();
});
});
};
// unpublish 2
exports['repository.deletePackage 2'] = function (test) {
var loc = 'dep_test_lib@0.0.4';
repository.deletePackage(settings, loc, function (err) {
if (err) throw err;
var p = repo_ins + '/dep_test_lib-0.0.4';
couchdb(repo_ins2).exists(p, function (err, exists) {
if (err) throw err;
test.equals(exists, false);
test.done();
});
});
};
// delete
exports['db.deletePackage'] = function (test) {
var loc = ins + '/_design/dep_test2';
db.deletePackage(settings, loc, function (err) {
if (err) throw err;
couchdb(ins).exists('_design/dep_test2', function (err, exists) {
if (err) throw err;
test.equals(exists, false);
test.done();
});
});
};
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Skywriter.
*
* The Initial Developer of the Original Code is
* Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Joe Walker (jwalker@mozilla.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
var dom = require("pilot/dom");
var event = require("pilot/event");
var requestViewHtml = require("text!cockpit/ui/request_view.html");
var Templater = require("pilot/domtemplate").Templater;
var requestViewCss = require("text!cockpit/ui/request_view.css");
dom.importCssString(requestViewCss);
/**
* Pull the HTML into the DOM, but don't add it to the document
*/
var templates = document.createElement('div');
templates.innerHTML = requestViewHtml;
var row = templates.querySelector('.cptRow');
/**
* Work out the path for images.
* TODO: This should probably live in some utility area somewhere
*/
function imageUrl(path) {
var dataUrl;
try {
dataUrl = require('text!cockpit/ui/' + path);
} catch (e) { }
if (dataUrl) {
return dataUrl;
}
var filename = module.id.split('/').pop() + '.js';
var imagePath;
if (module.uri.substr(-filename.length) !== filename) {
console.error('Can\'t work out path from module.uri/module.id');
return path;
}
if (module.uri) {
var end = module.uri.length - filename.length - 1;
return module.uri.substr(0, end) + "/" + path;
}
return filename + path;
}
/**
* Adds a row to the CLI output display
*/
function RequestView(request, cliView) {
this.request = request;
this.cliView = cliView;
this.imageUrl = imageUrl;
// Elements attached to this by the templater. For info only
this.rowin = null;
this.rowout = null;
this.output = null;
this.hide = null;
this.show = null;
this.duration = null;
this.throb = null;
new Templater().processNode(row.cloneNode(true), this);
this.cliView.output.appendChild(this.rowin);
this.cliView.output.appendChild(this.rowout);
this.request.addEventListener('output', this.onRequestChange.bind(this));
};
RequestView.prototype = {
/**
* A single click on an invocation line in the console copies the command to
* the command line
*/
copyToInput: function() {
this.cliView.element.value = this.request.typed;
},
/**
* A double click on an invocation line in the console executes the command
*/
executeRequest: function(ev) {
this.cliView.cli.update({
typed: this.request.typed,
cursor: { start:0, end:0 }
});
this.cliView.cli.exec();
},
hideOutput: function(ev) {
this.output.style.display = 'none';
dom.addCssClass(this.hide, 'cmd_hidden');
dom.removeCssClass(this.show, 'cmd_hidden');
event.stopPropagation(ev);
},
showOutput: function(ev) {
this.output.style.display = 'block';
dom.removeCssClass(this.hide, 'cmd_hidden');
dom.addCssClass(this.show, 'cmd_hidden');
event.stopPropagation(ev);
},
remove: function(ev) {
this.cliView.output.removeChild(this.rowin);
this.cliView.output.removeChild(this.rowout);
event.stopPropagation(ev);
},
onRequestChange: function(ev) {
this.duration.innerHTML = this.request.duration ?
'completed in ' + (this.request.duration / 1000) + ' sec ' :
'';
this.output.innerHTML = '';
this.request.outputs.forEach(function(output) {
var node;
if (typeof output == 'string') {
node = document.createElement('p');
node.innerHTML = output;
} else {
node = output;
}
this.output.appendChild(node);
}, this);
this.cliView.scrollOutputToBottom();
dom.setCssClass(this.output, 'cmd_error', this.request.error);
this.throb.style.display = this.request.completed ? 'none' : 'block';
}
};
exports.RequestView = RequestView;
});
|
/**
* Event handlers for Footer pattern.
*/
const $ = require('jquery');
$(document).ready(() => {
// Hide footer on mobile until clicked
const $collapsible = $('.js-toggle-collapsed');
$collapsible.addClass('is-collapsed is-toggleable');
$collapsible.on('click', function () {
if (window.matchMedia('screen and (max-width: 768px)').matches) {
$(this).toggleClass('is-collapsed');
}
});
});
|
/* test_toichika.js */
ui.debug.addDebugData('toichika', {
url : '4/4/n70kt84j',
failcheck : [
['bkNumGe2', "pzprv3/toichika/4/4/6/0 1 1 2 /3 1 2 2 /3 3 4 5 /3 4 4 4 /4 . . . /. . . . /. . . . /. . . . /. . . . /2 . . . /. . . . /4 . . . /"],
['arAdjPair',"pzprv3/toichika/4/4/6/0 1 1 2 /3 1 2 2 /3 3 4 5 /3 4 4 4 /4 . . . /. . . . /. . . . /. . . . /. + 3 . /. + . . /. . . . /. . . . /"],
['arAlone', "pzprv3/toichika/4/4/6/0 1 1 2 /3 1 2 2 /3 3 4 5 /3 4 4 4 /4 . . . /. . . . /. . . . /. . . . /. + + 3 /. 2 + + /. . . . /. . . . /"],
['bkNoNum', "pzprv3/toichika/4/4/6/0 1 1 2 /3 1 2 2 /3 3 4 5 /3 4 4 4 /4 . . . /. . . . /. . . . /. . . . /. + + 3 /. 2 + + /. + . . /. 1 . . /"],
[null, "pzprv3/toichika/4/4/6/0 1 1 2 /3 1 2 2 /3 3 4 5 /3 4 4 4 /4 . . . /. . . . /. . . . /. . . . /. + + 3 /+ 2 + + /4 + + 3 /+ 1 + + /"]
],
inputs : [
/* 問題入力はromaと同じなので省略 */
/* 回答入力テスト */
/* 矢印の入力はromaと同じ */
{ input:["newboard,5,2", "playmode"] },
{ input:["cursor,1,1", "key,1", "key,right,2", "key,right,3", "key,right,4"] },
{ input:["cursor,0,0", "mouse,right, 1,1, 3,1", "mouse,right, 1,3, 5,3", "mouse,right, 3,3, 7,3, 7,1"],
result:"pzprv3/toichika/2/5/1/0 0 0 0 0 /0 0 0 0 0 /. . . . . /. . . . . /+ + 2 . . /+ . . . . /" }
]
});
|
define(['some_dep'], function (dep) {
'use strict';
return {};
});
|
import { alias } from "@ember/object/computed";
import FollowButtonComponent from "../-follow-button/component";
export default FollowButtonComponent.extend({
modelName: "twitchChannelFollowed",
// model alias (component attribute)
model : alias( "channel" ),
// save the data on the channel record instead of the component
record : alias( "channel.followed" ),
// use the channel's display_name
name : alias( "channel.display_name" )
});
|
//noinspection JSUnusedGlobalSymbols
/**
* Checks if value matches to the predefined regexp
* @constructor
* @author dev.ymalcev@gmail.com
*/
function SymfonyComponentValidatorConstraintsRegex() {
this.message = '';
this.pattern = '';
this.match = true;
this.validate = function(value) {
var errors = [];
var f = FpJsFormValidator;
if (!f.isValueEmty(value) && !this.pattern.test(value)) {
errors.push(this.message.replace('{{ value }}', FpJsBaseConstraint.formatValue(value)));
}
return errors;
};
this.onCreate = function() {
var flags = this.pattern.match(/[\/#](\w*)$/);
this.pattern = new RegExp(this.pattern.trim().replace(/(^[\/#])|([\/#]\w*$)/g, ''), flags[1]);
}
}
|
(function() {
'use strict';
angular
.module('app')
.factory('User', User);
User.$inject = ['$resource'];
function User($resource) {
return $resource('/api/users/:id/:controller', {
id: '@_id'
},
{
changePassword: {
method: 'PUT',
params: {
controller:'password'
}
},
get: {
method: 'GET',
params: {
id:'me'
}
}
});
}
})(); |
"use babel";
// @flow
import { List, Map } from "immutable";
import type { PackagePanel } from "../Types/types";
import type { State } from "../../../GlobalSystem/types.js.flow";
import { selectTasksOfPlan } from "../../TaskExecutionFeature/Selectors/Tasks";
import type { Package } from "../../../ProjectSystemEpic/PackageFeature/Types/types.js.flow";
type PackageGroup = {
rootPackage: Package,
packages: List<Package>,
};
export function getPackagePanelsFromState(state: State): List<PackagePanel> {
const initialState: List<PackagePanel> = List();
return state.packages
.reduce((red, list) => red.concat(list), List())
.reduce((red: Map<string, PackageGroup>, packageInfo) => {
const rootFound = red.keySeq().find(key => {
return packageInfo.path.startsWith(key);
});
if (rootFound) {
return red.update(rootFound, group => ({
...group,
packages: group.packages.push(packageInfo),
}));
} else {
return red.set(packageInfo.path, {
rootPackage: packageInfo,
packages: List.of(packageInfo),
});
}
}, Map())
.reduce(
(packageReducer: List<PackagePanel>, packageFound: PackageGroup) => {
return packageReducer.push({
package: packageFound.rootPackage,
terminals: state.terminals
.get(packageFound.rootPackage.path, Map())
.toList(),
tools: state.devtools
.toList()
.filter(devtool => {
return (
packageFound.packages.find(
packageOfGroup =>
packageOfGroup.plugin.tool.id === devtool.id,
) !== undefined
);
})
.reduce((devtoolsReducer, devtool) => {
return devtoolsReducer.push({
tool: devtool,
plans: state.plans
.get(devtool.id, List())
.toList()
.filter(plan => {
return plan.packageInfo.path.startsWith(
packageFound.rootPackage.path,
);
})
.map(plan => ({
plan,
tasks: selectTasksOfPlan(state.tasks, plan),
})),
});
}, List()),
});
},
initialState,
);
}
|
// @require ../init.js
(function ( _ ) {
/* NOW SECS */
_.nowSecs = function () {
return Math.floor ( _.now () / 1000 );
};
}( window._ ));
|
/**
* jquery.dlmenu.js v1.0.1
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
;( function( $, window, undefined ) {
'use strict';
// global
var Modernizr = window.Modernizr, $body = $( 'body' );
$.DLMenu = function( options, element ) {
this.$el = $( element );
this._init( options );
};
// the options
$.DLMenu.defaults = {
// classes for the animation effects
animationClasses : { classin : 'dl-animate-in-1', classout : 'dl-animate-out-1' },
// callback: click a link that has a sub menu
// el is the link element (li); name is the level name
onLevelClick : function( el, name ) { return false; },
// callback: click a link that does not have a sub menu
// el is the link element (li); ev is the event obj
onLinkClick : function( el, ev ) { return false; }
};
$.DLMenu.prototype = {
_init : function( options ) {
// options
this.options = $.extend( true, {}, $.DLMenu.defaults, options );
// cache some elements and initialize some variables
this._config();
var animEndEventNames = {
'WebkitAnimation' : 'webkitAnimationEnd',
'OAnimation' : 'oAnimationEnd',
'msAnimation' : 'MSAnimationEnd',
'animation' : 'animationend'
},
transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
};
// animation end event name
this.animEndEventName = animEndEventNames[ Modernizr.prefixed( 'animation' ) ] + '.dlmenu';
// transition end event name
this.transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ] + '.dlmenu',
// support for css animations and css transitions
this.supportAnimations = Modernizr.cssanimations,
this.supportTransitions = Modernizr.csstransitions;
this._initEvents();
},
_config : function() {
this.open = false;
this.$trigger = $('.dl-trigger'); // Trigger button for opening the menu
this.$menu = this.$el.children( 'ul.dl-menu' );
this.$menuitems = this.$menu.find( 'li:not(.dl-back)' );
this.$el.find( 'ul.dl-submenu' ).prepend( '<li class="dl-back"><a href="#">back</a></li>' );
this.$back = this.$menu.find( 'li.dl-back' );
},
_initEvents : function() {
var self = this;
this.$trigger.on( 'click.dlmenu', function() {
if( self.open ) {
self._closeMenu();
}
else {
self._openMenu();
}
return false;
} );
this.$menuitems.on( 'click.dlmenu', function( event ) {
event.stopPropagation();
var $item = $(this),
$submenu = $item.children( 'ul.dl-submenu' );
if( $submenu.length > 0 ) {
var $flyin = $submenu.clone().css( 'opacity', 0 ).insertAfter( self.$menu ),
onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classout ).addClass( 'dl-subview' );
$item.addClass( 'dl-subviewopen' ).parents( '.dl-subviewopen:first' ).removeClass( 'dl-subviewopen' ).addClass( 'dl-subview' );
$flyin.remove();
};
setTimeout( function() {
$flyin.addClass( self.options.animationClasses.classin );
self.$menu.addClass( self.options.animationClasses.classout );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
self.options.onLevelClick( $item, $item.children( 'a:first' ).text() );
} );
return false;
}
else {
self.options.onLinkClick( $item, event );
}
} );
this.$back.on( 'click.dlmenu', function( event ) {
var $this = $( this ),
$submenu = $this.parents( 'ul.dl-submenu:first' ),
$item = $submenu.parent(),
$flyin = $submenu.clone().insertAfter( self.$menu );
var onAnimationEndFn = function() {
self.$menu.off( self.animEndEventName ).removeClass( self.options.animationClasses.classin );
$flyin.remove();
};
setTimeout( function() {
$flyin.addClass( self.options.animationClasses.classout );
self.$menu.addClass( self.options.animationClasses.classin );
if( self.supportAnimations ) {
self.$menu.on( self.animEndEventName, onAnimationEndFn );
}
else {
onAnimationEndFn.call();
}
$item.removeClass( 'dl-subviewopen' );
var $subview = $this.parents( '.dl-subview:first' );
if( $subview.is( 'li' ) ) {
$subview.addClass( 'dl-subviewopen' );
}
$subview.removeClass( 'dl-subview' );
} );
return false;
} );
},
closeMenu : function() {
if( this.open ) {
this._closeMenu();
}
},
_closeMenu : function() {
var self = this,
onTransitionEndFn = function() {
self.$menu.off( self.transEndEventName );
self._resetMenu();
};
this.$menu.removeClass( 'dl-menuopen' );
this.$menu.addClass( 'dl-menu-toggle' );
this.$trigger.removeClass( 'dl-active' );
if( this.supportTransitions ) {
this.$menu.on( this.transEndEventName, onTransitionEndFn );
}
else {
onTransitionEndFn.call();
}
this.open = false;
},
openMenu : function() {
if( !this.open ) {
this._openMenu();
}
},
_openMenu : function() {
var self = this;
// clicking somewhere else makes the menu close
$body.off( 'click' ).on( 'click.dlmenu', function() {
//self._closeMenu() ;
} );
this.$menu.addClass( 'dl-menuopen dl-menu-toggle' ).on( this.transEndEventName, function() {
$( this ).removeClass( 'dl-menu-toggle' );
} );
this.$trigger.addClass( 'dl-active' );
this.open = true;
},
// resets the menu to its original state (first level of options)
_resetMenu : function() {
this.$menu.removeClass( 'dl-subview' );
this.$menuitems.removeClass( 'dl-subview dl-subviewopen' );
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.dlmenu = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( !instance ) {
logError( "cannot call methods on dlmenu prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for dlmenu instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'dlmenu' );
if ( instance ) {
instance._init();
}
else {
instance = $.data( this, 'dlmenu', new $.DLMenu( options, this ) );
}
});
}
return this;
};
} )( jQuery, window ); |
import { GraphQLEnumType } from 'graphql';
export const errors = {
EMPTY: 'EMPTY',
NOT_TRIMMED: 'NOT_TRIMMED',
HAS_URI_COMPONENT: 'HAS_URI_COMPONENT',
TAKEN: 'TAKEN',
};
export default new GraphQLEnumType({
name: 'SlugErrorEnum',
description: 'Slug of canot',
values: {
[errors.EMPTY]: {
value: errors.EMPTY,
description: 'Slug is empty',
},
[errors.NOT_TRIMMED]: {
value: errors.NOT_TRIMMED,
description: 'Slug have leading or trailing spaces or line ends',
},
[errors.HAS_URI_COMPONENT]: {
value: errors.HAS_URI_COMPONENT,
description:
'Slug has URI component inside, which can be misleading to browsers',
},
[errors.TAKEN]: {
value: errors.TAKEN,
description: 'Slug has already been taken by someone else',
},
},
});
|
smalltalk.addPackage('Spaces');
smalltalk.addClass('ObjectSpace', smalltalk.Object, ['frame'], 'Spaces');
smalltalk.ObjectSpace.comment="I am a connection to another Smalltalk environment.\x0aThe implementation creates an iframe on the same location as the window, and connect to the Amber environment.\x0a\x0a\x0a\x0a## Usage example:\x0a\x0a\x09| space |\x0a\x09\x0a\x09space := ObjectSpace new.\x0a\x09space do: [ smalltalk ] \x22Answers aSmalltalk\x22\x0a\x09(space do: [ smalltalk ]) == smalltalk \x22Answers false\x22\x0a\x09\x0a\x09space release \x22Remove the object space environment\x22"
smalltalk.addMethod(
smalltalk.method({
selector: "connectTo:",
category: 'initialization',
fn: function (aFrame){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self)._release();
self["@frame"]=aFrame;
return self}, function($ctx1) {$ctx1.fill(self,"connectTo:",{aFrame:aFrame},smalltalk.ObjectSpace)})},
args: ["aFrame"],
source: "connectTo: aFrame\x0a\x09self release.\x0a\x09frame := aFrame",
messageSends: ["release"],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "create",
category: 'initialization',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(_st(window)._jQuery_("body"))._append_("<iframe style=\x22display: none;\x22></iframe>");
self["@frame"]=_st(_st(_st(window)._jQuery_("iframe"))._get())._last();
_st(_st(self["@frame"])._contentWindow())._location_(_st(window)._location());
return self}, function($ctx1) {$ctx1.fill(self,"create",{},smalltalk.ObjectSpace)})},
args: [],
source: "create\x0a\x09(window jQuery: 'body') append: '<iframe style=\x22display: none;\x22></iframe>'.\x0a\x09frame := (window jQuery: 'iframe') get last.\x0a\x09frame contentWindow location: window location",
messageSends: ["append:", "jQuery:", "last", "get", "location:", "location", "contentWindow"],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "destroy",
category: 'releasing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=self["@frame"];
if(($receiver = $1) == nil || $receiver == undefined){
$2=self;
return $2;
} else {
$1;
};
_st(_st(window)._jQuery_(self["@frame"]))._remove();
_st(self)._release();
return self}, function($ctx1) {$ctx1.fill(self,"destroy",{},smalltalk.ObjectSpace)})},
args: [],
source: "destroy\x0a\x09frame ifNil: [ ^ self ].\x0a\x09(window jQuery: frame) remove.\x0a\x0a\x09self release",
messageSends: ["ifNil:", "remove", "jQuery:", "release"],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "do:",
category: 'evaluating',
fn: function (aBlock){
var self=this;
function $ObjectSpaceConnectionError(){return smalltalk.ObjectSpaceConnectionError||(typeof ObjectSpaceConnectionError=="undefined"?nil:ObjectSpaceConnectionError)}
return smalltalk.withContext(function($ctx1) {
var $1,$2,$3;
$1=_st(self)._isConnected();
if(! smalltalk.assert($1)){
$2=_st($ObjectSpaceConnectionError())._signal();
return $2;
};
$3=_st(_st(self["@frame"])._contentWindow())._eval_(_st(_st("(").__comma(_st(aBlock)._compiledSource())).__comma(")()"));
return $3;
}, function($ctx1) {$ctx1.fill(self,"do:",{aBlock:aBlock},smalltalk.ObjectSpace)})},
args: ["aBlock"],
source: "do: aBlock\x0a\x09self isConnected ifFalse: [ ^ ObjectSpaceConnectionError signal ].\x0a\x09^ frame contentWindow eval: '(', aBlock compiledSource, ')()'",
messageSends: ["ifFalse:", "signal", "isConnected", "eval:", ",", "compiledSource", "contentWindow"],
referencedClasses: ["ObjectSpaceConnectionError"]
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "frame",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@frame"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"frame",{},smalltalk.ObjectSpace)})},
args: [],
source: "frame\x0a\x09^ frame",
messageSends: [],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "initialize",
category: 'initialization',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
smalltalk.Object.fn.prototype._initialize.apply(_st(self), []);
_st(self)._create();
return self}, function($ctx1) {$ctx1.fill(self,"initialize",{},smalltalk.ObjectSpace)})},
args: [],
source: "initialize\x0a\x09super initialize.\x0a\x09self create",
messageSends: ["initialize", "create"],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "isConnected",
category: 'initialization',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(self)._frame())._notNil();
return $1;
}, function($ctx1) {$ctx1.fill(self,"isConnected",{},smalltalk.ObjectSpace)})},
args: [],
source: "isConnected\x0a\x09^ self frame notNil",
messageSends: ["notNil", "frame"],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "release",
category: 'releasing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@frame"]=nil;
return self}, function($ctx1) {$ctx1.fill(self,"release",{},smalltalk.ObjectSpace)})},
args: [],
source: "release\x0a\x09frame := nil",
messageSends: [],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "whenReadyDo:",
category: 'events',
fn: function (aBlock){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(_st(window)._jQuery_(self["@frame"]))._bind_do_("load",aBlock);
return self}, function($ctx1) {$ctx1.fill(self,"whenReadyDo:",{aBlock:aBlock},smalltalk.ObjectSpace)})},
args: ["aBlock"],
source: "whenReadyDo: aBlock\x0a\x09(window jQuery: frame)\x0a\x09\x09bind: 'load'\x0a\x09\x09do: aBlock",
messageSends: ["bind:do:", "jQuery:"],
referencedClasses: []
}),
smalltalk.ObjectSpace);
smalltalk.addMethod(
smalltalk.method({
selector: "on:",
category: 'instance creation',
fn: function (aFrame){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=_st(self)._basicNew();
_st($2)._connectTo_(aFrame);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"on:",{aFrame:aFrame},smalltalk.ObjectSpace.klass)})},
args: ["aFrame"],
source: "on: aFrame\x0a\x09^ self basicNew\x0a\x09\x09connectTo: aFrame;\x0a\x09\x09yourself",
messageSends: ["connectTo:", "basicNew", "yourself"],
referencedClasses: []
}),
smalltalk.ObjectSpace.klass);
smalltalk.addClass('ObjectSpaceConnectionError', smalltalk.Error, [], 'Spaces');
smalltalk.addMethod(
smalltalk.method({
selector: "messageText",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return "The ObjectSpace is not connected";
}, function($ctx1) {$ctx1.fill(self,"messageText",{},smalltalk.ObjectSpaceConnectionError)})},
args: [],
source: "messageText\x0a\x09^ 'The ObjectSpace is not connected'",
messageSends: [],
referencedClasses: []
}),
smalltalk.ObjectSpaceConnectionError);
smalltalk.addClass('ObjectSpaceTest', smalltalk.TestCase, ['space'], 'Spaces');
smalltalk.addMethod(
smalltalk.method({
selector: "setUp",
category: 'initialization',
fn: function (){
var self=this;
function $ObjectSpace(){return smalltalk.ObjectSpace||(typeof ObjectSpace=="undefined"?nil:ObjectSpace)}
return smalltalk.withContext(function($ctx1) {
self["@space"]=_st($ObjectSpace())._new();
return self}, function($ctx1) {$ctx1.fill(self,"setUp",{},smalltalk.ObjectSpaceTest)})},
args: [],
source: "setUp\x0a\x09space := ObjectSpace new",
messageSends: ["new"],
referencedClasses: ["ObjectSpace"]
}),
smalltalk.ObjectSpaceTest);
smalltalk.addMethod(
smalltalk.method({
selector: "tearDown",
category: 'initialization',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self["@space"])._destroy();
return self}, function($ctx1) {$ctx1.fill(self,"tearDown",{},smalltalk.ObjectSpaceTest)})},
args: [],
source: "tearDown\x0a\x09space destroy",
messageSends: ["destroy"],
referencedClasses: []
}),
smalltalk.ObjectSpaceTest);
smalltalk.addMethod(
smalltalk.method({
selector: "testConnection",
category: 'tests',
fn: function (){
var self=this;
function $ObjectSpaceConnectionError(){return smalltalk.ObjectSpaceConnectionError||(typeof ObjectSpaceConnectionError=="undefined"?nil:ObjectSpaceConnectionError)}
return smalltalk.withContext(function($ctx1) {
_st(self["@space"])._destroy();
_st(self)._deny_(_st(self["@space"])._isConnected());
_st(self)._should_raise_((function(){
return smalltalk.withContext(function($ctx2) {
return _st(self["@space"])._do_((function(){
return smalltalk.withContext(function($ctx3) {
}, function($ctx3) {$ctx3.fillBlock({},$ctx1)})}));
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}),$ObjectSpaceConnectionError());
return self}, function($ctx1) {$ctx1.fill(self,"testConnection",{},smalltalk.ObjectSpaceTest)})},
args: [],
source: "testConnection\x0a\x09space destroy.\x0a\x09self deny: space isConnected.\x0a\x09self should: [ space do: [] ] raise: ObjectSpaceConnectionError",
messageSends: ["destroy", "deny:", "isConnected", "should:raise:", "do:"],
referencedClasses: ["ObjectSpaceConnectionError"]
}),
smalltalk.ObjectSpaceTest);
smalltalk.addMethod(
smalltalk.method({
selector: "testCreate",
category: 'tests',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self)._assert_(_st(_st(self["@space"])._frame())._notNil());
_st(self)._assert_(_st(self["@space"])._isConnected());
return self}, function($ctx1) {$ctx1.fill(self,"testCreate",{},smalltalk.ObjectSpaceTest)})},
args: [],
source: "testCreate\x0a\x0a\x09self assert: space frame notNil.\x0a\x09self assert: space isConnected",
messageSends: ["assert:", "notNil", "frame", "isConnected"],
referencedClasses: []
}),
smalltalk.ObjectSpaceTest);
smalltalk.addMethod(
smalltalk.method({
selector: "testEvaluation",
category: 'tests',
fn: function (){
var self=this;
var result;
function $Smalltalk(){return smalltalk.Smalltalk||(typeof Smalltalk=="undefined"?nil:Smalltalk)}
return smalltalk.withContext(function($ctx1) {
_st(self["@space"])._whenReadyDo_((function(){
return smalltalk.withContext(function($ctx2) {
result=_st(self["@space"])._do_((function(){
return smalltalk.withContext(function($ctx3) {
return smalltalk;
}, function($ctx3) {$ctx3.fillBlock({},$ctx1)})}));
result;
_st(self)._assert_equals_(_st(_st(result)._class())._name(),"Smalltalk");
_st(self)._deny_(_st(_st(result)._class()).__eq($Smalltalk()));
return _st(self)._deny_(_st(result).__eq_eq(smalltalk));
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"testEvaluation",{result:result},smalltalk.ObjectSpaceTest)})},
args: [],
source: "testEvaluation\x0a\x09| result |\x0a\x0a\x09space whenReadyDo: [\x0a\x09\x09result := space do: [ smalltalk ].\x0a\x0a\x09\x09self assert: result class name equals: 'Smalltalk'.\x0a\x09\x09self deny: result class = Smalltalk.\x0a\x09\x09self deny: result == smalltalk ]",
messageSends: ["whenReadyDo:", "do:", "assert:equals:", "name", "class", "deny:", "=", "=="],
referencedClasses: ["Smalltalk"]
}),
smalltalk.ObjectSpaceTest);
smalltalk.addMethod(
smalltalk.method({
selector: "testRelease",
category: 'tests',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self)._deny_(_st(_st(self["@space"])._frame())._isNil());
_st(self["@space"])._release();
_st(self)._assert_(_st(_st(self["@space"])._frame())._isNil());
return self}, function($ctx1) {$ctx1.fill(self,"testRelease",{},smalltalk.ObjectSpaceTest)})},
args: [],
source: "testRelease\x0a\x0a\x09self deny: space frame isNil.\x0a\x0a\x09space release.\x0a\x09\x0a\x09self assert: space frame isNil",
messageSends: ["deny:", "isNil", "frame", "release", "assert:"],
referencedClasses: []
}),
smalltalk.ObjectSpaceTest);
|
/*jshint multistr: true */
var Helpy = Helpy || {};
Helpy.ready = function(){
$('.selectpicker').selectpicker({});
$(".best_in_place").best_in_place();
$('.edit-topic-name-menu').on('click', function(){
$('.best_in_place').click();
});
$('.profile').initial();
$('.attachinary-input').attachinary();
$('.uploader').fileupload({
dataType: 'script',
singleFileUploads: false
});
$('.submit-loader').off('submit', Helpy.loader).on('submit', Helpy.loader);
$('.new-ticket-loader').off('submit', Helpy.loader).on('submit', function(){
var $form = $('form.new-ticket-loader');
$(document.body).append($form);
$form.addClass('hidden');
Helpy.loader();
});
$('.click-loader').off('click').on('click', Helpy.loader);
$('ul.pagination li a').off('click').on('click', Helpy.loader);
$('.screenshot-link').magnificPopup({type:'image', gallery:{enabled:true}});
// make sure dropdowns close after click of link
$(".dropdown-menu a").click(function() {
$(this).closest(".dropdown-menu").prev().dropdown("toggle");
});
$('.navbar-form, #search-form').off().on('submit', function(){
$('.navbar-collapse.in').collapse('hide');
});
$('.thumbnail, .stats').off();
// jquery hhoks for the home page
$('.topic-box').click(function(){
document.location.href = $(this).data("link");
});
$('.thumbnail, .stats').on('mouseover',function(){
$(this).css('cursor','pointer');
$(this).css('border','1px solid #666');
$(this).css('box-shadow', '0px 0px 10px #eee');
$(this).closest('.has-arrow').addClass('over');
});
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item.name )
.append( "<div class='ui-menu-item-heading'><a href=" + item.link + " >" + item.name + "</a></div>" )
.append( "<div class='ui-menu-item-content' >" + item.content + "</div>" )
.appendTo( ul );
};
$(".autosearch").keyup(function () {
var that = $(this);
value = $(this).val();
$(this).autocomplete({
source: function (request, response) {
jQuery.get("/"+location.href.split("/")[3]+"/search.json", {
query: value
}, function (data) {
response(data);
});
},
minLength: 3,
appendTo: that.next(),
focus: function( event, ui ) {
$(".autosearch").val(ui.item.name);
},
select: function( event, ui ) {
window.location.href = ui.item.link;
},
messages: {
noResults: '',
results: function() {}
}
});
});
$(".suggest-results").blur(function () {
var that = $(this);
var $results = $('.suggestion-results');
var $container = $('.suggestion-results-container');
$query = $(this).val();
if ($query.length >= 3) {
$.getJSON( "/"+location.href.split("/")[3]+"/search.json?depth=5&query=" + $query, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'><a href='" + val.link + "' target='blank'>" + val.name + "</a></li>" );
});
var $html = $( "<ul/>", {
"class": "suggested-results list-unstyled",
html: items.join( "" )}
);
if (items.length > 0) {
$results.html($html);
$container.removeClass("hidden");
$container.fadeIn();
}
});
}
});
$('.stats').on('click', function(){
$('.stats').css('border','1px solid #ddd');
$('.stats').css('box-shadow', '');
$('.has-arrow').removeClass("over");
$('.stats').removeClass("selected");
$(this).addClass('selected');
$(this).css('border','1px solid #666');
$(this).css('box-shadow', '0px 0px 10px #eee');
$(this).closest('.has-arrow').addClass('over');
var form = $("<form></form>");
var url = $(this).find('a').attr('href');
form.attr(
{
id : "formform",
// The location given in the link itself
action : $(this).find('a').attr('href'),
method : "GET",
"data-remote" : "true"
});
$("body").append(form);
$("#formform").submit();
$("#formform").remove();
// Show loader
Helpy.loader();
// Ensure history is captured in the browser
history.pushState(null, '', url);
$(window).off().on("popstate", function(){
console.log("Popstate fired: " + location.href);
$.getScript(location.href);
});
// Prevent the link from opening normally
return false;
});
$('.thumbnail, .stats').on('mouseout',function(){
if ($(this).hasClass('selected') !== true) {
$(this).css('cursor','auto');
$(this).css('border','1px solid #ddd');
$(this).css('box-shadow', '');
$(this).closest('.has-arrow').removeClass('over');
}
});
// Sets up autoscroll for any link with class autoscroll
// requires data-target param containing class or ID of target
$(".autoscroll").each(function(){
$(this).click(function(){
var scrollTarget=$(this).data("target");
$('html,body').animate({
scrollTop: $(scrollTarget).offset().top},'slow');
});
});
// used by create topic form
$('#topic_private_true').click(function(){
$("#topic_forum_id").parent().hide();
$('#new_topic').append("<input type='hidden' id='new_topic_forum_id' name='topic[forum_id]' value='1'/>");
Helpy.showGroup();
});
$('#topic_private_false').click(function(){
$("#topic_forum_id").parent().show();
$("#new_topic_forum_id").remove();
Helpy.showGroup();
});
// Generate temp email address on demand, in case the user does not have an email
$('.generate-temp').off().on('click', function(){
if ($('#topic_user_email').val() === '') {
var placeholder = Math.random().toString(36).substring(7);
$('#topic_user_email').val("change@me-" + placeholder + '.com');
$('#topic_user_email').trigger('change');
$('#topic_user_email').trigger('focusout');
return false;
}
});
// Hide/replace last child of breadcrumbs since I don't have time to hack gem right now
$("ul.breadcrumb li:last-child").html("");
// compress thread if there are more than 4 messages
var $threadAll = $('.post-container');
// add kind first to first post if it is missing
if (!$threadAll.first().hasClass('kind-first')) {
$threadAll.first().removeClass('kind-reply').addClass('kind-first');
}
var $thread = $('.post-container.kind-reply.disallow-post-voting');
if ($thread.size() >= 2) {
// insert expand thread message
var $hider = "<div class='collapsed-posts text-center'><span class='label label-collapsed'>" + Helpy.messages + " </span></div>";
// check to see if we are already collapsed
if ($(".collapsed-posts").size() === 0) {
$(".kind-first").append($hider);
}
// add listener to expand messages
$('.collapsed-posts').on('click', function(){
$thread.show();
$('.collapsed-posts').hide();
});
// hide thread, except for most recent message
$thread.hide().last().show();
}
// Use or append common reply
$('#post_reply_id').on('change', function(){
var common_reply = $('#post_reply_id option:selected');
// set value of summernote with existing value + common reply
$('#post_body').summernote('code', $('#post_body').summernote('code') + common_reply.val());
$('#topic_post_body').summernote('code', $('#topic_post_body').summernote('code') + common_reply.val());
$('.disableable').attr('disabled', false);
});
$('.post-menu span').off().on('click', function(){
$(this).closest('.post-container').css('z-index','99999');
});
function updateMessage(){
var output;
var messages = $('.topic-checkbox:checked').size();
$('.merge-span').hide();
console.log("Update");
switch(messages) {
case 1:
output = Helpy.selected[1];
$('.merge-span').hide();
break;
case 2:
output = Helpy.selected[2];
$('.merge-span').show();
break;
default:
output = Helpy.selected[3].replace("9", messages);
$('.merge-span').show();
break;
}
$('.selected-message').text(output);
}
$('#check-all').off().on('change', function(){
if (this.checked) {
$('.topic-checkbox').prop('checked', true);
$('#multiple-edit').fadeIn();
updateMessage();
} else {
$('.topic-checkbox').prop('checked', false);
$('#multiple-edit').fadeOut();
}
});
$('.topic-checkbox').off().on('change', function(){
if (this.checked) {
$('#multiple-edit').fadeIn();
updateMessage();
} else {
if ($('.topic-checkbox:checked').size() === 0) {
$('#multiple-edit').fadeOut();
} else {
updateMessage();
}
}
});
$('.multiple-update').off().on('click', function(){
var str = $(this).attr('href');
if ($('#select_all').is(':checked')) {
str = str + "&affect=all";
$(this).attr('href', str);
} else {
// collect array of all checked boxes
var topic_ids = {};
$('.topic-checkbox:checked').each(function(i){
topic_ids[i] = $(this).val();
});
// modify link to include array
$.each(topic_ids, function(i){
str = str + "&topic_ids[]=" + topic_ids[i];
});
$(this).attr('href', str);
}
// return true to follow the link
return true;
});
// Topic voting widget animation
$('.topic-points').hover(function(){
$(this).addClass('animated pulse');
$(this).prev().addClass('animated bounce');
}, function(){
$(this).removeClass('animated pulse');
$(this).prev().removeClass('animated bounce');
});
// Locale Picker
$('#lang').off().on('change', function() {
var url = $("#lang").val();
if(url !=="")
{
$("#locale-change").submit();
}
});
// Login/Forgot Switcher
$('.login-link').off().on('click', function() {
$('.login-form').show();
$('.forgot-form').hide();
$('.modal-title').text($('.login-form').data("title"));
$('.modal-links').show();
});
$('.forgot-link').off().on('click', function() {
$('.login-form').hide();
$('.forgot-form').show();
$(ClientSideValidations.selectors.forms).validate();
$('.modal-title').text($('.forgot-form').data("title"));
$('.modal-links').hide();
});
// Disable submit button if post not provided
$('.disable-empty').keyup(function(){
$('.disable-empty').each(function(){
if ($(this).val() === '') {
$('.disableable').attr('disabled', 'disabled');
} else {
$('.disableable').removeAttr('disabled');
}
});
});
$('.keyboard-shortcuts-link').off().on('click', function(){
Helpy.showShortcuts();
});
// Autolink messages
$('.post-body').each(function(){
var that = $(this);
var text = that.html();
that.html(text.autoLink({ target: "_blank" }));
});
// Post CC and BCC
$('.cc-bcc-toggle').off().on('click', function() {
$fieldContainer = $('.cc-bcc');
if ($fieldContainer.hasClass('hidden')){
$fieldContainer.removeClass('hidden');
var previousCC = $('.post-cc').last().text().split(": ")[1];
var previousBCC = $('.post-bcc').last().text().split(": ")[1];
$('#post_cc').val(previousCC);
$('#post_bcc').val(previousBCC);
$('.cc-bcc-toggle').addClass('fa-angle-up').removeClass('fa-angle-down');
} else {
$fieldContainer.addClass('hidden');
$('#post_cc').val("");
$('#post_bcc').val("");
$('.cc-bcc-toggle').removeClass('fa-angle-up').addClass('fa-angle-down');
}
});
// Hide required field indicator generated by simple_form, as we already
// Add this in css. There is probably a better way to do this?
$("abbr[title='required']").hide();
// Add hoversort icon
$('.hoversort').off().on('mouseover', function(){
$(this).prepend('<span class="fas fa-arrows-alt-v" style="color:#666; margin-right: 0;"></span>');
$(this).css("cursor","move");
$(this).on('mouseout', function(){
$(this).find('span.fa-arrows-alt-v').remove();
});
});
};
$.attachinary.config.template = '\
<ul class="list-inline attachinary-thumbnails">\
<% for(var i=0; i<files.length; i++){ %>\
<li>\
<% if(files[i].resource_type == "raw") { %>\
<div class="raw-file"></div>\
<% } else { %>\
<img\
src="<%= $.cloudinary.url(files[i].public_id, { "version": files[i].version, "format": "jpg", "crop": "fill", "width": 250, "height": 250 }) %>"\
alt="" width="75" height="75" />\
<% } %>\
<br/>\
<a href="#" data-remove="<%= files[i].public_id %>">Remove</a>\
</li>\
<% } %>\
</ul>\
';
// This is included here because you would expect to find it here. The function is actually called
// from event-tracking.js where we have to unbind and rebind the event to support turbolinks
Helpy.didthisHelp = function(yesno){
var message;
var contactus;
if (yesno === "no") {
message = "<h3>" + Helpy.noHelped + "</h3>";
contactus = "<div class='col-md-3 align-right'><h3>" + Helpy.contactUs + "</h3></div>";
} else {
message = "<h3>" + Helpy.yesHelped + "</h3>";
contactus = '';
}
message = "<div class='col-md-9'>" + message + "</div>" + contactus;
$('#did-this-help').html(message);
return true;
};
Helpy.showGroup = function() {
if ($('#topic_private_true').is(':checked')) {
$('#topic_team_list').parent().removeClass('hidden');
$("#topic_forum_id").parent().hide();
$('#new_topic').append("<input type='hidden' id='new_topic_forum_id' name='topic[forum_id]' value='1'/>");
$('#topic_team_list').removeClass('hidden');
} else if ($('#topic_private_false').is(':checked')) {
$('#topic_team_list').parent().addClass('hidden');
} else {
$('#topic_team_list').parent().removeClass('hidden');
}
};
Helpy.loader = function(){
$('#tickets').html("<div class=\"col-md-12 text-center no-tickets\"><i class=\"fas fa-spinner fa-pulse fa-3x fa-fw\"></i><span class=\"sr-only\"></span></div>");
};
// Provides attachment validation
Helpy.validateFiles = function (inputFile, allowedExtension, blockedExtension) {
var extErrorMessage, maxExceededMessage = "This file exceeds the maximum allowed file size (5 MB)";
if (allowedExtension.length > 0) {
extErrorMessage = "The following file types are allowed: " + allowedExtension;
} else if (blockedExtension.length > 0) {
extErrorMessage = "A file you attempted to upload is not allowed";
}
var extName;
var maxFileSize = $(inputFile).data('max-file-size');
var sizeExceeded = false;
var extError = false;
$.each(inputFile.files, function () {
if (this.size && maxFileSize && this.size > parseInt(maxFileSize)) { sizeExceeded = true; }
extName = this.name.split('.').pop();
if (allowedExtension.length > 0 && $.inArray(extName, allowedExtension) == -1) { extError = true; }
if (blockedExtension.length > 0 && $.inArray(extName, blockedExtension) != -1) { extError = true; }
});
if (sizeExceeded) {
window.alert(maxExceededMessage);
$(inputFile).val('');
}
if (extError) {
window.alert(extErrorMessage);
$(inputFile).val('');
}
};
$(document).ready(Helpy.ready);
$(document).on('page:load', Helpy.ready);
$(document).on('page:change', function () {
//Truncate Q&A responses
$('.shorten').jTruncate({
length: 200,
minTrail: 0,
moreText: " (more)",
lessText: " (less)",
ellipsisText: " ...",
moreAni: "",
lessAni: ""
});
// Allows image insertion into editor
$('.doc-form-files .cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
$('#doc_body').summernote('editor.insertImage', $.cloudinary.image(data.result.public_id).attr('src'));
return true;
});
});
|
const DrawCard = require('../../drawcard.js');
class FeverDreams extends DrawCard {
setupCardAbilities(ability) {
this.reaction({
when: {
onCardKneeled: event => event.card === this.parent
},
cost: ability.costs.discardGold(),
handler: () => {
this.controller.drawCardsToHand(2);
this.game.addMessage('{0} discards a gold from {1} to draw 2 cards', this.controller, this);
}
});
}
canAttach(player, card) {
if(card.getType() !== 'character' || card.controller === this.controller) {
return false;
}
return super.canAttach(player, card);
}
}
FeverDreams.code = '06050';
module.exports = FeverDreams;
|
import './js/jquery.instantSearch.js';
$(function() {
$('.search-field')
.instantSearch({
delay: 100,
})
.keyup();
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.