code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
import type { Config } from '../src/core/config'
import type VNode from '../src/core/vdom/vnode'
import type Watcher from '../src/core/observer/watcher'
declare interface Component {
// constructor information
static cid: number;
static options: Object;
// extend
static extend: (options: Object) => Function;
static superOptions: Object;
static extendOptions: Object;
static sealedOptions: Object;
static super: Class<Component>;
// assets
static directive: (id: string, def?: Function | Object) => Function | Object | void;
static component: (id: string, def?: Class<Component> | Object) => Class<Component>;
static filter: (id: string, def?: Function) => Function | void;
// public properties
$el: any; // so that we can attach __vue__ to it
$data: Object;
$options: ComponentOptions;
$parent: Component | void;
$root: Component;
$children: Array<Component>;
$refs: { [key: string]: Component | Element | Array<Component | Element> | void };
$slots: { [key: string]: Array<VNode> };
$scopedSlots: { [key: string]: () => VNodeChildren };
$vnode: VNode; // the placeholder node for the component in parent's render tree
$isServer: boolean;
$props: Object;
// public methods
$mount: (el?: Element | string, hydrating?: boolean) => Component;
$forceUpdate: () => void;
$destroy: () => void;
$set: <T>(target: Object | Array<T>, key: string | number, val: T) => T;
$delete: <T>(target: Object | Array<T>, key: string | number) => void;
$watch: (expOrFn: string | Function, cb: Function, options?: Object) => Function;
$on: (event: string | Array<string>, fn: Function) => Component;
$once: (event: string, fn: Function) => Component;
$off: (event?: string | Array<string>, fn?: Function) => Component;
$emit: (event: string, ...args: Array<mixed>) => Component;
$nextTick: (fn: Function) => void | Promise<*>;
$createElement: (tag?: string | Component, data?: Object, children?: VNodeChildren) => VNode;
// private properties
_uid: number;
_name: string; // this only exists in dev mode
_isVue: true;
_self: Component;
_renderProxy: Component;
_renderContext: ?Component;
_watcher: Watcher;
_watchers: Array<Watcher>;
_computedWatchers: { [key: string]: Watcher };
_data: Object;
_props: Object;
_events: Object;
_inactive: boolean | null;
_directInactive: boolean;
_isMounted: boolean;
_isDestroyed: boolean;
_isBeingDestroyed: boolean;
_vnode: ?VNode; // self root node
_staticTrees: ?Array<VNode>;
_hasHookEvent: boolean;
_provided: ?Object;
// private methods
// lifecycle
_init: Function;
_mount: (el?: Element | void, hydrating?: boolean) => Component;
_update: (vnode: VNode, hydrating?: boolean) => void;
// rendering
_render: () => VNode;
__patch__: (a: Element | VNode | void, b: VNode) => any;
// createElement
// _c is internal that accepts `normalizationType` optimization hint
_c: (vnode?: VNode, data?: VNodeData, children?: VNodeChildren, normalizationType?: number) => VNode | void;
// renderStatic
_m: (index: number, isInFor?: boolean) => VNode | VNodeChildren;
// markOnce
_o: (vnode: VNode | Array<VNode>, index: number, key: string) => VNode | VNodeChildren;
// toString
_s: (value: mixed) => string;
// text to VNode
_v: (value: string | number) => VNode;
// toNumber
_n: (value: string) => number | string;
// empty vnode
_e: () => VNode;
// loose equal
_q: (a: mixed, b: mixed) => boolean;
// loose indexOf
_i: (arr: Array<mixed>, val: mixed) => number;
// resolveFilter
_f: (id: string) => Function;
// renderList
_l: (val: mixed, render: Function) => ?Array<VNode>;
// renderSlot
_t: (name: string, fallback: ?Array<VNode>, props: ?Object) => ?Array<VNode>;
// apply v-bind object
_b: (data: any, value: any, asProp?: boolean) => VNodeData;
// check custom keyCode
_k: (eventKeyCode: number, key: string, builtInAlias: number | Array<number> | void) => boolean;
// resolve scoped slots
_u: (scopedSlots: ScopedSlotsData, res?: Object) => { [key: string]: Function };
// allow dynamic method registration
[key: string]: any
}
| search5/nanumlectures | static/bower_components/vue/flow/component.js | JavaScript | apache-2.0 | 4,160 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) {
if (n === 0)
return 0;
if (n === 1)
return 1;
if (n === 2)
return 2;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10)
return 3;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99)
return 4;
return 5;
}
export default [
'ar-JO',
[
['ص', 'م'],
,
],
[['ص', 'م'], , ['صباحًا', 'مساءً']],
[
['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
[
'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس',
'الجمعة', 'السبت'
],
,
['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت']
],
,
[
['ك', 'ش', 'آ', 'ن', 'أ', 'ح', 'ت', 'آ', 'أ', 'ت', 'ت', 'ك'],
[
'كانون الثاني', 'شباط', 'آذار', 'نيسان', 'أيار', 'حزيران',
'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني',
'كانون الأول'
],
],
,
[['ق.م', 'م'], , ['قبل الميلاد', 'ميلادي']], 6, [5, 6],
['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/y', 'd MMMM y', 'EEEE، d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
[
'{1} {0}',
,
,
],
[
'.', ',', ';', '\u200e%\u200e', '\u200e+', '\u200e-', 'E', '×', '‰', '∞',
'ليس رقمًا', ':'
],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'د.أ.\u200f', 'دينار أردني', plural
];
//# sourceMappingURL=ar-JO.js.map | rospilot/rospilot | share/web_assets/nodejs_deps/node_modules/@angular/common/locales/ar-JO.js | JavaScript | apache-2.0 | 1,996 |
// Declare internals
var internals = {};
// Plugin registration
exports.register = function (plugin, options, next) {
plugin.route({ path: '/test2', method: 'GET', handler: function (request, reply) { reply('testing123'); } });
plugin.route({ path: '/test2/path', method: 'GET', handler: function (request, reply) { reply(plugin.path); } });
plugin.log('test', 'abc');
return next();
};
| thebillkidy/WebRTC-Stream | server/node_modules/hapi/test/integration/pack/--test2/lib/index.js | JavaScript | apache-2.0 | 409 |
// Copyright (C) 2015 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Compound Assignment Operator evaluates its operands from left to right.
description: >
The left-hand side expression is evaluated before the right-hand side.
Left-hand side expression is MemberExpression: base[prop]. base is the
undefined value.
Check operator is "x <<= y".
---*/
function DummyError() { }
assert.throws(DummyError, function() {
var base = undefined;
var prop = function() {
throw new DummyError();
};
var expr = function() {
$ERROR("right-hand side expression evaluated");
};
base[prop()] <<= expr();
});
assert.throws(TypeError, function() {
var base = undefined;
var prop = {
toString: function() {
$ERROR("property key evaluated");
}
};
var expr = function() {
$ERROR("right-hand side expression evaluated");
};
base[prop] <<= expr();
});
| sebastienros/jint | Jint.Tests.Test262/test/language/expressions/compound-assignment/S11.13.2_A7.6_T2.js | JavaScript | bsd-2-clause | 974 |
/*!
* FileInput Polish Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['pl'] = {
fileSingle: 'plik',
filePlural: 'pliki',
browseLabel: 'Przeglądaj …',
removeLabel: 'Usuń',
removeTitle: 'Usuń zaznaczone pliki',
cancelLabel: 'Przerwij',
cancelTitle: 'Anuluj wysyłanie',
pauseLabel: 'Wstrzymaj',
pauseTitle: 'Wstrzymaj trwające przesyłanie',
uploadLabel: 'Wgraj',
uploadTitle: 'Wgraj zaznaczone pliki',
msgNo: 'Nie',
msgNoFilesSelected: 'Brak zaznaczonych plików',
msgPaused: 'Wstrzymano',
msgCancelled: 'Odwołany',
msgPlaceholder: 'Wybierz {files} ...',
msgZoomModalHeading: 'Szczegółowy podgląd',
msgFileRequired: 'Musisz wybrać plik do wgrania.',
msgSizeTooSmall: 'Plik "{name}" (<b>{size} KB</b>) jest zbyt mały i musi być większy niż <b>{minSize} KB</b>.',
msgSizeTooLarge: 'Plik o nazwie "{name}" (<b>{size} KB</b>) przekroczył maksymalną dopuszczalną wielkość pliku wynoszącą <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Minimalna liczba plików do wgrania: <b>{n}</b>.',
msgFilesTooMany: 'Liczba plików wybranych do wgrania w liczbie <b>({n})</b>, przekracza maksymalny dozwolony limit wynoszący <b>{m}</b>.',
msgTotalFilesTooMany: 'Możesz wgrać maksymalnie <b>{m}</b> plików (wykryto <b>{n}</b>).',
msgFileNotFound: 'Plik "{name}" nie istnieje!',
msgFileSecured: 'Ustawienia zabezpieczeń uniemożliwiają odczyt pliku "{name}".',
msgFileNotReadable: 'Plik "{name}" nie jest plikiem do odczytu.',
msgFilePreviewAborted: 'Podgląd pliku "{name}" został przerwany.',
msgFilePreviewError: 'Wystąpił błąd w czasie odczytu pliku "{name}".',
msgInvalidFileName: 'Nieprawidłowe lub nieobsługiwane znaki w nazwie pliku "{name}".',
msgInvalidFileType: 'Nieznany typ pliku "{name}". Tylko następujące rodzaje plików są dozwolone: "{types}".',
msgInvalidFileExtension: 'Złe rozszerzenie dla pliku "{name}". Tylko następujące rozszerzenia plików są dozwolone: "{extensions}".',
msgUploadAborted: 'Przesyłanie pliku zostało przerwane',
msgUploadThreshold: 'Przetwarzanie …',
msgUploadBegin: 'Rozpoczynanie …',
msgUploadEnd: 'Gotowe!',
msgUploadResume: 'Wznawianie przesyłania …',
msgUploadEmpty: 'Brak poprawnych danych do przesłania.',
msgUploadError: 'Błąd przesyłania',
msgDeleteError: 'Błąd usuwania',
msgProgressError: 'Błąd',
msgValidationError: 'Błąd walidacji',
msgLoading: 'Wczytywanie pliku {index} z {files} …',
msgProgress: 'Wczytywanie pliku {index} z {files} - {name} - {percent}% zakończone.',
msgSelected: '{n} Plików zaznaczonych',
msgFoldersNotAllowed: 'Metodą przeciągnij i upuść, można przenosić tylko pliki. Pominięto {n} katalogów.',
msgImageWidthSmall: 'Szerokość pliku obrazu "{name}" musi być co najmniej {size} px.',
msgImageHeightSmall: 'Wysokość pliku obrazu "{name}" musi być co najmniej {size} px.',
msgImageWidthLarge: 'Szerokość pliku obrazu "{name}" nie może przekraczać {size} px.',
msgImageHeightLarge: 'Wysokość pliku obrazu "{name}" nie może przekraczać {size} px.',
msgImageResizeError: 'Nie udało się uzyskać wymiaru obrazu, aby zmienić rozmiar.',
msgImageResizeException: 'Błąd podczas zmiany rozmiaru obrazu.<pre>{errors}</pre>',
msgAjaxError: 'Coś poczło nie tak podczas {operation}. Spróbuj ponownie!',
msgAjaxProgressError: '{operation} nie powiodło się',
msgDuplicateFile: 'Plik "{name}" o identycznym rozmiarze "{size} KB" został wgrany wcześniej. Pomijanie zduplikowanego pliku.',
msgResumableUploadRetriesExceeded: 'Przekroczono limit <b>{max}</b> prób wgrania pliku <b>{file}</b>! Szczegóły błędu: <pre>{error}</pre>',
msgPendingTime: 'Pozostało {time}',
msgCalculatingTime: 'obliczanie pozostałego czasu',
ajaxOperations: {
deleteThumb: 'usuwanie pliku',
uploadThumb: 'przesyłanie pliku',
uploadBatch: 'masowe przesyłanie plików',
uploadExtra: 'przesyłanie danych formularza'
},
dropZoneTitle: 'Przeciągnij i upuść pliki tutaj …',
dropZoneClickTitle: '<br>(lub kliknij tutaj i wybierz {files} z komputera)',
fileActionSettings: {
removeTitle: 'Usuń plik',
uploadTitle: 'Przesyłanie pliku',
uploadRetryTitle: 'Ponów',
downloadTitle: 'Pobierz plik',
zoomTitle: 'Pokaż szczegóły',
dragTitle: 'Przenies / Ponownie zaaranżuj',
indicatorNewTitle: 'Jeszcze nie przesłany',
indicatorSuccessTitle: 'Dodane',
indicatorErrorTitle: 'Błąd',
indicatorPausedTitle: 'Przesyłanie zatrzymane',
indicatorLoadingTitle: 'Przesyłanie …'
},
previewZoomButtonTitles: {
prev: 'Pokaż poprzedni plik',
next: 'Pokaż następny plik',
toggleheader: 'Włącz / wyłącz nagłówek',
fullscreen: 'Włącz / wyłącz pełny ekran',
borderless: 'Włącz / wyłącz tryb bez ramek',
close: 'Zamknij szczegółowy widok'
}
};
})(window.jQuery);
| OlliL/lalaMoneyflow | client/contrib/bootstrap-fileinput/js/locales/pl.js | JavaScript | bsd-2-clause | 5,901 |
var path = require('path');
var url = require('url');
var closure = require('closure-util');
var nomnom = require('nomnom');
var log = closure.log;
var options = nomnom.options({
port: {
abbr: 'p',
'default': 4000,
help: 'Port for incoming connections',
metavar: 'PORT'
},
loglevel: {
abbr: 'l',
choices: ['silly', 'verbose', 'info', 'warn', 'error'],
'default': 'info',
help: 'Log level',
metavar: 'LEVEL'
}
}).parse();
/** @type {string} */
log.level = options.loglevel;
log.info('ol3-cesium', 'Parsing dependencies ...');
var manager = new closure.Manager({
closure: true, // use the bundled Closure Library
lib: [
'src/**/*.js'
],
ignoreRequires: '^ol\\.'
});
manager.on('error', function(e) {
log.error('ol3-cesium', e.message);
});
manager.on('ready', function() {
var server = new closure.Server({
manager: manager,
loader: '/@loader'
});
server.listen(options.port, function() {
log.info('ol3-cesium', 'Listening on http://localhost:' +
options.port + '/ (Ctrl+C to stop)');
});
server.on('error', function(err) {
log.error('ol3-cesium', 'Server failed to start: ' + err.message);
process.exit(1);
});
});
| GistdaDev/ol3-cesium | build/serve.js | JavaScript | bsd-2-clause | 1,218 |
/**
* This is specifically for the builder where the
* dependencies have been resolved and you just want
* to access the component.jsons locally.
*/
var semver = require('semver');
var fs = require('graceful-fs');
var join = require('path').join;
var resolve = require('path').resolve;
var debug = require('debug')('remotes:local');
var Remote = require('../remote')
module.exports = Local
Remote.extend(Local)
function Local(options) {
if (!(this instanceof Local))
return new Local(options)
options = Object.create(options || {});
this.out = resolve(options.out
|| options.dir
|| 'components')
debug('checking local components at %s', this.out);
Remote.call(this, options)
}
Local.prototype.name = 'local';
/**
* Local resolution is a little different than other remotes.
* In particular, if no `ref` is set,
* we check for any version.
*
* @param {String} repo
* @return {this}
* @api public
*/
Local.prototype.resolve = function* (remotes, repo, ref) {
debug('resolving local remote');
if (typeof remotes === 'string') {
ref = repo;
repo = remotes;
} else if (Array.isArray(remotes) && !~remotes.indexOf('local')) {
// if the current remote is not in this list,
// then it's obviously not valid.
return;
}
var folders = yield* this.folders(repo);
// none installed
if (!folders || !folders.length) return;
// no specific version we care about
if (!ref) return this;
// exact tag version
if (~folders.indexOf(ref)) return this;
// check for equal semantic versions
if (semver.maxSatisfying(folders.filter(valid), ref)) return this;
}
/**
* Get the currently downloaded versions of a repo.
*
* @param {String} repo
* @return {Array} folders
* @api public
*/
Local.prototype.folders = function* (repo) {
try {
var frags = repo.toLowerCase().split('/');
// ignore malformed repos for now
if (frags.length !== 2) return;
var folder = join(this.out, frags[0], frags[1]);
debug('checking folder: %s', folder);
var folders = yield readdir(folder);
debug('got folders: %s', folders.join(', '));
return folders.filter(noLeadingDot);
} catch (err) {
if (err.code === 'ENOENT') return;
throw err;
}
}
/**
* Return the currently downloaded components' semantic versions.
*
* @param {String} repo
* @return {Array} references
* @api public
*/
Local.prototype._versions = function* (repo) {
return yield* this.folders(repo);
}
/**
* Return the existing component.json, if any.
* @param {String} repo
* @param {String} reference
* @return {Object} component.json
* @api public
*/
Local.prototype._json = function* (repo, ref) {
var body;
var filename = join(this.out, repo, ref, 'component.json');
try {
body = yield read(filename);
} catch (err) {
if (err.code === 'ENOENT') return;
throw err;
}
try {
return JSON.parse(body);
} catch (_err) {
throw new Error('JSON parsing error with "' + filename + '"');
}
}
/**
* NOT RELEVANT WITH THIS REMOTE
*/
Local.prototype._tree = function* () {
/* jshint noyield:true */
}
function valid(x) {
return semver.valid(x, true);
}
function noLeadingDot(x) {
return x[0] !== '.';
}
function readdir(root) {
return function (done) {
fs.readdir(root, done)
}
}
function read(filename) {
return function (done) {
fs.readFile(filename, 'utf8', done)
}
}
| bmanth60/workflow-test | node_modules/component/node_modules/component-remotes/lib/remotes/local.js | JavaScript | bsd-3-clause | 3,407 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {createElementWithClassName} from 'chrome://resources/js/util.m.js';
/**
* Create by |LineChart.LineChart|.
* Create a dummy scrollbar to show the position of the line chart and to scroll
* the line chart, so we can draw the visible part of the line chart only
* instead of drawing the whole chart.
* @const
*/
export class Scrollbar {
constructor(/** function(): undefined */ callback) {
/** @const {function(): undefined} - Handle the scrolling event. */
this.callback_ = callback;
/** @type {number} - The range the scrollbar can scroll. */
this.range_ = 0;
/** @type {number} - The current position of the scrollbar. */
this.position_ = 0;
/** @type {number} - The real width of this scrollbar, in pixels. */
this.width_ = 0;
/** @type {Element} - The outer div to show the scrollbar. */
this.outerDiv_ =
createElementWithClassName('div', 'horizontal-scrollbar-outer');
this.outerDiv_.addEventListener('scroll', this.onScroll_.bind(this));
/** @type {Element} - The inner div to make outer div scrollable. */
this.innerDiv_ =
createElementWithClassName('div', 'horizontal-scrollbar-inner');
this.outerDiv_.appendChild(this.innerDiv_);
}
/**
* Scrolling event handler.
*/
onScroll_() {
const /** number */ newPosition = this.outerDiv_.scrollLeft;
if (newPosition == this.position_)
return;
this.position_ = newPosition;
this.callback_();
}
/** @return {Element} */
getRootDiv() {
return this.outerDiv_;
}
/**
* Return the height of scrollbar element.
* @return {number}
*/
getHeight() {
return this.outerDiv_.offsetHeight;
}
/** @return {number} */
getRange() {
return this.range_;
}
/**
* Position may be float point number because |document.scrollLeft| may be
* float point number.
* @return {number}
*/
getPosition() {
return Math.round(this.position_);
}
/**
* Change the size of the outer div and update the scrollbar position.
* @param {number} width
*/
resize(width) {
if (this.width_ == width)
return;
this.width_ = width;
this.updateOuterDivWidth_();
}
updateOuterDivWidth_() {
this.constructor.setNodeWidth(this.outerDiv_, this.width_);
}
/**
* Set the scrollable range to |range|. Use the inner div's width to control
* the scrollable range. If position go out of range after range update, set
* it to the boundary value.
* @param {number} range
*/
setRange(range) {
this.range_ = range;
this.updateInnerDivWidth_();
if (range < this.position_) {
this.position_ = range;
this.updateScrollbarPosition_();
}
}
updateInnerDivWidth_() {
const width = this.outerDiv_.clientWidth;
this.constructor.setNodeWidth(this.innerDiv_, width + this.range_);
}
/**
* @param {Element} node
* @param {number} width
*/
static setNodeWidth(node, width) {
node.style.width = width + 'px';
}
/**
* Set the scrollbar position to |position|. If the new position go out of
* range, set it to the boundary value.
* @param {number} position
*/
setPosition(position) {
const /** number */ newPosition =
Math.max(0, Math.min(position, this.range_));
this.position_ = newPosition;
this.updateScrollbarPosition_();
}
/**
* Update the scrollbar position via Javascript scrollbar api. Position may
* not be the same value as what we assigned even if the value is in the
* range. See crbug.com/760425.
*/
updateScrollbarPosition_() {
if (this.outerDiv_.scrollLeft == this.position_)
return;
this.outerDiv_.scrollLeft = this.position_;
}
/**
* Return true if scrollbar is at the right edge of the chart.
* @return {boolean}
*/
isScrolledToRightEdge() {
/* |scrollLeft| may become a float point number even if we set it to some
* integer value. If the distance to the right edge less than 2 pixels, we
* consider that it is scrolled to the right edge.
*/
const scrollLeftErrorAmount = 2;
return this.position_ + scrollLeftErrorAmount > this.range_;
}
/**
* Scroll the scrollbar to the right edge.
*/
scrollToRightEdge() {
this.setPosition(this.range_);
}
}
| chromium/chromium | chrome/browser/resources/chromeos/sys_internals/line_chart/scrollbar.js | JavaScript | bsd-3-clause | 4,454 |
function safeMatchMedia(query) {
var m = window.matchMedia(query);
return !!m && m.matches;
}
define('capabilities', [], function() {
var capabilities = {
'JSON': window.JSON && typeof JSON.parse == 'function',
'debug': (('' + document.location).indexOf('dbg') >= 0),
'debug_in_page': (('' + document.location).indexOf('dbginpage') >= 0),
'console': window.console && (typeof window.console.log == 'function'),
'replaceState': typeof history.replaceState === 'function',
'chromeless': window.locationbar && !window.locationbar.visible,
'localStorage': false,
'sessionStorage': false,
'webApps': !!(navigator.mozApps && navigator.mozApps.install),
'app_runtime': !!(
navigator.mozApps &&
typeof navigator.mozApps.html5Implementation === 'undefined'
),
'fileAPI': !!window.FileReader,
'userAgent': navigator.userAgent,
'desktop': false,
'tablet': false,
'mobile': safeMatchMedia('(max-width: 600px)'),
'firefoxAndroid': (navigator.userAgent.indexOf('Firefox') != -1 && navigator.userAgent.indexOf('Android') != -1),
'touch': ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
'nativeScroll': (function() {
return 'WebkitOverflowScrolling' in document.createElement('div').style;
})(),
'performance': !!(window.performance || window.msPerformance || window.webkitPerformance || window.mozPerformance),
'navPay': !!navigator.mozPay,
'webactivities': !!(window.setMessageHandler || window.mozSetMessageHandler),
'firefoxOS': null // This is set below.
};
// We're probably tablet if we have touch and we're larger than mobile.
capabilities.tablet = capabilities.touch && safeMatchMedia('(min-width: 601px)');
// We're probably desktop if we don't have touch and we're larger than some arbitrary dimension.
capabilities.desktop = !capabilities.touch && safeMatchMedia('(min-width: 673px)');
// Packaged-app installation are supported only on Firefox OS, so this is how we sniff.
capabilities.gaia = !!(capabilities.mobile && navigator.mozApps && navigator.mozApps.installPackage);
capabilities.getDeviceType = function() {
return this.desktop ? 'desktop' : (this.tablet ? 'tablet' : 'mobile');
};
if (capabilities.tablet) {
// If we're on tablet, then we're not on desktop.
capabilities.desktop = false;
}
if (capabilities.mobile) {
// If we're on mobile, then we're not on desktop nor tablet.
capabilities.desktop = capabilities.tablet = false;
}
// Detect Firefox OS.
// This will be true if the request is from a Firefox OS phone *or*
// a desktop B2G build with the correct UA pref, such as this:
// https://github.com/mozilla/r2d2b2g/blob/master/prosthesis/defaults/preferences/prefs.js
capabilities.firefoxOS = capabilities.gaia && !capabilities.firefoxAndroid;
try {
if ('localStorage' in window && window.localStorage !== null) {
capabilities.localStorage = true;
}
} catch (e) {
}
try {
if ('sessionStorage' in window && window.sessionStorage !== null) {
capabilities.sessionStorage = true;
}
} catch (e) {
}
return capabilities;
});
z.capabilities = require('capabilities');
| Joergen/zamboni | media/js/mkt/capabilities.js | JavaScript | bsd-3-clause | 3,467 |
var expect = require('expect.js');
var path = require('path');
var fs = require('../extfs');
describe('extfs', function () {
var rootPath = path.join(__dirname, '../');
it('should return all directories', function (done) {
fs.getDirs(rootPath, function (err, dirs) {
expect(dirs).to.be.an(Array);
expect(dirs.length).to.be.greaterThan(0);
done();
});
});
it('should return all directories sync', function () {
var dirs = fs.getDirsSync(rootPath);
expect(dirs).to.be.an(Array);
expect(dirs.length > 0).to.be.ok();
});
it('should check if a file is empty', function (done) {
var notEmptyFile = path.join(__dirname, '../README.md');
var emptyFile = './AN EMPTY FILE';
fs.isEmpty(notEmptyFile, function (empty) {
expect(empty).to.be(false);
fs.isEmpty(emptyFile, function (empty) {
expect(empty).to.be(true);
done();
});
});
});
it('should check if a file is empty sync', function () {
var notEmptyFile = path.join(__dirname, '../README.md');
var emptyFile = './AN EMPTY FILE';
var empty = fs.isEmptySync(notEmptyFile);
expect(empty).to.be(false);
empty = fs.isEmptySync(emptyFile);
expect(empty).to.be(true);
});
it('should check if a directory is empty', function (done) {
var notEmptyDir = __dirname;
var emptyDir = './AN EMPTY DIR';
fs.isEmpty(notEmptyDir, function (empty) {
expect(empty).to.be(false);
fs.isEmpty(emptyDir, function (empty) {
expect(empty).to.be(true);
done();
})
});
});
it('should check if a directory is empty sync', function () {
var notEmptyDir = __dirname;
var emptyDir = './AN EMPTY DIR';
expect(fs.isEmptySync(notEmptyDir)).to.be(false);
expect(fs.isEmptySync(emptyDir)).to.be(true);
});
describe('remove directories', function () {
var tmpPath = path.join(rootPath, 'tmp');
var folders = [ 'folder1', 'folder2', 'folder3' ];
var files = [ '1.txt', '2.txt', '3.txt' ];
folders = folders.map(function (folder) {
return path.join(tmpPath, folder);
});
/**
* Create 3 folders with 3 files each
*/
beforeEach(function () {
if (!fs.existsSync(tmpPath)) {
fs.mkdirSync(tmpPath, '0755');
}
folders.forEach(function (folder) {
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder, '0755');
}
files.forEach(function (file) {
fs.writeFile(path.join(folder, file), 'file content');
});
});
});
it('should remove a non empty directory', function (done) {
fs.remove(tmpPath, function (err) {
expect(err).to.be(null);
expect(fs.existsSync(tmpPath)).to.be(false);
done();
});
});
it('should remove a non empty directory synchronously', function () {
fs.removeSync(tmpPath);
expect(fs.existsSync(tmpPath)).to.be(false);
});
it('should remove an array of directories', function (done) {
fs.remove(folders, function (err) {
expect(err).to.be(null);
expect(fs.existsSync(folders[0])).to.be(false);
expect(fs.existsSync(folders[1])).to.be(false);
expect(fs.existsSync(folders[2])).to.be(false);
expect(fs.existsSync(tmpPath)).to.be(true);
done();
});
});
it('should remove an array of directories synchronously', function () {
fs.removeSync(folders);
expect(fs.existsSync(folders[0])).to.be(false);
expect(fs.existsSync(folders[1])).to.be(false);
expect(fs.existsSync(folders[2])).to.be(false);
expect(fs.existsSync(tmpPath)).to.be(true);
});
});
it('should extends to fs', function () {
expect(fs.readdir).to.be.a(Function);
});
}); | codexar/npm-extfs | tests/extfsTest.js | JavaScript | mit | 3,671 |
describe("BASIC CRUD SCENARIOS", function() {
require("./basic");
});
describe("VALIDATE CRUD SCENARIOS", function() {
require("./validation");
});
describe("REPORT SCENARIOS", function() {
require("./report");
}); | AndreaZain/dl-module | test/production/finishing-printing/monitoring-event/index.js | JavaScript | mit | 228 |
var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure();
var testCase = require('../../deps/nodeunit').testCase,
debug = require('util').debug,
inspect = require('util').inspect,
nodeunit = require('../../deps/nodeunit'),
gleak = require('../../tools/gleak'),
Db = mongodb.Db,
Cursor = mongodb.Cursor,
Collection = mongodb.Collection,
Server = mongodb.Server,
ServerManager = require('../../test/tools/server_manager').ServerManager,
Step = require("../../deps/step/lib/step");
var MONGODB = 'integration_tests';
var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)});
var serverManager = null;
// Define the tests, we want them to run as a nested test so we only clean up the
// db connection once
var tests = testCase({
setUp: function(callback) {
callback();
},
tearDown: function(callback) {
// serverManager.stop(9, function(err, result) {
callback();
// });
},
shouldCorrectlyKeepInsertingDocumentsWhenServerDiesAndComesUp : function(test) {
var db1 = new Db('mongo-ruby-test-single-server', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)});
// All inserted docs
var docs = [];
var errs = [];
var insertDocs = [];
// Start server
serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true})
serverManager.start(true, function() {
db1.open(function(err, db) {
// Startup the insert of documents
var intervalId = setInterval(function() {
db.collection('inserts', function(err, collection) {
var doc = {timestamp:new Date().getTime()};
insertDocs.push(doc);
// Insert document
collection.insert(doc, {safe:{fsync:true}}, function(err, result) {
// Save errors
if(err != null) errs.push(err);
if(err == null) {
docs.push(result[0]);
}
})
});
}, 500);
// Wait for a second and then kill the server
setTimeout(function() {
// Kill server instance
serverManager.stop(9, function(err, result) {
// Server down for 1 second
setTimeout(function() {
// Restart server
serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true});
serverManager.start(true, function() {
// Wait for it
setTimeout(function() {
// Drop db
db.dropDatabase(function(err, result) {
// Close db
db.close();
// Check that we got at least one error
// test.ok(errs.length > 0);
test.ok(docs.length > 0);
test.ok(insertDocs.length > 0);
// Finish up
test.done();
});
}, 5000)
})
}, 1000);
});
}, 3000);
})
});
},
shouldCorrectlyInsertKillServerFailThenRestartServerAndSucceed : function(test) {
var db = new Db('test-single-server-recovery', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {numberOfRetries:3, retryMiliSeconds:500, native_parser: (process.env['TEST_NATIVE'] != null)});
// All inserted docs
var docs = [];
var errs = [];
var insertDocs = [];
// Start server
serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true})
serverManager.start(true, function() {
db.open(function(err, db) {
// Add an error handler
db.on("error", function(err) {
console.log("----------------------------------------------- received error")
console.dir(err)
errs.push(err);
});
db.collection('inserts', function(err, collection) {
var doc = {timestamp:new Date().getTime(), a:1};
collection.insert(doc, {safe:true}, function(err, result) {
test.equal(null, err);
// Kill server instance
serverManager.stop(9, function(err, result) {
// Attemp insert (should timeout)
var doc = {timestamp:new Date().getTime(), b:1};
collection.insert(doc, {safe:true}, function(err, result) {
test.ok(err != null);
test.equal(null, result);
// Restart server
serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true});
serverManager.start(true, function() {
// Attemp insert again
collection.insert(doc, {safe:true}, function(err, result) {
// Fetch the documents
collection.find({b:1}).toArray(function(err, items) {
test.equal(null, err);
test.equal(1, items[0].b);
test.done();
});
});
});
});
});
})
});
});
});
},
noGlobalsLeaked : function(test) {
var leaks = gleak.detectNew();
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
test.done();
}
})
// Assign out tests
module.exports = tests; | thebinarypenguin/tasty | server/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js | JavaScript | mit | 5,743 |
'use strict';
describe('Controller: AboutCtrl', function () {
// load the controller's module
beforeEach(module('e01App'));
var AboutCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AboutCtrl = $controller('AboutCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(AboutCtrl.awesomeThings.length).toBe(3);
});
});
| malaniz/cursoAngular | cl06ClienteB/test/spec/controllers/about.js | JavaScript | mit | 550 |
var searchData=
[
['digitalpin_2eh',['DigitalPin.h',['../_digital_pin_8h.html',1,'']]]
];
| cnorfleet/Feeder | libraries/SdFatCopy/html/search/files_2.js | JavaScript | mit | 92 |
/**
* @typedef {object} Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig
* @since 3.0.0
*
* @property {Phaser.GameObjects.DynamicBitmapText} parent - The Dynamic Bitmap Text object that owns this character being rendered.
* @property {Phaser.Types.GameObjects.BitmapText.TintConfig} tint - The tint of the character being rendered. Always zero in Canvas.
* @property {number} index - The index of the character being rendered.
* @property {number} charCode - The character code of the character being rendered.
* @property {number} x - The x position of the character being rendered.
* @property {number} y - The y position of the character being rendered.
* @property {number} scale - The scale of the character being rendered.
* @property {number} rotation - The rotation of the character being rendered.
* @property {any} data - Custom data stored with the character being rendered.
*/
/**
* @callback Phaser.Types.GameObjects.BitmapText.DisplayCallback
*
* @param {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} display - Settings of the character that is about to be rendered.
*
* @return {Phaser.Types.GameObjects.BitmapText.DisplayCallbackConfig} Altered position, scale and rotation values for the character that is about to be rendered.
*/
| mahill/phaser | src/gameobjects/bitmaptext/typedefs/DisplayCallbackConfig.js | JavaScript | mit | 1,291 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = Buffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
*
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will
* get the Object implementation, which is slower but will work correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return 42 === arr.foo() && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* Class: Buffer
* =============
*
* The Buffer constructor returns instances of `Uint8Array` that are augmented
* with function properties for all the node `Buffer` API functions. We use
* `Uint8Array` so that square bracket notation works as expected -- it returns
* a single octet.
*
* By augmenting the instances, we can avoid modifying the `Uint8Array`
* prototype.
*/
function Buffer (subject, encoding, noZero) {
if (!(this instanceof Buffer))
return new Buffer(subject, encoding, noZero)
var type = typeof subject
// Find the length
var length
if (type === 'number')
length = subject > 0 ? subject >>> 0 : 0
else if (type === 'string') {
if (encoding === 'base64')
subject = base64clean(subject)
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) { // assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data))
subject = subject.data
length = +subject.length > 0 ? Math.floor(+subject.length) : 0
} else
throw new TypeError('must start with number, buffer, array or string')
if (this.length > kMaxLength)
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength.toString(16) + ' bytes')
var buf
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
buf = Buffer._augment(new Uint8Array(length))
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
buf = this
buf.length = length
buf._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
buf._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++)
buf[i] = subject.readUInt8(i)
} else {
for (i = 0; i < length; i++)
buf[i] = ((subject[i] % 256) + 256) % 256
}
} else if (type === 'string') {
buf.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT && !noZero) {
for (i = 0; i < length; i++) {
buf[i] = 0
}
}
return buf
}
Buffer.isBuffer = function (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))
throw new TypeError('Arguments must be Buffers')
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {}
if (i !== len) {
x = a[i]
y = b[i]
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function (list, totalLength) {
if (!isArray(list)) throw new TypeError('Usage: Buffer.concat(list[, length])')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.byteLength = function (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
case 'hex':
ret = str.length >>> 1
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'base64':
ret = base64ToBytes(str).length
break
default:
ret = str.length
}
return ret
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function (encoding, start, end) {
var loweredCase = false
start = start >>> 0
end = end === undefined || end === Infinity ? this.length : end >>> 0
if (!encoding) encoding = 'utf8'
if (start < 0) start = 0
if (end > this.length) end = this.length
if (end <= start) return ''
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase)
throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.equals = function (b) {
if(!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max)
str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
return Buffer.compare(this, b)
}
// `get` will be removed in Node 0.13+
Buffer.prototype.get = function (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
Buffer.prototype.set = function (v, offset) {
console.log('.set() is deprecated. Access using array indexes instead.')
return this.writeUInt8(v, offset)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var byte = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(byte)) throw new Error('Invalid hex string')
buf[offset + i] = byte
}
return i
}
function utf8Write (buf, string, offset, length) {
var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
Buffer.prototype.toJSON = function () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function binarySlice (buf, start, end) {
return asciiSlice(buf, start, end)
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len;
if (start < 0)
start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0)
end = 0
} else if (end > len) {
end = len
}
if (end < start)
end = start
if (Buffer.TYPED_ARRAY_SUPPORT) {
return Buffer._augment(this.subarray(start, end))
} else {
var sliceLen = end - start
var newBuf = new Buffer(sliceLen, undefined, true)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
return newBuf
}
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0)
throw new RangeError('offset is not uint')
if (offset + ext > length)
throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUInt8 = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readInt8 = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80))
return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function (offset, noAssert) {
if (!noAssert)
checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
if (value > max || value < min) throw new TypeError('value is out of bounds')
if (offset + ext > buf.length) throw new TypeError('index out of range')
}
Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = value
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else objectWriteUInt16(this, value, offset, true)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else objectWriteUInt16(this, value, offset, false)
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = value
} else objectWriteUInt32(this, value, offset, true)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else objectWriteUInt32(this, value, offset, false)
return offset + 4
}
Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = value
return offset + 1
}
Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
} else objectWriteUInt16(this, value, offset, true)
return offset + 2
}
Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = value
} else objectWriteUInt16(this, value, offset, false)
return offset + 2
}
Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = value
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else objectWriteUInt32(this, value, offset, true)
return offset + 4
}
Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert)
checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = value
} else objectWriteUInt32(this, value, offset, false)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (value > max || value < min) throw new TypeError('value is out of bounds')
if (offset + ext > buf.length) throw new TypeError('index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert)
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert)
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function (target, target_start, start, end) {
var source = this
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (!target_start) target_start = 0
// Copy 0 bytes; we're done
if (end === start) return
if (target.length === 0 || source.length === 0) return
// Fatal error conditions
if (end < start) throw new TypeError('sourceEnd < sourceStart')
if (target_start < 0 || target_start >= target.length)
throw new TypeError('targetStart out of bounds')
if (start < 0 || start >= source.length) throw new TypeError('sourceStart out of bounds')
if (end < 0 || end > source.length) throw new TypeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length)
end = this.length
if (target.length - target_start < end - start)
end = target.length - target_start + start
var len = end - start
if (len < 100 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
}
// fill(value, start=0, end=buffer.length)
Buffer.prototype.fill = function (value, start, end) {
if (!value) value = 0
if (!start) start = 0
if (!end) end = this.length
if (end < start) throw new TypeError('end < start')
// Fill 0 bytes; we're done
if (end === start) return
if (this.length === 0) return
if (start < 0 || start >= this.length) throw new TypeError('start out of bounds')
if (end < 0 || end > this.length) throw new TypeError('end out of bounds')
var i
if (typeof value === 'number') {
for (i = start; i < end; i++) {
this[i] = value
}
} else {
var bytes = utf8ToBytes(value.toString())
var len = bytes.length
for (i = start; i < end; i++) {
this[i] = bytes[i % len]
}
}
return this
}
/**
* Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
* Added in Node 0.12. Only available in browsers that support ArrayBuffer.
*/
Buffer.prototype.toArrayBuffer = function () {
if (typeof Uint8Array !== 'undefined') {
if (Buffer.TYPED_ARRAY_SUPPORT) {
return (new Buffer(this)).buffer
} else {
var buf = new Uint8Array(this.length)
for (var i = 0, len = buf.length; i < len; i += 1) {
buf[i] = this[i]
}
return buf.buffer
}
} else {
throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
}
}
// HELPER FUNCTIONS
// ================
var BP = Buffer.prototype
/**
* Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
*/
Buffer._augment = function (arr) {
arr._isBuffer = true
// save reference to original Uint8Array get/set methods before overwriting
arr._get = arr.get
arr._set = arr.set
// deprecated, will be removed in node 0.13+
arr.get = BP.get
arr.set = BP.set
arr.write = BP.write
arr.toString = BP.toString
arr.toLocaleString = BP.toString
arr.toJSON = BP.toJSON
arr.equals = BP.equals
arr.compare = BP.compare
arr.copy = BP.copy
arr.slice = BP.slice
arr.readUInt8 = BP.readUInt8
arr.readUInt16LE = BP.readUInt16LE
arr.readUInt16BE = BP.readUInt16BE
arr.readUInt32LE = BP.readUInt32LE
arr.readUInt32BE = BP.readUInt32BE
arr.readInt8 = BP.readInt8
arr.readInt16LE = BP.readInt16LE
arr.readInt16BE = BP.readInt16BE
arr.readInt32LE = BP.readInt32LE
arr.readInt32BE = BP.readInt32BE
arr.readFloatLE = BP.readFloatLE
arr.readFloatBE = BP.readFloatBE
arr.readDoubleLE = BP.readDoubleLE
arr.readDoubleBE = BP.readDoubleBE
arr.writeUInt8 = BP.writeUInt8
arr.writeUInt16LE = BP.writeUInt16LE
arr.writeUInt16BE = BP.writeUInt16BE
arr.writeUInt32LE = BP.writeUInt32LE
arr.writeUInt32BE = BP.writeUInt32BE
arr.writeInt8 = BP.writeInt8
arr.writeInt16LE = BP.writeInt16LE
arr.writeInt16BE = BP.writeInt16BE
arr.writeInt32LE = BP.writeInt32LE
arr.writeInt32BE = BP.writeInt32BE
arr.writeFloatLE = BP.writeFloatLE
arr.writeFloatBE = BP.writeFloatBE
arr.writeDoubleLE = BP.writeDoubleLE
arr.writeDoubleBE = BP.writeDoubleBE
arr.fill = BP.fill
arr.inspect = BP.inspect
arr.toArrayBuffer = BP.toArrayBuffer
return arr
}
var INVALID_BASE64_RE = /[^+\/0-9A-z]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
var b = str.charCodeAt(i)
if (b <= 0x7F) {
byteArray.push(b)
} else {
var start = i
if (b >= 0xD800 && b <= 0xDFFF) i++
var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
for (var j = 0; j < h.length; j++) {
byteArray.push(parseInt(h[j], 16))
}
}
}
return byteArray
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(str)
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length))
break
dst[i + offset] = src[i]
}
return i
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":2,"ieee754":3,"is-array":4}],2:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS)
return 62 // '+'
if (code === SLASH)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len = b64.length
placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length
var L = 0
function push (v) {
arr[L++] = v
}
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
push((tmp & 0xFF0000) >> 16)
push((tmp & 0xFF00) >> 8)
push(tmp & 0xFF)
}
if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
push(tmp & 0xFF)
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
push((tmp >> 8) & 0xFF)
push(tmp & 0xFF)
}
return arr
}
function uint8ToBase64 (uint8) {
var i,
extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
output = "",
temp, length
function encode (num) {
return lookup.charAt(num)
}
function tripletToBase64 (num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
}
// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output += tripletToBase64(temp)
}
// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1]
output += encode(temp >> 2)
output += encode((temp << 4) & 0x3F)
output += '=='
break
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
output += encode(temp >> 10)
output += encode((temp >> 4) & 0x3F)
output += encode((temp << 2) & 0x3F)
output += '='
break
}
return output
}
exports.toByteArray = b64ToByteArray
exports.fromByteArray = uint8ToBase64
}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
},{}],3:[function(require,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
};
exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
};
},{}],4:[function(require,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],5:[function(require,module,exports){
ndarray = require( 'ndarray' );
},{"ndarray":6}],6:[function(require,module,exports){
(function (Buffer){
var iota = require("iota-array")
var hasTypedArrays = ((typeof Float64Array) !== "undefined")
var hasBuffer = ((typeof Buffer) !== "undefined")
function compare1st(a, b) {
return a[0] - b[0]
}
function order() {
var stride = this.stride
var terms = new Array(stride.length)
var i
for(i=0; i<terms.length; ++i) {
terms[i] = [Math.abs(stride[i]), i]
}
terms.sort(compare1st)
var result = new Array(terms.length)
for(i=0; i<result.length; ++i) {
result[i] = terms[i][1]
}
return result
}
function compileConstructor(dtype, dimension) {
var className = ["View", dimension, "d", dtype].join("")
if(dimension < 0) {
className = "View_Nil" + dtype
}
var useGetters = (dtype === "generic")
if(dimension === -1) {
//Special case for trivial arrays
var code =
"function "+className+"(a){this.data=a;};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return -1};\
proto.size=0;\
proto.dimension=-1;\
proto.shape=proto.stride=proto.order=[];\
proto.lo=proto.hi=proto.transpose=proto.step=\
function(){return new "+className+"(this.data);};\
proto.get=proto.set=function(){};\
proto.pick=function(){return null};\
return function construct_"+className+"(a){return new "+className+"(a);}"
var procedure = new Function(code)
return procedure()
} else if(dimension === 0) {
//Special case for 0d arrays
var code =
"function "+className+"(a,d) {\
this.data = a;\
this.offset = d\
};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return this.offset};\
proto.dimension=0;\
proto.size=1;\
proto.shape=\
proto.stride=\
proto.order=[];\
proto.lo=\
proto.hi=\
proto.transpose=\
proto.step=function "+className+"_copy() {\
return new "+className+"(this.data,this.offset)\
};\
proto.pick=function "+className+"_pick(){\
return TrivialArray(this.data);\
};\
proto.valueOf=proto.get=function "+className+"_get(){\
return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+
"};\
proto.set=function "+className+"_set(v){\
return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\
};\
return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}"
var procedure = new Function("TrivialArray", code)
return procedure(CACHED_CONSTRUCTORS[dtype][0])
}
var code = ["'use strict'"]
//Create constructor for view
var indices = iota(dimension)
var args = indices.map(function(i) { return "i"+i })
var index_str = "this.offset+" + indices.map(function(i) {
return "this.stride[" + i + "]*i" + i
}).join("+")
var shapeArg = indices.map(function(i) {
return "b"+i
}).join(",")
var strideArg = indices.map(function(i) {
return "c"+i
}).join(",")
code.push(
"function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a",
"this.shape=[" + shapeArg + "]",
"this.stride=[" + strideArg + "]",
"this.offset=d|0}",
"var proto="+className+".prototype",
"proto.dtype='"+dtype+"'",
"proto.dimension="+dimension)
//view.size:
code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\
return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"),
"}})")
//view.order:
if(dimension === 1) {
code.push("proto.order=[0]")
} else {
code.push("Object.defineProperty(proto,'order',{get:")
if(dimension < 4) {
code.push("function "+className+"_order(){")
if(dimension === 2) {
code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})")
} else if(dimension === 3) {
code.push(
"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\
if(s0>s1){\
if(s1>s2){\
return [2,1,0];\
}else if(s0>s2){\
return [1,2,0];\
}else{\
return [1,0,2];\
}\
}else if(s0>s2){\
return [2,0,1];\
}else if(s2>s1){\
return [0,1,2];\
}else{\
return [0,2,1];\
}}})")
}
} else {
code.push("ORDER})")
}
}
//view.set(i0, ..., v):
code.push(
"proto.set=function "+className+"_set("+args.join(",")+",v){")
if(useGetters) {
code.push("return this.data.set("+index_str+",v)}")
} else {
code.push("return this.data["+index_str+"]=v}")
}
//view.get(i0, ...):
code.push("proto.get=function "+className+"_get("+args.join(",")+"){")
if(useGetters) {
code.push("return this.data.get("+index_str+")}")
} else {
code.push("return this.data["+index_str+"]}")
}
//view.index:
code.push(
"proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}")
//view.hi():
code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
indices.map(function(i) {
return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("")
}).join(",")+","+
indices.map(function(i) {
return "this.stride["+i + "]"
}).join(",")+",this.offset)}")
//view.lo():
var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" })
var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" })
code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","))
for(var i=0; i<dimension; ++i) {
code.push(
"if(typeof i"+i+"==='number'&&i"+i+">=0){\
d=i"+i+"|0;\
b+=c"+i+"*d;\
a"+i+"-=d}")
}
code.push("return new "+className+"(this.data,"+
indices.map(function(i) {
return "a"+i
}).join(",")+","+
indices.map(function(i) {
return "c"+i
}).join(",")+",b)}")
//view.step():
code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
indices.map(function(i) {
return "a"+i+"=this.shape["+i+"]"
}).join(",")+","+
indices.map(function(i) {
return "b"+i+"=this.stride["+i+"]"
}).join(",")+",c=this.offset,d=0,ceil=Math.ceil")
for(var i=0; i<dimension; ++i) {
code.push(
"if(typeof i"+i+"==='number'){\
d=i"+i+"|0;\
if(d<0){\
c+=b"+i+"*(a"+i+"-1);\
a"+i+"=ceil(-a"+i+"/d)\
}else{\
a"+i+"=ceil(a"+i+"/d)\
}\
b"+i+"*=d\
}")
}
code.push("return new "+className+"(this.data,"+
indices.map(function(i) {
return "a" + i
}).join(",")+","+
indices.map(function(i) {
return "b" + i
}).join(",")+",c)}")
//view.transpose():
var tShape = new Array(dimension)
var tStride = new Array(dimension)
for(var i=0; i<dimension; ++i) {
tShape[i] = "a[i"+i+"]"
tStride[i] = "b[i"+i+"]"
}
code.push("proto.transpose=function "+className+"_transpose("+args+"){"+
args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"),
"var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}")
//view.pick():
code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset")
for(var i=0; i<dimension; ++i) {
code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}")
}
code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}")
//Add return statement
code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
indices.map(function(i) {
return "shape["+i+"]"
}).join(",")+","+
indices.map(function(i) {
return "stride["+i+"]"
}).join(",")+",offset)}")
//Compile procedure
var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"))
return procedure(CACHED_CONSTRUCTORS[dtype], order)
}
function arrayDType(data) {
if(hasBuffer) {
if(Buffer.isBuffer(data)) {
return "buffer"
}
}
if(hasTypedArrays) {
switch(Object.prototype.toString.call(data)) {
case "[object Float64Array]":
return "float64"
case "[object Float32Array]":
return "float32"
case "[object Int8Array]":
return "int8"
case "[object Int16Array]":
return "int16"
case "[object Int32Array]":
return "int32"
case "[object Uint8Array]":
return "uint8"
case "[object Uint16Array]":
return "uint16"
case "[object Uint32Array]":
return "uint32"
case "[object Uint8ClampedArray]":
return "uint8_clamped"
}
}
if(Array.isArray(data)) {
return "array"
}
return "generic"
}
var CACHED_CONSTRUCTORS = {
"float32":[],
"float64":[],
"int8":[],
"int16":[],
"int32":[],
"uint8":[],
"uint16":[],
"uint32":[],
"array":[],
"uint8_clamped":[],
"buffer":[],
"generic":[]
}
;(function() {
for(var id in CACHED_CONSTRUCTORS) {
CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))
}
});
function wrappedNDArrayCtor(data, shape, stride, offset) {
if(data === undefined) {
var ctor = CACHED_CONSTRUCTORS.array[0]
return ctor([])
} else if(typeof data === "number") {
data = [data]
}
if(shape === undefined) {
shape = [ data.length ]
}
var d = shape.length
if(stride === undefined) {
stride = new Array(d)
for(var i=d-1, sz=1; i>=0; --i) {
stride[i] = sz
sz *= shape[i]
}
}
if(offset === undefined) {
offset = 0
for(var i=0; i<d; ++i) {
if(stride[i] < 0) {
offset -= (shape[i]-1)*stride[i]
}
}
}
var dtype = arrayDType(data)
var ctor_list = CACHED_CONSTRUCTORS[dtype]
while(ctor_list.length <= d+1) {
ctor_list.push(compileConstructor(dtype, ctor_list.length-1))
}
var ctor = ctor_list[d+1]
return ctor(data, shape, stride, offset)
}
module.exports = wrappedNDArrayCtor
}).call(this,require("buffer").Buffer)
},{"buffer":1,"iota-array":7}],7:[function(require,module,exports){
"use strict"
function iota(n) {
var result = new Array(n)
for(var i=0; i<n; ++i) {
result[i] = i
}
return result
}
module.exports = iota
},{}]},{},[5]);
| NeoVand/networks3d | js/vendor/ndarray.js | JavaScript | mit | 45,269 |
define('lodash/internal/createWrapper', ['exports', 'lodash/internal/baseSetData', 'lodash/internal/createBindWrapper', 'lodash/internal/createHybridWrapper', 'lodash/internal/createPartialWrapper', 'lodash/internal/getData', 'lodash/internal/mergeData', 'lodash/internal/setData'], function (exports, _lodashInternalBaseSetData, _lodashInternalCreateBindWrapper, _lodashInternalCreateHybridWrapper, _lodashInternalCreatePartialWrapper, _lodashInternalGetData, _lodashInternalMergeData, _lodashInternalSetData) {
'use strict';
/** Used to compose bitmasks for wrapper metadata. */
var BIND_FLAG = 1,
BIND_KEY_FLAG = 2,
PARTIAL_FLAG = 32,
PARTIAL_RIGHT_FLAG = 64;
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of flags.
* The bitmask may be composed of the following flags:
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
length -= holders ? holders.length : 0;
if (bitmask & PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : (0, _lodashInternalGetData['default'])(func),
newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
if (data) {
(0, _lodashInternalMergeData['default'])(newData, data);
bitmask = newData[1];
arity = newData[9];
}
newData[9] = arity == null ? isBindKey ? 0 : func.length : nativeMax(arity - length, 0) || 0;
if (bitmask == BIND_FLAG) {
var result = (0, _lodashInternalCreateBindWrapper['default'])(newData[0], newData[2]);
} else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
result = _lodashInternalCreatePartialWrapper['default'].apply(undefined, newData);
} else {
result = _lodashInternalCreateHybridWrapper['default'].apply(undefined, newData);
}
var setter = data ? _lodashInternalBaseSetData['default'] : _lodashInternalSetData['default'];
return setter(result, newData);
}
exports['default'] = createWrapper;
}); | hoka-plus/p-01-web | tmp/babel-output_path-hOv4KMmE.tmp/lodash/internal/createWrapper.js | JavaScript | mit | 3,598 |
Clazz.declarePackage ("JU");
Clazz.load (["JU.V3"], "JU.Measure", ["java.lang.Float", "javajs.api.Interface", "JU.Lst", "$.P3", "$.P4", "$.Quat"], function () {
c$ = Clazz.declareType (JU, "Measure");
c$.computeAngle = Clazz.defineMethod (c$, "computeAngle",
function (pointA, pointB, pointC, vectorBA, vectorBC, asDegrees) {
vectorBA.sub2 (pointA, pointB);
vectorBC.sub2 (pointC, pointB);
var angle = vectorBA.angle (vectorBC);
return (asDegrees ? angle / 0.017453292 : angle);
}, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3,~B");
c$.computeAngleABC = Clazz.defineMethod (c$, "computeAngleABC",
function (pointA, pointB, pointC, asDegrees) {
var vectorBA = new JU.V3 ();
var vectorBC = new JU.V3 ();
return JU.Measure.computeAngle (pointA, pointB, pointC, vectorBA, vectorBC, asDegrees);
}, "JU.T3,JU.T3,JU.T3,~B");
c$.computeTorsion = Clazz.defineMethod (c$, "computeTorsion",
function (p1, p2, p3, p4, asDegrees) {
var ijx = p1.x - p2.x;
var ijy = p1.y - p2.y;
var ijz = p1.z - p2.z;
var kjx = p3.x - p2.x;
var kjy = p3.y - p2.y;
var kjz = p3.z - p2.z;
var klx = p3.x - p4.x;
var kly = p3.y - p4.y;
var klz = p3.z - p4.z;
var ax = ijy * kjz - ijz * kjy;
var ay = ijz * kjx - ijx * kjz;
var az = ijx * kjy - ijy * kjx;
var cx = kjy * klz - kjz * kly;
var cy = kjz * klx - kjx * klz;
var cz = kjx * kly - kjy * klx;
var ai2 = 1 / (ax * ax + ay * ay + az * az);
var ci2 = 1 / (cx * cx + cy * cy + cz * cz);
var ai = Math.sqrt (ai2);
var ci = Math.sqrt (ci2);
var denom = ai * ci;
var cross = ax * cx + ay * cy + az * cz;
var cosang = cross * denom;
if (cosang > 1) {
cosang = 1;
}if (cosang < -1) {
cosang = -1;
}var torsion = Math.acos (cosang);
var dot = ijx * cx + ijy * cy + ijz * cz;
var absDot = Math.abs (dot);
torsion = (dot / absDot > 0) ? torsion : -torsion;
return (asDegrees ? torsion / 0.017453292 : torsion);
}, "JU.T3,JU.T3,JU.T3,JU.T3,~B");
c$.computeHelicalAxis = Clazz.defineMethod (c$, "computeHelicalAxis",
function (a, b, dq) {
var vab = new JU.V3 ();
vab.sub2 (b, a);
var theta = dq.getTheta ();
var n = dq.getNormal ();
var v_dot_n = vab.dot (n);
if (Math.abs (v_dot_n) < 0.0001) v_dot_n = 0;
var va_prime_d = new JU.V3 ();
va_prime_d.cross (vab, n);
if (va_prime_d.dot (va_prime_d) != 0) va_prime_d.normalize ();
var vda = new JU.V3 ();
var vcb = JU.V3.newV (n);
if (v_dot_n == 0) v_dot_n = 1.4E-45;
vcb.scale (v_dot_n);
vda.sub2 (vcb, vab);
vda.scale (0.5);
va_prime_d.scale (theta == 0 ? 0 : (vda.length () / Math.tan (theta / 2 / 180 * 3.141592653589793)));
var r = JU.V3.newV (va_prime_d);
if (theta != 0) r.add (vda);
var pt_a_prime = JU.P3.newP (a);
pt_a_prime.sub (r);
if (v_dot_n != 1.4E-45) n.scale (v_dot_n);
var pt_b_prime = JU.P3.newP (pt_a_prime);
pt_b_prime.add (n);
theta = JU.Measure.computeTorsion (a, pt_a_prime, pt_b_prime, b, true);
if (Float.isNaN (theta) || r.length () < 0.0001) theta = dq.getThetaDirectedV (n);
var residuesPerTurn = Math.abs (theta == 0 ? 0 : 360 / theta);
var pitch = Math.abs (v_dot_n == 1.4E-45 ? 0 : n.length () * (theta == 0 ? 1 : 360 / theta));
return Clazz.newArray (-1, [pt_a_prime, n, r, JU.P3.new3 (theta, pitch, residuesPerTurn), pt_b_prime]);
}, "JU.P3,JU.P3,JU.Quat");
c$.getPlaneThroughPoints = Clazz.defineMethod (c$, "getPlaneThroughPoints",
function (pointA, pointB, pointC, vNorm, vAB, plane) {
var w = JU.Measure.getNormalThroughPoints (pointA, pointB, pointC, vNorm, vAB);
plane.set4 (vNorm.x, vNorm.y, vNorm.z, w);
return plane;
}, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3,JU.P4");
c$.getPlaneThroughPoint = Clazz.defineMethod (c$, "getPlaneThroughPoint",
function (pt, normal, plane) {
plane.set4 (normal.x, normal.y, normal.z, -normal.dot (pt));
}, "JU.T3,JU.V3,JU.P4");
c$.distanceToPlane = Clazz.defineMethod (c$, "distanceToPlane",
function (plane, pt) {
return (plane == null ? NaN : (plane.dot (pt) + plane.w) / Math.sqrt (plane.dot (plane)));
}, "JU.P4,JU.T3");
c$.directedDistanceToPlane = Clazz.defineMethod (c$, "directedDistanceToPlane",
function (pt, plane, ptref) {
var f = plane.dot (pt) + plane.w;
var f1 = plane.dot (ptref) + plane.w;
return Math.signum (f1) * f / Math.sqrt (plane.dot (plane));
}, "JU.P3,JU.P4,JU.P3");
c$.distanceToPlaneD = Clazz.defineMethod (c$, "distanceToPlaneD",
function (plane, d, pt) {
return (plane == null ? NaN : (plane.dot (pt) + plane.w) / d);
}, "JU.P4,~N,JU.P3");
c$.distanceToPlaneV = Clazz.defineMethod (c$, "distanceToPlaneV",
function (norm, w, pt) {
return (norm == null ? NaN : (norm.dot (pt) + w) / Math.sqrt (norm.dot (norm)));
}, "JU.V3,~N,JU.P3");
c$.calcNormalizedNormal = Clazz.defineMethod (c$, "calcNormalizedNormal",
function (pointA, pointB, pointC, vNormNorm, vAB) {
vAB.sub2 (pointB, pointA);
vNormNorm.sub2 (pointC, pointA);
vNormNorm.cross (vAB, vNormNorm);
vNormNorm.normalize ();
}, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3");
c$.getDirectedNormalThroughPoints = Clazz.defineMethod (c$, "getDirectedNormalThroughPoints",
function (pointA, pointB, pointC, ptRef, vNorm, vAB) {
var nd = JU.Measure.getNormalThroughPoints (pointA, pointB, pointC, vNorm, vAB);
if (ptRef != null) {
var pt0 = JU.P3.newP (pointA);
pt0.add (vNorm);
var d = pt0.distance (ptRef);
pt0.sub2 (pointA, vNorm);
if (d > pt0.distance (ptRef)) {
vNorm.scale (-1);
nd = -nd;
}}return nd;
}, "JU.T3,JU.T3,JU.T3,JU.T3,JU.V3,JU.V3");
c$.getNormalThroughPoints = Clazz.defineMethod (c$, "getNormalThroughPoints",
function (pointA, pointB, pointC, vNorm, vTemp) {
JU.Measure.calcNormalizedNormal (pointA, pointB, pointC, vNorm, vTemp);
vTemp.setT (pointA);
return -vTemp.dot (vNorm);
}, "JU.T3,JU.T3,JU.T3,JU.V3,JU.V3");
c$.getPlaneProjection = Clazz.defineMethod (c$, "getPlaneProjection",
function (pt, plane, ptProj, vNorm) {
var dist = JU.Measure.distanceToPlane (plane, pt);
vNorm.set (plane.x, plane.y, plane.z);
vNorm.normalize ();
vNorm.scale (-dist);
ptProj.add2 (pt, vNorm);
}, "JU.P3,JU.P4,JU.P3,JU.V3");
c$.getNormalFromCenter = Clazz.defineMethod (c$, "getNormalFromCenter",
function (ptCenter, ptA, ptB, ptC, isOutward, normal, vTemp) {
var d = JU.Measure.getNormalThroughPoints (ptA, ptB, ptC, normal, vTemp);
var isReversed = (JU.Measure.distanceToPlaneV (normal, d, ptCenter) > 0);
if (isReversed == isOutward) normal.scale (-1.0);
return !isReversed;
}, "JU.P3,JU.P3,JU.P3,JU.P3,~B,JU.V3,JU.V3");
c$.getNormalToLine = Clazz.defineMethod (c$, "getNormalToLine",
function (pointA, pointB, vNormNorm) {
vNormNorm.sub2 (pointA, pointB);
vNormNorm.cross (vNormNorm, JU.Measure.axisY);
vNormNorm.normalize ();
if (Float.isNaN (vNormNorm.x)) vNormNorm.set (1, 0, 0);
}, "JU.P3,JU.P3,JU.V3");
c$.getBisectingPlane = Clazz.defineMethod (c$, "getBisectingPlane",
function (pointA, vAB, ptTemp, vTemp, plane) {
ptTemp.scaleAdd2 (0.5, vAB, pointA);
vTemp.setT (vAB);
vTemp.normalize ();
JU.Measure.getPlaneThroughPoint (ptTemp, vTemp, plane);
}, "JU.P3,JU.V3,JU.T3,JU.V3,JU.P4");
c$.projectOntoAxis = Clazz.defineMethod (c$, "projectOntoAxis",
function (point, axisA, axisUnitVector, vectorProjection) {
vectorProjection.sub2 (point, axisA);
var projectedLength = vectorProjection.dot (axisUnitVector);
point.scaleAdd2 (projectedLength, axisUnitVector, axisA);
vectorProjection.sub2 (point, axisA);
}, "JU.P3,JU.P3,JU.V3,JU.V3");
c$.calcBestAxisThroughPoints = Clazz.defineMethod (c$, "calcBestAxisThroughPoints",
function (points, axisA, axisUnitVector, vectorProjection, nTriesMax) {
var nPoints = points.length;
axisA.setT (points[0]);
axisUnitVector.sub2 (points[nPoints - 1], axisA);
axisUnitVector.normalize ();
JU.Measure.calcAveragePointN (points, nPoints, axisA);
var nTries = 0;
while (nTries++ < nTriesMax && JU.Measure.findAxis (points, nPoints, axisA, axisUnitVector, vectorProjection) > 0.001) {
}
var tempA = JU.P3.newP (points[0]);
JU.Measure.projectOntoAxis (tempA, axisA, axisUnitVector, vectorProjection);
axisA.setT (tempA);
}, "~A,JU.P3,JU.V3,JU.V3,~N");
c$.findAxis = Clazz.defineMethod (c$, "findAxis",
function (points, nPoints, axisA, axisUnitVector, vectorProjection) {
var sumXiYi = new JU.V3 ();
var vTemp = new JU.V3 ();
var pt = new JU.P3 ();
var ptProj = new JU.P3 ();
var a = JU.V3.newV (axisUnitVector);
var sum_Xi2 = 0;
for (var i = nPoints; --i >= 0; ) {
pt.setT (points[i]);
ptProj.setT (pt);
JU.Measure.projectOntoAxis (ptProj, axisA, axisUnitVector, vectorProjection);
vTemp.sub2 (pt, ptProj);
vTemp.cross (vectorProjection, vTemp);
sumXiYi.add (vTemp);
sum_Xi2 += vectorProjection.lengthSquared ();
}
var m = JU.V3.newV (sumXiYi);
m.scale (1 / sum_Xi2);
vTemp.cross (m, axisUnitVector);
axisUnitVector.add (vTemp);
axisUnitVector.normalize ();
vTemp.sub2 (axisUnitVector, a);
return vTemp.length ();
}, "~A,~N,JU.P3,JU.V3,JU.V3");
c$.calcAveragePoint = Clazz.defineMethod (c$, "calcAveragePoint",
function (pointA, pointB, pointC) {
pointC.set ((pointA.x + pointB.x) / 2, (pointA.y + pointB.y) / 2, (pointA.z + pointB.z) / 2);
}, "JU.P3,JU.P3,JU.P3");
c$.calcAveragePointN = Clazz.defineMethod (c$, "calcAveragePointN",
function (points, nPoints, averagePoint) {
averagePoint.setT (points[0]);
for (var i = 1; i < nPoints; i++) averagePoint.add (points[i]);
averagePoint.scale (1 / nPoints);
}, "~A,~N,JU.P3");
c$.transformPoints = Clazz.defineMethod (c$, "transformPoints",
function (vPts, m4, center) {
var v = new JU.Lst ();
for (var i = 0; i < vPts.size (); i++) {
var pt = JU.P3.newP (vPts.get (i));
pt.sub (center);
m4.rotTrans (pt);
pt.add (center);
v.addLast (pt);
}
return v;
}, "JU.Lst,JU.M4,JU.P3");
c$.isInTetrahedron = Clazz.defineMethod (c$, "isInTetrahedron",
function (pt, ptA, ptB, ptC, ptD, plane, vTemp, vTemp2, fullyEnclosed) {
var b = (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptC, ptD, ptA, vTemp, vTemp2, plane), pt) >= 0);
if (b != (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptA, ptD, ptB, vTemp, vTemp2, plane), pt) >= 0)) return false;
if (b != (JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptB, ptD, ptC, vTemp, vTemp2, plane), pt) >= 0)) return false;
var d = JU.Measure.distanceToPlane (JU.Measure.getPlaneThroughPoints (ptA, ptB, ptC, vTemp, vTemp2, plane), pt);
if (fullyEnclosed) return (b == (d >= 0));
var d1 = JU.Measure.distanceToPlane (plane, ptD);
return d1 * d <= 0 || Math.abs (d1) > Math.abs (d);
}, "JU.P3,JU.P3,JU.P3,JU.P3,JU.P3,JU.P4,JU.V3,JU.V3,~B");
c$.getIntersectionPP = Clazz.defineMethod (c$, "getIntersectionPP",
function (plane1, plane2) {
var a1 = plane1.x;
var b1 = plane1.y;
var c1 = plane1.z;
var d1 = plane1.w;
var a2 = plane2.x;
var b2 = plane2.y;
var c2 = plane2.z;
var d2 = plane2.w;
var norm1 = JU.V3.new3 (a1, b1, c1);
var norm2 = JU.V3.new3 (a2, b2, c2);
var nxn = new JU.V3 ();
nxn.cross (norm1, norm2);
var ax = Math.abs (nxn.x);
var ay = Math.abs (nxn.y);
var az = Math.abs (nxn.z);
var x;
var y;
var z;
var diff;
var type = (ax > ay ? (ax > az ? 1 : 3) : ay > az ? 2 : 3);
switch (type) {
case 1:
x = 0;
diff = (b1 * c2 - b2 * c1);
if (Math.abs (diff) < 0.01) return null;
y = (c1 * d2 - c2 * d1) / diff;
z = (b2 * d1 - d2 * b1) / diff;
break;
case 2:
diff = (a1 * c2 - a2 * c1);
if (Math.abs (diff) < 0.01) return null;
x = (c1 * d2 - c2 * d1) / diff;
y = 0;
z = (a2 * d1 - d2 * a1) / diff;
break;
case 3:
default:
diff = (a1 * b2 - a2 * b1);
if (Math.abs (diff) < 0.01) return null;
x = (b1 * d2 - b2 * d1) / diff;
y = (a2 * d1 - d2 * a1) / diff;
z = 0;
}
var list = new JU.Lst ();
list.addLast (JU.P3.new3 (x, y, z));
nxn.normalize ();
list.addLast (nxn);
return list;
}, "JU.P4,JU.P4");
c$.getIntersection = Clazz.defineMethod (c$, "getIntersection",
function (pt1, v, plane, ptRet, tempNorm, vTemp) {
JU.Measure.getPlaneProjection (pt1, plane, ptRet, tempNorm);
tempNorm.set (plane.x, plane.y, plane.z);
tempNorm.normalize ();
if (v == null) v = JU.V3.newV (tempNorm);
var l_dot_n = v.dot (tempNorm);
if (Math.abs (l_dot_n) < 0.01) return null;
vTemp.sub2 (ptRet, pt1);
ptRet.scaleAdd2 (vTemp.dot (tempNorm) / l_dot_n, v, pt1);
return ptRet;
}, "JU.P3,JU.V3,JU.P4,JU.P3,JU.V3,JU.V3");
c$.calculateQuaternionRotation = Clazz.defineMethod (c$, "calculateQuaternionRotation",
function (centerAndPoints, retStddev) {
retStddev[1] = NaN;
var q = new JU.Quat ();
if (centerAndPoints[0].length == 1 || centerAndPoints[0].length != centerAndPoints[1].length) return q;
var n = centerAndPoints[0].length - 1;
if (n < 2) return q;
var Sxx = 0;
var Sxy = 0;
var Sxz = 0;
var Syx = 0;
var Syy = 0;
var Syz = 0;
var Szx = 0;
var Szy = 0;
var Szz = 0;
var ptA = new JU.P3 ();
var ptB = new JU.P3 ();
for (var i = n + 1; --i >= 1; ) {
var aij = centerAndPoints[0][i];
var bij = centerAndPoints[1][i];
ptA.sub2 (aij, centerAndPoints[0][0]);
ptB.sub2 (bij, centerAndPoints[0][1]);
Sxx += ptA.x * ptB.x;
Sxy += ptA.x * ptB.y;
Sxz += ptA.x * ptB.z;
Syx += ptA.y * ptB.x;
Syy += ptA.y * ptB.y;
Syz += ptA.y * ptB.z;
Szx += ptA.z * ptB.x;
Szy += ptA.z * ptB.y;
Szz += ptA.z * ptB.z;
}
retStddev[0] = JU.Measure.getRmsd (centerAndPoints, q);
var N = Clazz.newDoubleArray (4, 4, 0);
N[0][0] = Sxx + Syy + Szz;
N[0][1] = N[1][0] = Syz - Szy;
N[0][2] = N[2][0] = Szx - Sxz;
N[0][3] = N[3][0] = Sxy - Syx;
N[1][1] = Sxx - Syy - Szz;
N[1][2] = N[2][1] = Sxy + Syx;
N[1][3] = N[3][1] = Szx + Sxz;
N[2][2] = -Sxx + Syy - Szz;
N[2][3] = N[3][2] = Syz + Szy;
N[3][3] = -Sxx - Syy + Szz;
var v = (javajs.api.Interface.getInterface ("JU.Eigen")).setM (N).getEigenvectorsFloatTransposed ()[3];
q = JU.Quat.newP4 (JU.P4.new4 (v[1], v[2], v[3], v[0]));
retStddev[1] = JU.Measure.getRmsd (centerAndPoints, q);
return q;
}, "~A,~A");
c$.getTransformMatrix4 = Clazz.defineMethod (c$, "getTransformMatrix4",
function (ptsA, ptsB, m, centerA) {
var cptsA = JU.Measure.getCenterAndPoints (ptsA);
var cptsB = JU.Measure.getCenterAndPoints (ptsB);
var retStddev = Clazz.newFloatArray (2, 0);
var q = JU.Measure.calculateQuaternionRotation ( Clazz.newArray (-1, [cptsA, cptsB]), retStddev);
var r = q.getMatrix ();
if (centerA == null) r.rotate (cptsA[0]);
else centerA.setT (cptsA[0]);
var t = JU.V3.newVsub (cptsB[0], cptsA[0]);
m.setMV (r, t);
return retStddev[1];
}, "JU.Lst,JU.Lst,JU.M4,JU.P3");
c$.getCenterAndPoints = Clazz.defineMethod (c$, "getCenterAndPoints",
function (vPts) {
var n = vPts.size ();
var pts = new Array (n + 1);
pts[0] = new JU.P3 ();
if (n > 0) {
for (var i = 0; i < n; i++) {
pts[0].add (pts[i + 1] = vPts.get (i));
}
pts[0].scale (1 / n);
}return pts;
}, "JU.Lst");
c$.getRmsd = Clazz.defineMethod (c$, "getRmsd",
function (centerAndPoints, q) {
var sum2 = 0;
var ptsA = centerAndPoints[0];
var ptsB = centerAndPoints[1];
var cA = ptsA[0];
var cB = ptsB[0];
var n = ptsA.length - 1;
var ptAnew = new JU.P3 ();
for (var i = n + 1; --i >= 1; ) {
ptAnew.sub2 (ptsA[i], cA);
q.transform2 (ptAnew, ptAnew).add (cB);
sum2 += ptAnew.distanceSquared (ptsB[i]);
}
return Math.sqrt (sum2 / n);
}, "~A,JU.Quat");
Clazz.defineStatics (c$,
"radiansPerDegree", (0.017453292519943295));
c$.axisY = c$.prototype.axisY = JU.V3.new3 (0, 1, 0);
});
| sandipde/Interactive-Sketchmap-Visualizer | static/jmol/j2s/JU/Measure.js | JavaScript | mit | 15,234 |
import Ember from 'ember';
export default Ember.Object.extend({
content: {},
contentLength: 0,
add: function(obj) {
var id = this.generateId();
this.get('content')[id] = obj;
this.incrementProperty("contentLength");
return id;
},
getObj: function(key) {
var res = this.get('content')[key];
if (!res) {
throw "no obj for key "+key;
}
return res;
},
generateId: function() {
var num = Math.random() * 1000000000000.0;
num = parseInt(num);
num = ""+num;
return num;
},
keys: function() {
var res = [];
for (var key in this.get('content')) {
res.push(key);
}
return Ember.A(res);
},
lengthBinding: "contentLength"
}); | bdvholmes/ember-drag-drop | app/models/obj-hash.js | JavaScript | mit | 717 |
require('ember-runtime/core');
require('ember-runtime/system/core_object');
require('ember-runtime/mixins/mutable_enumerable');
require('ember-runtime/mixins/copyable');
require('ember-runtime/mixins/freezable');
/**
@module ember
@submodule ember-runtime
*/
var get = Ember.get, set = Ember.set, guidFor = Ember.guidFor, isNone = Ember.isNone, fmt = Ember.String.fmt;
/**
An unordered collection of objects.
A Set works a bit like an array except that its items are not ordered. You
can create a set to efficiently test for membership for an object. You can
also iterate through a set just like an array, even accessing objects by
index, however there is no guarantee as to their order.
All Sets are observable via the Enumerable Observer API - which works
on any enumerable object including both Sets and Arrays.
## Creating a Set
You can create a set like you would most objects using
`new Ember.Set()`. Most new sets you create will be empty, but you can
also initialize the set with some content by passing an array or other
enumerable of objects to the constructor.
Finally, you can pass in an existing set and the set will be copied. You
can also create a copy of a set by calling `Ember.Set#copy()`.
```javascript
// creates a new empty set
var foundNames = new Ember.Set();
// creates a set with four names in it.
var names = new Ember.Set(["Charles", "Tom", "Juan", "Alex"]); // :P
// creates a copy of the names set.
var namesCopy = new Ember.Set(names);
// same as above.
var anotherNamesCopy = names.copy();
```
## Adding/Removing Objects
You generally add or remove objects from a set using `add()` or
`remove()`. You can add any type of object including primitives such as
numbers, strings, and booleans.
Unlike arrays, objects can only exist one time in a set. If you call `add()`
on a set with the same object multiple times, the object will only be added
once. Likewise, calling `remove()` with the same object multiple times will
remove the object the first time and have no effect on future calls until
you add the object to the set again.
NOTE: You cannot add/remove `null` or `undefined` to a set. Any attempt to do
so will be ignored.
In addition to add/remove you can also call `push()`/`pop()`. Push behaves
just like `add()` but `pop()`, unlike `remove()` will pick an arbitrary
object, remove it and return it. This is a good way to use a set as a job
queue when you don't care which order the jobs are executed in.
## Testing for an Object
To test for an object's presence in a set you simply call
`Ember.Set#contains()`.
## Observing changes
When using `Ember.Set`, you can observe the `"[]"` property to be
alerted whenever the content changes. You can also add an enumerable
observer to the set to be notified of specific objects that are added and
removed from the set. See `Ember.Enumerable` for more information on
enumerables.
This is often unhelpful. If you are filtering sets of objects, for instance,
it is very inefficient to re-filter all of the items each time the set
changes. It would be better if you could just adjust the filtered set based
on what was changed on the original set. The same issue applies to merging
sets, as well.
## Other Methods
`Ember.Set` primary implements other mixin APIs. For a complete reference
on the methods you will use with `Ember.Set`, please consult these mixins.
The most useful ones will be `Ember.Enumerable` and
`Ember.MutableEnumerable` which implement most of the common iterator
methods you are used to on Array.
Note that you can also use the `Ember.Copyable` and `Ember.Freezable`
APIs on `Ember.Set` as well. Once a set is frozen it can no longer be
modified. The benefit of this is that when you call `frozenCopy()` on it,
Ember will avoid making copies of the set. This allows you to write
code that can know with certainty when the underlying set data will or
will not be modified.
@class Set
@namespace Ember
@extends Ember.CoreObject
@uses Ember.MutableEnumerable
@uses Ember.Copyable
@uses Ember.Freezable
@since Ember 0.9
*/
Ember.Set = Ember.CoreObject.extend(Ember.MutableEnumerable, Ember.Copyable, Ember.Freezable,
/** @scope Ember.Set.prototype */ {
// ..........................................................
// IMPLEMENT ENUMERABLE APIS
//
/**
This property will change as the number of objects in the set changes.
@property length
@type number
@default 0
*/
length: 0,
/**
Clears the set. This is useful if you want to reuse an existing set
without having to recreate it.
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.length; // 3
colors.clear();
colors.length; // 0
```
@method clear
@return {Ember.Set} An empty Set
*/
clear: function() {
if (this.isFrozen) { throw new Error(Ember.FROZEN_ERROR); }
var len = get(this, 'length');
if (len === 0) { return this; }
var guid;
this.enumerableContentWillChange(len, 0);
Ember.propertyWillChange(this, 'firstObject');
Ember.propertyWillChange(this, 'lastObject');
for (var i=0; i < len; i++){
guid = guidFor(this[i]);
delete this[guid];
delete this[i];
}
set(this, 'length', 0);
Ember.propertyDidChange(this, 'firstObject');
Ember.propertyDidChange(this, 'lastObject');
this.enumerableContentDidChange(len, 0);
return this;
},
/**
Returns true if the passed object is also an enumerable that contains the
same objects as the receiver.
```javascript
var colors = ["red", "green", "blue"],
same_colors = new Ember.Set(colors);
same_colors.isEqual(colors); // true
same_colors.isEqual(["purple", "brown"]); // false
```
@method isEqual
@param {Ember.Set} obj the other object.
@return {Boolean}
*/
isEqual: function(obj) {
// fail fast
if (!Ember.Enumerable.detect(obj)) return false;
var loc = get(this, 'length');
if (get(obj, 'length') !== loc) return false;
while(--loc >= 0) {
if (!obj.contains(this[loc])) return false;
}
return true;
},
/**
Adds an object to the set. Only non-`null` objects can be added to a set
and those can only be added once. If the object is already in the set or
the passed value is null this method will have no effect.
This is an alias for `Ember.MutableEnumerable.addObject()`.
```javascript
var colors = new Ember.Set();
colors.add("blue"); // ["blue"]
colors.add("blue"); // ["blue"]
colors.add("red"); // ["blue", "red"]
colors.add(null); // ["blue", "red"]
colors.add(undefined); // ["blue", "red"]
```
@method add
@param {Object} obj The object to add.
@return {Ember.Set} The set itself.
*/
add: Ember.aliasMethod('addObject'),
/**
Removes the object from the set if it is found. If you pass a `null` value
or an object that is already not in the set, this method will have no
effect. This is an alias for `Ember.MutableEnumerable.removeObject()`.
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.remove("red"); // ["blue", "green"]
colors.remove("purple"); // ["blue", "green"]
colors.remove(null); // ["blue", "green"]
```
@method remove
@param {Object} obj The object to remove
@return {Ember.Set} The set itself.
*/
remove: Ember.aliasMethod('removeObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
```javascript
var colors = new Ember.Set(["green", "blue"]);
colors.pop(); // "blue"
colors.pop(); // "green"
colors.pop(); // null
```
@method pop
@return {Object} The removed object from the set or null.
*/
pop: function() {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
var obj = this.length > 0 ? this[this.length-1] : null;
this.remove(obj);
return obj;
},
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias for `Ember.MutableEnumerable.addObject()`.
```javascript
var colors = new Ember.Set();
colors.push("red"); // ["red"]
colors.push("green"); // ["red", "green"]
colors.push("blue"); // ["red", "green", "blue"]
```
@method push
@return {Ember.Set} The set itself.
*/
push: Ember.aliasMethod('addObject'),
/**
Removes the last element from the set and returns it, or `null` if it's empty.
This is an alias for `Ember.Set.pop()`.
```javascript
var colors = new Ember.Set(["green", "blue"]);
colors.shift(); // "blue"
colors.shift(); // "green"
colors.shift(); // null
```
@method shift
@return {Object} The removed object from the set or null.
*/
shift: Ember.aliasMethod('pop'),
/**
Inserts the given object on to the end of the set. It returns
the set itself.
This is an alias of `Ember.Set.push()`
```javascript
var colors = new Ember.Set();
colors.unshift("red"); // ["red"]
colors.unshift("green"); // ["red", "green"]
colors.unshift("blue"); // ["red", "green", "blue"]
```
@method unshift
@return {Ember.Set} The set itself.
*/
unshift: Ember.aliasMethod('push'),
/**
Adds each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.addObjects()`
```javascript
var colors = new Ember.Set();
colors.addEach(["red", "green", "blue"]); // ["red", "green", "blue"]
```
@method addEach
@param {Ember.Enumerable} objects the objects to add.
@return {Ember.Set} The set itself.
*/
addEach: Ember.aliasMethod('addObjects'),
/**
Removes each object in the passed enumerable to the set.
This is an alias of `Ember.MutableEnumerable.removeObjects()`
```javascript
var colors = new Ember.Set(["red", "green", "blue"]);
colors.removeEach(["red", "blue"]); // ["green"]
```
@method removeEach
@param {Ember.Enumerable} objects the objects to remove.
@return {Ember.Set} The set itself.
*/
removeEach: Ember.aliasMethod('removeObjects'),
// ..........................................................
// PRIVATE ENUMERABLE SUPPORT
//
init: function(items) {
this._super();
if (items) this.addObjects(items);
},
// implement Ember.Enumerable
nextObject: function(idx) {
return this[idx];
},
// more optimized version
firstObject: Ember.computed(function() {
return this.length > 0 ? this[0] : undefined;
}),
// more optimized version
lastObject: Ember.computed(function() {
return this.length > 0 ? this[this.length-1] : undefined;
}),
// implements Ember.MutableEnumerable
addObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
added ;
if (idx>=0 && idx<len && (this[idx] === obj)) return this; // added
added = [obj];
this.enumerableContentWillChange(null, added);
Ember.propertyWillChange(this, 'lastObject');
len = get(this, 'length');
this[guid] = len;
this[len] = obj;
set(this, 'length', len+1);
Ember.propertyDidChange(this, 'lastObject');
this.enumerableContentDidChange(null, added);
return this;
},
// implements Ember.MutableEnumerable
removeObject: function(obj) {
if (get(this, 'isFrozen')) throw new Error(Ember.FROZEN_ERROR);
if (isNone(obj)) return this; // nothing to do
var guid = guidFor(obj),
idx = this[guid],
len = get(this, 'length'),
isFirst = idx === 0,
isLast = idx === len-1,
last, removed;
if (idx>=0 && idx<len && (this[idx] === obj)) {
removed = [obj];
this.enumerableContentWillChange(removed, null);
if (isFirst) { Ember.propertyWillChange(this, 'firstObject'); }
if (isLast) { Ember.propertyWillChange(this, 'lastObject'); }
// swap items - basically move the item to the end so it can be removed
if (idx < len-1) {
last = this[len-1];
this[idx] = last;
this[guidFor(last)] = idx;
}
delete this[guid];
delete this[len-1];
set(this, 'length', len-1);
if (isFirst) { Ember.propertyDidChange(this, 'firstObject'); }
if (isLast) { Ember.propertyDidChange(this, 'lastObject'); }
this.enumerableContentDidChange(removed, null);
}
return this;
},
// optimized version
contains: function(obj) {
return this[guidFor(obj)]>=0;
},
copy: function() {
var C = this.constructor, ret = new C(), loc = get(this, 'length');
set(ret, 'length', loc);
while(--loc>=0) {
ret[loc] = this[loc];
ret[guidFor(this[loc])] = loc;
}
return ret;
},
toString: function() {
var len = this.length, idx, array = [];
for(idx = 0; idx < len; idx++) {
array[idx] = this[idx];
}
return fmt("Ember.Set<%@>", [array.join(',')]);
}
});
| teddyzeenny/ember.js | packages/ember-runtime/lib/system/set.js | JavaScript | mit | 13,316 |
/*!
* Bootstrap-select v1.13.2 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2018 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: 'Нищо избрано',
noneResultsText: 'Няма резултат за {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? "{0} избран елемент" : "{0} избрани елемента";
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Лимита е достигнат ({n} елемент максимум)' : 'Лимита е достигнат ({n} елемента максимум)',
(numGroup == 1) ? 'Груповия лимит е достигнат ({n} елемент максимум)' : 'Груповия лимит е достигнат ({n} елемента максимум)'
];
},
selectAllText: 'Избери всички',
deselectAllText: 'Размаркирай всички',
multipleSeparator: ', '
};
})(jQuery);
}));
| extend1994/cdnjs | ajax/libs/bootstrap-select/1.13.2/js/i18n/defaults-bg_BG.js | JavaScript | mit | 1,838 |
/*! PopUp Free - v4.7.11
* https://wordpress.org/plugins/wordpress-popup/
* Copyright (c) 2015; * Licensed GPLv2+ */
/*global window:false */
/*global document:false */
/*global wp:false */
/*global wpmUi:false */
/*global ace:false */
/**
* Admin Javascript functions for PopUp
*/
jQuery(function init_admin() {
// ----- POPUP EDITOR --
// Disables dragging of metaboxes: Users cannot change the metabox order.
function disable_metabox_dragging() {
var boxes = jQuery( '.meta-box-sortables' ),
handles = jQuery( '.postbox .hndle' );
if ( ! boxes.length ) { return; }
boxes.sortable({
disabled: true
});
handles.css( 'cursor', 'pointer' );
}
// Keeps the submitdiv always visible, even when scrolling.
function scrolling_submitdiv() {
var scroll_top,
top_offset,
submitdiv = jQuery( '#submitdiv' ),
postbody = jQuery( '#post-body' ),
body = jQuery( 'body' ),
padding = 20;
if ( ! submitdiv.length ) { return; }
top_offset = submitdiv.position().top;
var small_make_sticky = function() {
if ( ! body.hasClass( 'sticky-submit' ) ) {
body.addClass( 'sticky-submit' );
submitdiv.css({ 'marginTop': 0 } );
submitdiv.find( '.sticky-actions' ).show();
submitdiv.find( '.non-sticky' ).hide();
}
};
var small_remove_sticky = function() {
if ( body.hasClass( 'sticky-submit' ) ) {
body.removeClass( 'sticky-submit' );
submitdiv.find( '.sticky-actions' ).hide();
submitdiv.find( '.non-sticky' ).show();
}
};
jQuery( window ).resize(function() {
var is_small = jQuery( window ).width() <= 850;
if ( is_small ) {
if ( ! body.hasClass( 'po-small' ) ) {
body.addClass( 'po-small' );
}
} else {
if ( body.hasClass( 'po-small' ) ) {
body.removeClass( 'po-small' );
small_remove_sticky();
}
}
}).scroll(function(){
if ( postbody.hasClass( 'columns-1' ) || body.hasClass( 'po-small' ) ) {
// 1-column view:
// The div stays as sticky toolbar when scrolling down.
scroll_top = jQuery( window ).scrollTop() - top_offset;
if ( scroll_top > 0 ) {
small_make_sticky();
} else {
small_remove_sticky();
}
} else {
// 2-column view:
// The div scrolls with the page to stay visible.
scroll_top = jQuery( window ).scrollTop() - top_offset + padding;
if ( scroll_top > 0 ) {
submitdiv.css({ 'marginTop': scroll_top } );
} else {
submitdiv.css({ 'marginTop': 0 } );
}
}
});
window.setTimeout( function() {
jQuery( window ).trigger( 'scroll' );
}, 100 );
}
// Change the text-fields to colorpicker fields.
function init_colorpicker() {
var inp = jQuery( '.colorpicker' );
if ( ! inp.length || 'function' !== typeof inp.wpColorPicker ) { return; }
var maybe_hide_picker = function maybe_hide_picker( ev ) {
var el = jQuery( ev.target ),
cp = el.closest( '.wp-picker-container' ),
me = cp.find( '.colorpicker' ),
do_hide = jQuery( '.colorpicker' );
if ( cp.length ) {
do_hide = do_hide.not( me );
}
do_hide.each( function() {
var picker = jQuery( this ),
wrap = picker.closest( '.wp-picker-container' );
picker.iris( 'hide' );
// As mentioned: Color picker does not like to hide properly...
picker.hide();
wrap.find( '.wp-picker-clear').addClass( 'hidden' );
wrap.find( '.wp-picker-open').removeClass( 'wp-picker-open' );
});
};
inp.wpColorPicker();
// Don't ask why the handler is hooked three times ;-)
// The Color picker is a bit bitchy when it comes to hiding it...
jQuery( document ).on( 'mousedown', maybe_hide_picker );
jQuery( document ).on( 'click', maybe_hide_picker );
jQuery( document ).on( 'mouseup', maybe_hide_picker );
}
// Add event handlers for editor UI controls (i.e. to checkboxes)
function init_edit_controls() {
var chk_colors = jQuery( '#po-custom-colors' ),
chk_size = jQuery( '#po-custom-size' ),
opt_display = jQuery( '[name=po_display]' ),
chk_can_hide = jQuery( '#po-can-hide' ),
chk_close_hides = jQuery( '#po-close-hides' );
if ( ! chk_colors.length ) { return; }
var toggle_section = function toggle_section() {
var group,
me = jQuery( this ),
sel = me.data( 'toggle' ),
sect = jQuery( sel ),
group_or = me.data( 'or' ),
group_and = me.data( 'and' ),
is_active = false;
if ( group_or ) {
group = jQuery( group_or );
is_active = ( group.filter( ':checked' ).length > 0);
} else if ( group_and ) {
group = jQuery( group_and );
is_active = ( group.length === group.filter( ':checked' ).length );
} else {
is_active = me.prop( 'checked' );
}
if ( is_active ) {
sect.removeClass( 'inactive' );
sect.find( 'input,select,textarea,a' )
.prop( 'readonly', false )
.removeClass( 'disabled' );
} else {
sect.addClass( 'inactive' );
// Do NOT set .prop('disabled', true)!
sect.find( 'input,select,textarea,a' )
.prop( 'readonly', true )
.addClass( 'disabled' );
}
sect.addClass( 'inactive-anim' );
};
var toggle_section_group = function toggle_section_group() {
var me = jQuery( this ),
name = me.attr( 'name' ),
group = jQuery( '[name="' + name + '"]' );
group.each(function() {
toggle_section.call( this );
});
};
var create_sliders = function create_sliders() {
jQuery( '.slider' ).each(function() {
var me = jQuery( this ),
wrap = me.closest( '.slider-wrap' ),
inp_base = me.data( 'input' ),
inp_min = wrap.find( inp_base + 'min' ),
inp_max = wrap.find( inp_base + 'max' ),
min_input = wrap.find( '.slider-min-input' ),
min_ignore = wrap.find( '.slider-min-ignore' ),
max_input = wrap.find( '.slider-max-input' ),
max_ignore = wrap.find( '.slider-max-ignore' ),
min = me.data( 'min' ),
max = me.data( 'max' );
if ( isNaN( min ) ) { min = 0; }
if ( isNaN( max ) ) { max = 9999; }
inp_min.prop( 'readonly', true );
inp_max.prop( 'readonly', true );
var update_fields = function update_fields( val1, val2 ) {
inp_min.val( val1 );
inp_max.val( val2 );
if ( val1 === min ) {
min_input.hide();
min_ignore.show();
} else {
min_input.show();
min_ignore.hide();
}
if ( val2 === max ) {
max_input.hide();
max_ignore.show();
} else {
max_input.show();
max_ignore.hide();
}
};
me.slider({
range: true,
min: min,
max: max,
values: [ inp_min.val(), inp_max.val() ],
slide: function( event, ui ) {
update_fields( ui.values[0], ui.values[1] );
}
});
update_fields( inp_min.val(), inp_max.val() );
});
};
chk_colors.click( toggle_section );
chk_size.click( toggle_section );
chk_can_hide.click( toggle_section );
chk_close_hides.click( toggle_section );
opt_display.click( toggle_section_group );
toggle_section.call( chk_colors );
toggle_section.call( chk_size );
toggle_section.call( chk_can_hide );
toggle_section.call( chk_close_hides );
opt_display.each(function() {
toggle_section.call( jQuery( this ) );
});
create_sliders();
}
// Toggle rules on/off
function init_rules() {
var all_rules = jQuery( '#meta-rules .all-rules' ),
active_rules = jQuery( '#meta-rules .active-rules' );
if ( ! all_rules.length ) { return; }
var toggle_checkbox = function toggle_checkbox( ev ) {
var me = jQuery( ev.target ),
chk = me.find( 'input.wpmui-toggle-checkbox' );
if ( me.closest( '.wpmui-toggle' ).length ) { return; }
if ( me.hasClass( 'inactive' ) ) { return false; }
chk.trigger( 'click' );
};
var toggle_rule = function toggle_rule() {
var me = jQuery( this ),
rule = me.closest( '.rule' ),
sel = me.data( 'form' ),
form = active_rules.find( sel ),
active = me.prop( 'checked' );
if ( active ) {
rule.removeClass( 'off' ).addClass( 'on' );
form.removeClass( 'off' ).addClass( 'on open' );
} else {
rule.removeClass( 'on' ).addClass( 'off' );
form.removeClass( 'on' ).addClass( 'off' );
}
exclude_rules( me, active );
};
var exclude_rules = function exclude_rules( checkbox, active ) {
var ind, excl1, excl2,
excl = checkbox.data( 'exclude' ),
keys = (excl ? excl.split( ',' ) : []);
// Exclude other rules.
for ( ind = keys.length - 1; ind >= 0; ind -= 1 ) {
excl1 = all_rules.find( '.rule-' + keys[ ind ] );
excl2 = active_rules.find( '#po-rule-' + keys[ ind ] );
if ( excl1.hasClass( 'on' ) ) {
// Rule is active; possibly migrated from old PopUp editor
// so we cannot disable the rule now...
continue;
}
excl1.prop( 'disabled', active );
if ( active ) {
excl1.addClass( 'inactive off' ).removeClass( 'on' );
excl2.addClass( 'off' ).removeClass( 'on' );
} else {
excl1.removeClass( 'inactive off' );
}
}
};
var toggle_form = function toggle_form() {
var me = jQuery( this ),
form = me.closest( '.rule' );
form.toggleClass( 'open' );
};
all_rules.find( 'input.wpmui-toggle-checkbox' ).click( toggle_rule );
all_rules.find( '.rule' ).click( toggle_checkbox );
active_rules.on( 'click', '.rule-title,.rule-toggle', toggle_form );
// Exclude rules.
all_rules.find( '.rule.on input.wpmui-toggle-checkbox' ).each(function() {
exclude_rules( jQuery( this ), true );
});
jQuery( '.init-loading' ).removeClass( 'wpmui-loading' );
}
// Hook up the "Featured image" button.
function init_image() {
// Uploading files
var box = jQuery( '.content-image' ),
btn = box.find( '.add_image' ),
dropzone = box.find( '.featured-img' ),
reset = box.find( '.reset' ),
inp = box.find( '.po-image' ),
img_preview = box.find( '.img-preview' ),
img_label = box.find( '.lbl-empty' ),
img_pos = box.find( '.img-pos' ),
file_frame;
// User selected an image (via drag-drop or file_frame)
var use_image = function use_image( url ) {
inp.val( url );
img_preview.attr( 'src', url ).show();
img_label.hide();
img_pos.show();
dropzone.addClass( 'has-image' );
};
// User selected an image (via drag-drop or file_frame)
var reset_image = function reset_image( url ) {
inp.val( '' );
img_preview.attr( 'src', '' ).hide();
img_label.show();
img_pos.hide();
dropzone.removeClass( 'has-image' );
};
// User clicks on the "Add image" button.
var select_clicked = function select_clicked( ev ) {
ev.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: btn.attr( 'data-title' ),
button: {
text: btn.attr( 'data-button' )
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
var attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
use_image( attachment.url );
});
// Finally, open the modal
file_frame.open();
};
var select_pos = function select_pos( ev ) {
var me = jQuery( this );
img_pos.find( '.option' ).removeClass( 'selected' );
me.addClass( 'selected' );
};
btn.on( 'click', select_clicked );
reset.on( 'click', reset_image );
img_pos.on( 'click', '.option', select_pos );
}
// ----- POPUP LIST --
// Adds custom bulk actions to the popup list.
function bulk_actions() {
var key,
ba1 = jQuery( 'select[name="action"] '),
ba2 = jQuery( 'select[name="action2"] ');
if ( ! ba1.length || 'object' !== typeof window.po_bulk ) { return; }
for ( key in window.po_bulk ) {
jQuery( '<option>' )
.val( key )
.text( window.po_bulk[key] )
.appendTo( ba1 )
.clone()
.appendTo( ba2 );
}
}
// Makes the post-list sortable (to change popup-order)
function sortable_list() {
var table = jQuery( 'table.posts' ),
tbody = table.find( '#the-list' );
if ( ! tbody.length ) { return; }
var ajax_done = function ajax_done( resp, okay ) {
table.removeClass( 'wpmui-loading' );
if ( okay ) {
for ( var id in resp ) {
if ( ! resp.hasOwnProperty( id ) ) { continue; }
tbody.find( '#post-' + id + ' .the-pos' ).text( resp[id] );
}
}
};
var save_order = function save_order( event, ui ) {
var i,
rows = tbody.find('tr'),
order = [];
for ( i = 0; i < rows.length; i+= 1 ) {
order.push( jQuery( rows[i] ).attr( 'id' ) );
}
table.addClass( 'wpmui-loading' );
wpmUi.ajax( null, 'po-ajax' )
.data({
'do': 'order',
'order': order
})
.ondone( ajax_done )
.load_json();
};
tbody.sortable({
placeholder: 'ui-sortable-placeholder',
axis: 'y',
handle: '.column-po_order',
helper: 'clone',
opacity: 0.75,
update: save_order
});
tbody.disableSelection();
}
// Shows a preview of the current PopUp.
function init_preview() {
var doc = jQuery( document ),
body = jQuery( '#wpcontent' );
var handle_list_click = function handle_list_click( ev ) {
var me = jQuery( this ),
po_id = me.data( 'id' );
ev.preventDefault();
if ( undefined === window.inc_popup ) { return false; }
body.addClass( 'wpmui-loading' );
window.inc_popup.load( po_id );
return false;
};
var handle_editor_click = function handle_editor_click( ev ) {
var data,
me = jQuery( this ),
form = jQuery( '#post' ),
ajax = wpmUi.ajax();
ev.preventDefault();
if ( undefined === window.inc_popup ) { return false; }
data = ajax.extract_data( form );
body.addClass( 'wpmui-loading' );
window.inc_popup.load( 0, data );
return false;
};
var show_popup = function show_popup( ev, popup ) {
body.removeClass( 'wpmui-loading' );
popup.init();
};
doc.on( 'click', '.posts .po-preview', handle_list_click );
doc.on( 'click', '#post .preview', handle_editor_click );
doc.on( 'popup-initialized', show_popup );
}
// Initialize the CSS editor
function init_css_editor() {
jQuery('.po_css_editor').each(function(){
var editor = ace.edit(this.id);
jQuery(this).data('editor', editor);
editor.setTheme('ace/theme/chrome');
editor.getSession().setMode('ace/mode/css');
editor.getSession().setUseWrapMode(true);
editor.getSession().setUseWrapMode(false);
});
jQuery('.po_css_editor').each(function(){
var self = this,
input = jQuery( jQuery(this).data('input') );
jQuery(this).data('editor').getSession().on('change', function () {
input.val( jQuery(self).data('editor').getSession().getValue() );
});
});
}
if ( ! jQuery( 'body.post-type-inc_popup' ).length ) {
return;
}
// EDITOR
if ( jQuery( 'body.post-php' ).length || jQuery( 'body.post-new-php' ).length ) {
disable_metabox_dragging();
scrolling_submitdiv();
init_colorpicker();
init_edit_controls();
init_rules();
init_preview();
init_image();
init_css_editor();
wpmUi.upgrade_multiselect();
}
// POPUP LIST
else if ( jQuery( 'body.edit-php' ).length ) {
sortable_list();
bulk_actions();
init_preview();
}
}); | iAPT/producerroom | wp-content/plugins/wordpress-popup/js/popup-admin.js | JavaScript | gpl-2.0 | 15,341 |
goog.provide('ol.source.ImageVector');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.vec.Mat4');
goog.require('ol.dom');
goog.require('ol.extent');
goog.require('ol.render.canvas.ReplayGroup');
goog.require('ol.renderer.vector');
goog.require('ol.source.ImageCanvas');
goog.require('ol.source.Vector');
goog.require('ol.style.Style');
goog.require('ol.vec.Mat4');
/**
* @classdesc
* An image source whose images are canvas elements into which vector features
* read from a vector source (`ol.source.Vector`) are drawn. An
* `ol.source.ImageVector` object is to be used as the `source` of an image
* layer (`ol.layer.Image`). Image layers are rotated, scaled, and translated,
* as opposed to being re-rendered, during animations and interactions. So, like
* any other image layer, an image layer configured with an
* `ol.source.ImageVector` will exhibit this behaviour. This is in contrast to a
* vector layer, where vector features are re-drawn during animations and
* interactions.
*
* @constructor
* @extends {ol.source.ImageCanvas}
* @param {olx.source.ImageVectorOptions} options Options.
* @api
*/
ol.source.ImageVector = function(options) {
/**
* @private
* @type {ol.source.Vector}
*/
this.source_ = options.source;
/**
* @private
* @type {!goog.vec.Mat4.Number}
*/
this.transform_ = goog.vec.Mat4.createNumber();
/**
* @private
* @type {CanvasRenderingContext2D}
*/
this.canvasContext_ = ol.dom.createCanvasContext2D();
/**
* @private
* @type {ol.Size}
*/
this.canvasSize_ = [0, 0];
/**
* @private
* @type {ol.render.canvas.ReplayGroup}
*/
this.replayGroup_ = null;
goog.base(this, {
attributions: options.attributions,
canvasFunction: goog.bind(this.canvasFunctionInternal_, this),
logo: options.logo,
projection: options.projection,
ratio: options.ratio,
resolutions: options.resolutions,
state: this.source_.getState()
});
/**
* User provided style.
* @type {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
* @private
*/
this.style_ = null;
/**
* Style function for use within the library.
* @type {ol.style.StyleFunction|undefined}
* @private
*/
this.styleFunction_ = undefined;
this.setStyle(options.style);
goog.events.listen(this.source_, goog.events.EventType.CHANGE,
this.handleSourceChange_, undefined, this);
};
goog.inherits(ol.source.ImageVector, ol.source.ImageCanvas);
/**
* @param {ol.Extent} extent Extent.
* @param {number} resolution Resolution.
* @param {number} pixelRatio Pixel ratio.
* @param {ol.Size} size Size.
* @param {ol.proj.Projection} projection Projection;
* @return {HTMLCanvasElement} Canvas element.
* @private
*/
ol.source.ImageVector.prototype.canvasFunctionInternal_ =
function(extent, resolution, pixelRatio, size, projection) {
var replayGroup = new ol.render.canvas.ReplayGroup(
ol.renderer.vector.getTolerance(resolution, pixelRatio), extent,
resolution);
this.source_.loadFeatures(extent, resolution, projection);
var loading = false;
this.source_.forEachFeatureInExtentAtResolution(extent, resolution,
/**
* @param {ol.Feature} feature Feature.
*/
function(feature) {
loading = loading ||
this.renderFeature_(feature, resolution, pixelRatio, replayGroup);
}, this);
replayGroup.finish();
if (loading) {
return null;
}
if (this.canvasSize_[0] != size[0] || this.canvasSize_[1] != size[1]) {
this.canvasContext_.canvas.width = size[0];
this.canvasContext_.canvas.height = size[1];
this.canvasSize_[0] = size[0];
this.canvasSize_[1] = size[1];
} else {
this.canvasContext_.clearRect(0, 0, size[0], size[1]);
}
var transform = this.getTransform_(ol.extent.getCenter(extent),
resolution, pixelRatio, size);
replayGroup.replay(this.canvasContext_, pixelRatio, transform, 0, {});
this.replayGroup_ = replayGroup;
return this.canvasContext_.canvas;
};
/**
* @inheritDoc
*/
ol.source.ImageVector.prototype.forEachFeatureAtCoordinate = function(
coordinate, resolution, rotation, skippedFeatureUids, callback) {
if (goog.isNull(this.replayGroup_)) {
return undefined;
} else {
/** @type {Object.<string, boolean>} */
var features = {};
return this.replayGroup_.forEachFeatureAtCoordinate(
coordinate, resolution, 0, skippedFeatureUids,
/**
* @param {ol.Feature} feature Feature.
* @return {?} Callback result.
*/
function(feature) {
goog.asserts.assert(goog.isDef(feature));
var key = goog.getUid(feature).toString();
if (!(key in features)) {
features[key] = true;
return callback(feature);
}
});
}
};
/**
* Get a reference to the wrapped source.
* @return {ol.source.Vector} Source.
* @api
*/
ol.source.ImageVector.prototype.getSource = function() {
return this.source_;
};
/**
* Get the style for features. This returns whatever was passed to the `style`
* option at construction or to the `setStyle` method.
* @return {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction}
* Layer style.
* @api stable
*/
ol.source.ImageVector.prototype.getStyle = function() {
return this.style_;
};
/**
* Get the style function.
* @return {ol.style.StyleFunction|undefined} Layer style function.
* @api stable
*/
ol.source.ImageVector.prototype.getStyleFunction = function() {
return this.styleFunction_;
};
/**
* @param {ol.Coordinate} center Center.
* @param {number} resolution Resolution.
* @param {number} pixelRatio Pixel ratio.
* @param {ol.Size} size Size.
* @return {!goog.vec.Mat4.Number} Transform.
* @private
*/
ol.source.ImageVector.prototype.getTransform_ =
function(center, resolution, pixelRatio, size) {
return ol.vec.Mat4.makeTransform2D(this.transform_,
size[0] / 2, size[1] / 2,
pixelRatio / resolution, -pixelRatio / resolution,
0,
-center[0], -center[1]);
};
/**
* Handle changes in image style state.
* @param {goog.events.Event} event Image style change event.
* @private
*/
ol.source.ImageVector.prototype.handleImageChange_ =
function(event) {
this.changed();
};
/**
* @private
*/
ol.source.ImageVector.prototype.handleSourceChange_ = function() {
// setState will trigger a CHANGE event, so we always rely
// change events by calling setState.
this.setState(this.source_.getState());
};
/**
* @param {ol.Feature} feature Feature.
* @param {number} resolution Resolution.
* @param {number} pixelRatio Pixel ratio.
* @param {ol.render.canvas.ReplayGroup} replayGroup Replay group.
* @return {boolean} `true` if an image is loading.
* @private
*/
ol.source.ImageVector.prototype.renderFeature_ =
function(feature, resolution, pixelRatio, replayGroup) {
var styles;
if (goog.isDef(feature.getStyleFunction())) {
styles = feature.getStyleFunction().call(feature, resolution);
} else if (goog.isDef(this.styleFunction_)) {
styles = this.styleFunction_(feature, resolution);
}
if (!goog.isDefAndNotNull(styles)) {
return false;
}
var i, ii, loading = false;
for (i = 0, ii = styles.length; i < ii; ++i) {
loading = ol.renderer.vector.renderFeature(
replayGroup, feature, styles[i],
ol.renderer.vector.getSquaredTolerance(resolution, pixelRatio),
this.handleImageChange_, this) || loading;
}
return loading;
};
/**
* Set the style for features. This can be a single style object, an array
* of styles, or a function that takes a feature and resolution and returns
* an array of styles. If it is `undefined` the default style is used. If
* it is `null` the layer has no style (a `null` style), so only features
* that have their own styles will be rendered in the layer. See
* {@link ol.style} for information on the default style.
* @param {ol.style.Style|Array.<ol.style.Style>|ol.style.StyleFunction|undefined}
* style Layer style.
* @api stable
*/
ol.source.ImageVector.prototype.setStyle = function(style) {
this.style_ = goog.isDef(style) ? style : ol.style.defaultStyleFunction;
this.styleFunction_ = goog.isNull(style) ?
undefined : ol.style.createStyleFunction(this.style_);
this.changed();
};
| henriquespedro/Autarquia-Livre | vendor/openlayers/ol/ol/source/imagevectorsource.js | JavaScript | gpl-2.0 | 8,407 |
// methods (functions of objects)
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions
// http://www.ecma-international.org/ecma-262/6.0/#sec-method-definitions
var Obj = {
myMethod(a, b) {
},
*myGenerator(a, b) {
}
}
| masatake/ctags | Units/parser-javascript.r/js-methods.d/input.js | JavaScript | gpl-2.0 | 284 |
/*!
* jQuery Form Plugin
* version: 3.33.0-2013.05.02
* @requires jQuery v1.5 or later
* Copyright (c) 2013 M. Alsup
* Examples and documentation at: http://malsup.com/jquery/form/
* Project repository: https://github.com/malsup/form
* Dual licensed under the MIT and GPL licenses.
* https://github.com/malsup/form#copyright-and-license
*/
/*global ActiveXObject */
;(function($) {
"use strict";
/*
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form. For example,
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault(); // <-- important
$(this).ajaxSubmit({
target: '#output'
});
});
});
Use ajaxForm when you want the plugin to manage all the event binding
for you. For example,
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});
You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
form does not have to exist when you invoke ajaxForm:
$('#myForm').ajaxForm({
delegation: true,
target: '#output'
});
When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.
*/
/**
* Feature detection
*/
var feature = {};
feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
feature.formdata = window.FormData !== undefined;
var hasProp = !!$.fn.prop;
// attr2 uses prop when it can but checks the return type for
// an expected string. this accounts for the case where a form
// contains inputs with names like "action" or "method"; in those
// cases "prop" returns the element
$.fn.attr2 = function() {
if ( ! hasProp )
return this.attr.apply(this, arguments);
var val = this.prop.apply(this, arguments);
if ( ( val && val.jquery ) || typeof val === 'string' )
return val;
return this.attr.apply(this, arguments);
};
/**
* ajaxSubmit() provides a mechanism for immediately submitting
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
/*jshint scripturl:true */
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
var method, action, url, $form = this;
if (typeof options == 'function') {
options = { success: options };
}
method = this.attr2('method');
action = this.attr2('action');
url = (typeof action === 'string') ? $.trim(action) : '';
url = url || window.location.href || '';
if (url) {
// clean url (don't include hash vaue)
url = (url.match(/^([^#]+)/)||[])[1];
}
options = $.extend(true, {
url: url,
success: $.ajaxSettings.success,
type: method || 'GET',
iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
}, options);
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var traditional = options.traditional;
if ( traditional === undefined ) {
traditional = $.ajaxSettings.traditional;
}
var elements = [];
var qx, a = this.formToArray(options.semantic, elements);
if (options.data) {
options.extraData = options.data;
qx = $.param(options.data, traditional);
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a, traditional);
if (qx) {
q = ( q ? (q + '&' + qx) : qx );
}
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else {
options.data = q; // data is the query string for 'post'
}
var callbacks = [];
if (options.resetForm) {
callbacks.push(function() { $form.resetForm(); });
}
if (options.clearForm) {
callbacks.push(function() { $form.clearForm(options.includeHidden); });
}
// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
var fn = options.replaceTarget ? 'replaceWith' : 'html';
$(options.target)[fn](data).each(oldSuccess, arguments);
});
}
else if (options.success) {
callbacks.push(options.success);
}
options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
var context = options.context || this ; // jQuery 1.4+ supports scope context
for (var i=0, max=callbacks.length; i < max; i++) {
callbacks[i].apply(context, [data, status, xhr || $form, $form]);
}
};
if (options.error) {
var oldError = options.error;
options.error = function(xhr, status, error) {
var context = options.context || this;
oldError.apply(context, [xhr, status, error, $form]);
};
}
if (options.complete) {
var oldComplete = options.complete;
options.complete = function(xhr, status) {
var context = options.context || this;
oldComplete.apply(context, [xhr, status, $form]);
};
}
// are there files to upload?
// [value] (issue #113), also see comment:
// https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
var fileInputs = $('input[type=file]:enabled[value!=""]', this);
var hasFileInputs = fileInputs.length > 0;
var mp = 'multipart/form-data';
var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
var fileAPI = feature.fileapi && feature.formdata;
log("fileAPI :" + fileAPI);
var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
var jqxhr;
// options.iframe allows user to force iframe mode
// 06-NOV-09: now defaulting to iframe mode if file input is detected
if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if (options.closeKeepAlive) {
$.get(options.closeKeepAlive, function() {
jqxhr = fileUploadIframe(a);
});
}
else {
jqxhr = fileUploadIframe(a);
}
}
else if ((hasFileInputs || multipart) && fileAPI) {
jqxhr = fileUploadXhr(a);
}
else {
jqxhr = $.ajax(options);
}
$form.removeData('jqxhr').data('jqxhr', jqxhr);
// clear element array
for (var k=0; k < elements.length; k++)
elements[k] = null;
// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;
// utility fn for deep serialization
function deepSerialize(extraData){
var serialized = $.param(extraData).split('&');
var len = serialized.length;
var result = [];
var i, part;
for (i=0; i < len; i++) {
// #252; undo param space replacement
serialized[i] = serialized[i].replace(/\+/g,' ');
part = serialized[i].split('=');
// #278; use array instead of object storage, favoring array serializations
result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
}
return result;
}
// XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
function fileUploadXhr(a) {
var formdata = new FormData();
for (var i=0; i < a.length; i++) {
formdata.append(a[i].name, a[i].value);
}
if (options.extraData) {
var serializedData = deepSerialize(options.extraData);
for (i=0; i < serializedData.length; i++)
if (serializedData[i])
formdata.append(serializedData[i][0], serializedData[i][1]);
}
options.data = null;
var s = $.extend(true, {}, $.ajaxSettings, options, {
contentType: false,
processData: false,
cache: false,
type: method || 'POST'
});
if (options.uploadProgress) {
// workaround because jqXHR does not expose upload property
s.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position; /*event.position is deprecated*/
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
}
s.data = null;
var beforeSend = s.beforeSend;
s.beforeSend = function(xhr, o) {
o.data = formdata;
if(beforeSend)
beforeSend.call(this, xhr, o);
};
return $.ajax(s);
}
// private function for handling file uploads (hat tip to YAHOO!)
function fileUploadIframe(a) {
var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
var deferred = $.Deferred();
if (a) {
// ensure that every serialized input is still enabled
for (i=0; i < elements.length; i++) {
el = $(elements[i]);
if ( hasProp )
el.prop('disabled', false);
else
el.removeAttr('disabled');
}
}
s = $.extend(true, {}, $.ajaxSettings, options);
s.context = s.context || s;
id = 'jqFormIO' + (new Date().getTime());
if (s.iframeTarget) {
$io = $(s.iframeTarget);
n = $io.attr2('name');
if (!n)
$io.attr2('name', id);
else
id = n;
}
else {
$io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
}
io = $io[0];
xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function(status) {
var e = (status === 'timeout' ? 'timeout' : 'aborted');
log('aborting upload... ' + e);
this.aborted = 1;
try { // #214, #257
if (io.contentWindow.document.execCommand) {
io.contentWindow.document.execCommand('Stop');
}
}
catch(ignore) {}
$io.attr('src', s.iframeSrc); // abort op in progress
xhr.error = e;
if (s.error)
s.error.call(s.context, xhr, e, status);
if (g)
$.event.trigger("ajaxError", [xhr, s, e]);
if (s.complete)
s.complete.call(s.context, xhr, e);
}
};
g = s.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && 0 === $.active++) {
$.event.trigger("ajaxStart");
}
if (g) {
$.event.trigger("ajaxSend", [xhr, s]);
}
if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
if (s.global) {
$.active--;
}
deferred.reject();
return deferred;
}
if (xhr.aborted) {
deferred.reject();
return deferred;
}
// add submitting element to data if we know it
sub = form.clk;
if (sub) {
n = sub.name;
if (n && !sub.disabled) {
s.extraData = s.extraData || {};
s.extraData[n] = sub.value;
if (sub.type == "image") {
s.extraData[n+'.x'] = form.clk_x;
s.extraData[n+'.y'] = form.clk_y;
}
}
}
var CLIENT_TIMEOUT_ABORT = 1;
var SERVER_ABORT = 2;
function getDoc(frame) {
/* it looks like contentWindow or contentDocument do not
* carry the protocol property in ie8, when running under ssl
* frame.document is the only valid response document, since
* the protocol is know but not on the other two objects. strange?
* "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
*/
var doc = null;
// IE8 cascading access check
try {
if (frame.contentWindow) {
doc = frame.contentWindow.document;
}
} catch(err) {
// IE8 access denied under ssl & missing protocol
log('cannot get iframe.contentWindow document: ' + err);
}
if (doc) { // successful getting content
return doc;
}
try { // simply checking may throw in ie8 under ssl or mismatched protocol
doc = frame.contentDocument ? frame.contentDocument : frame.document;
} catch(err) {
// last attempt
log('cannot get iframe.contentDocument: ' + err);
doc = frame.document;
}
return doc;
}
// Rails CSRF hack (thanks to Yvan Barthelemy)
var csrf_token = $('meta[name=csrf-token]').attr('content');
var csrf_param = $('meta[name=csrf-param]').attr('content');
if (csrf_param && csrf_token) {
s.extraData = s.extraData || {};
s.extraData[csrf_param] = csrf_token;
}
// take a breath so that pending repaints get some cpu time before the upload starts
function doSubmit() {
// make sure form attrs are set
var t = $form.attr2('target'), a = $form.attr2('action');
// update form attrs in IE friendly way
form.setAttribute('target',id);
if (!method) {
form.setAttribute('method', 'POST');
}
if (a != s.url) {
form.setAttribute('action', s.url);
}
// ie borks in some cases when setting encoding
if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
// support timout
if (s.timeout) {
timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
}
// look for server aborts
function checkState() {
try {
var state = getDoc(io).readyState;
log('state = ' + state);
if (state && state.toLowerCase() == 'uninitialized')
setTimeout(checkState,50);
}
catch(e) {
log('Server abort: ' , e, ' (', e.name, ')');
cb(SERVER_ABORT);
if (timeoutHandle)
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
}
// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (s.extraData) {
for (var n in s.extraData) {
if (s.extraData.hasOwnProperty(n)) {
// if using the $.param format that allows for multiple values with the same name
if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
extraInputs.push(
$('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
.appendTo(form)[0]);
} else {
extraInputs.push(
$('<input type="hidden" name="'+n+'">').val(s.extraData[n])
.appendTo(form)[0]);
}
}
}
}
if (!s.iframeTarget) {
// add iframe to doc and submit the form
$io.appendTo('body');
if (io.attachEvent)
io.attachEvent('onload', cb);
else
io.addEventListener('load', cb, false);
}
setTimeout(checkState,15);
try {
form.submit();
} catch(err) {
// just in case form has element with name/id of 'submit'
var submitFn = document.createElement('form').submit;
submitFn.apply(form);
}
}
finally {
// reset attrs and remove "extra" input elements
form.setAttribute('action',a);
if(t) {
form.setAttribute('target', t);
} else {
$form.removeAttr('target');
}
$(extraInputs).remove();
}
}
if (s.forceSync) {
doSubmit();
}
else {
setTimeout(doSubmit, 10); // this lets dom updates render
}
var data, doc, domCheckCount = 50, callbackProcessed;
function cb(e) {
if (xhr.aborted || callbackProcessed) {
return;
}
doc = getDoc(io);
if(!doc) {
log('cannot access response document');
e = SERVER_ABORT;
}
if (e === CLIENT_TIMEOUT_ABORT && xhr) {
xhr.abort('timeout');
deferred.reject(xhr, 'timeout');
return;
}
else if (e == SERVER_ABORT && xhr) {
xhr.abort('server abort');
deferred.reject(xhr, 'error', 'server abort');
return;
}
if (!doc || doc.location.href == s.iframeSrc) {
// response not received yet
if (!timedOut)
return;
}
if (io.detachEvent)
io.detachEvent('onload', cb);
else
io.removeEventListener('load', cb, false);
var status = 'success', errMsg;
try {
if (timedOut) {
throw 'timeout';
}
var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
log('isXml='+isXml);
if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
if (--domCheckCount) {
// in some browsers (Opera) the iframe DOM is not always traversable when
// the onload callback fires, so we loop a bit to accommodate
log('requeing onLoad callback, DOM not available');
setTimeout(cb, 250);
return;
}
// let this fall through because server response could be an empty document
//log('Could not access iframe DOM after mutiple tries.');
//throw 'DOMException: not available';
}
//log('response detected');
var docRoot = doc.body ? doc.body : doc.documentElement;
xhr.responseText = docRoot ? docRoot.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
if (isXml)
s.dataType = 'xml';
xhr.getResponseHeader = function(header){
var headers = {'content-type': s.dataType};
return headers[header];
};
// support for XHR 'status' & 'statusText' emulation :
if (docRoot) {
xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
}
var dt = (s.dataType || '').toLowerCase();
var scr = /(json|script|text)/.test(dt);
if (scr || s.textarea) {
// see if user embedded response in textarea
var ta = doc.getElementsByTagName('textarea')[0];
if (ta) {
xhr.responseText = ta.value;
// support for XHR 'status' & 'statusText' emulation :
xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
}
else if (scr) {
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
var b = doc.getElementsByTagName('body')[0];
if (pre) {
xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
}
else if (b) {
xhr.responseText = b.textContent ? b.textContent : b.innerText;
}
}
}
else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
xhr.responseXML = toXml(xhr.responseText);
}
try {
data = httpData(xhr, dt, s);
}
catch (err) {
status = 'parsererror';
xhr.error = errMsg = (err || status);
}
}
catch (err) {
log('error caught: ',err);
status = 'error';
xhr.error = errMsg = (err || status);
}
if (xhr.aborted) {
log('upload aborted');
status = null;
}
if (xhr.status) { // we've set xhr.status
status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (status === 'success') {
if (s.success)
s.success.call(s.context, data, 'success', xhr);
deferred.resolve(xhr.responseText, 'success', xhr);
if (g)
$.event.trigger("ajaxSuccess", [xhr, s]);
}
else if (status) {
if (errMsg === undefined)
errMsg = xhr.statusText;
if (s.error)
s.error.call(s.context, xhr, status, errMsg);
deferred.reject(xhr, 'error', errMsg);
if (g)
$.event.trigger("ajaxError", [xhr, s, errMsg]);
}
if (g)
$.event.trigger("ajaxComplete", [xhr, s]);
if (g && ! --$.active) {
$.event.trigger("ajaxStop");
}
if (s.complete)
s.complete.call(s.context, xhr, status);
callbackProcessed = true;
if (s.timeout)
clearTimeout(timeoutHandle);
// clean up
setTimeout(function() {
if (!s.iframeTarget)
$io.remove();
xhr.responseXML = null;
}, 100);
}
var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else {
doc = (new DOMParser()).parseFromString(s, 'text/xml');
}
return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
};
var parseJSON = $.parseJSON || function(s) {
/*jslint evil:true */
return window['eval']('(' + s + ')');
};
var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
var ct = xhr.getResponseHeader('content-type') || '',
xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if (xml && data.documentElement.nodeName === 'parsererror') {
if ($.error)
$.error('parsererror');
}
if (s && s.dataFilter) {
data = s.dataFilter(data, type);
}
if (typeof data === 'string') {
if (type === 'json' || !type && ct.indexOf('json') >= 0) {
data = parseJSON(data);
} else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
$.globalEval(data);
}
}
return data;
};
return deferred;
}
};
/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
* is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
* used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/
$.fn.ajaxForm = function(options) {
options = options || {};
options.delegation = options.delegation && $.isFunction($.fn.on);
// in jQuery 1.3+ we can fix mistakes with the ready state
if (!options.delegation && this.length === 0) {
var o = { s: this.selector, c: this.context };
if (!$.isReady && o.s) {
log('DOM not ready, queuing ajaxForm');
$(function() {
$(o.s,o.c).ajaxForm(options);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
if ( options.delegation ) {
$(document)
.off('submit.form-plugin', this.selector, doAjaxSubmit)
.off('click.form-plugin', this.selector, captureSubmittingElement)
.on('submit.form-plugin', this.selector, options, doAjaxSubmit)
.on('click.form-plugin', this.selector, options, captureSubmittingElement);
return this;
}
return this.ajaxFormUnbind()
.bind('submit.form-plugin', options, doAjaxSubmit)
.bind('click.form-plugin', options, captureSubmittingElement);
};
// private event handlers
function doAjaxSubmit(e) {
/*jshint validthis:true */
var options = e.data;
if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
e.preventDefault();
$(this).ajaxSubmit(options);
}
}
function captureSubmittingElement(e) {
/*jshint validthis:true */
var target = e.target;
var $el = $(target);
if (!($el.is("[type=submit],[type=image]"))) {
// is this a child element of the submit el? (ex: a span within a button)
var t = $el.closest('[type=submit]');
if (t.length === 0) {
return;
}
target = t[0];
}
var form = this;
form.clk = target;
if (target.type == 'image') {
if (e.offsetX !== undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') {
var offset = $el.offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - target.offsetLeft;
form.clk_y = e.pageY - target.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
}
// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
return this.unbind('submit.form-plugin click.form-plugin');
};
/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property. An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic, elements) {
var a = [];
if (this.length === 0) {
return a;
}
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) {
return a;
}
var i,j,n,v,el,max,jmax;
for(i=0, max=els.length; i < max; i++) {
el = els[i];
n = el.name;
if (!n || el.disabled) {
continue;
}
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(form.clk == el) {
a.push({name: n, value: $(el).val(), type: el.type });
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
continue;
}
v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
if (elements)
elements.push(el);
for(j=0, jmax=v.length; j < jmax; j++) {
a.push({name: n, value: v[j]});
}
}
else if (feature.fileapi && el.type == 'file') {
if (elements)
elements.push(el);
var files = el.files;
if (files.length) {
for (j=0; j < files.length; j++) {
a.push({name: n, value: files[j], type: el.type});
}
}
else {
// #180
a.push({ name: n, value: '', type: el.type });
}
}
else if (v !== null && typeof v != 'undefined') {
if (elements)
elements.push(el);
a.push({name: n, value: v, type: el.type, required: el.required});
}
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle it here
var $input = $(form.clk), input = $input[0];
n = input.name;
if (n && !input.disabled && input.type == 'image') {
a.push({name: n, value: $input.val()});
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};
/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) {
return;
}
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++) {
a.push({name: n, value: v[i]});
}
}
else if (v !== null && typeof v != 'undefined') {
a.push({name: this.name, value: v});
}
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};
/**
* Returns the value(s) of the element in the matched set. For example, consider the following form:
*
* <form><fieldset>
* <input name="A" type="text" />
* <input name="A" type="text" />
* <input name="B" type="checkbox" value="B1" />
* <input name="B" type="checkbox" value="B2"/>
* <input name="C" type="radio" value="C1" />
* <input name="C" type="radio" value="C2" />
* </fieldset></form>
*
* var v = $('input[type=text]').fieldValue();
* // if no values are entered into the text inputs
* v == ['','']
* // if values entered into the text inputs are 'foo' and 'bar'
* v == ['foo','bar']
*
* var v = $('input[type=checkbox]').fieldValue();
* // if neither checkbox is checked
* v === undefined
* // if both checkboxes are checked
* v == ['B1', 'B2']
*
* var v = $('input[type=radio]').fieldValue();
* // if neither radio is checked
* v === undefined
* // if first radio is checked
* v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true. If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array. If no valid value can be determined the
* array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
continue;
}
if (v.constructor == Array)
$.merge(val, v);
else
val.push(v);
}
return val;
};
/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (successful === undefined) {
successful = true;
}
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1)) {
return null;
}
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) {
return null;
}
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = op.value;
if (!v) { // extra pain for IE...
v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
}
if (one) {
return v;
}
a.push(v);
}
}
return a;
}
return $(el).val();
};
/**
* Clears the form data. Takes the following actions on the form's input fields:
* - input text fields will have their 'value' property set to the empty string
* - select elements will have their 'selectedIndex' property set to -1
* - checkbox and radio inputs will have their 'checked' property set to false
* - inputs of type submit, button, reset, and hidden will *not* be effected
* - button elements will *not* be effected
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden);
});
};
/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) )
this.value = '';
}
});
};
/**
* Resets the form data. Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
this.reset();
}
});
};
/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) {
if (b === undefined) {
b = true;
}
return this.each(function() {
this.disabled = !b;
});
};
/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select === undefined) {
select = true;
}
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio') {
this.checked = select;
}
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
// expose debug var
$.fn.ajaxSubmit.debug = false;
// helper fn for console logging
function log() {
if (!$.fn.ajaxSubmit.debug)
return;
var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
if (window.console && window.console.log) {
window.console.log(msg);
}
else if (window.opera && window.opera.postError) {
window.opera.postError(msg);
}
}
})(jQuery);
| 12sm/erinmyers | wp-content/plugins/wp-toolbar-editor/js/jquery.form.js | JavaScript | gpl-2.0 | 41,603 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
goog.provide('goog.editor.plugins.LinkBubbleTest');
goog.setTestOnly('goog.editor.plugins.LinkBubbleTest');
goog.require('goog.dom');
goog.require('goog.dom.Range');
goog.require('goog.dom.TagName');
goog.require('goog.editor.Command');
goog.require('goog.editor.Link');
goog.require('goog.editor.plugins.LinkBubble');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.Event');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.testing.FunctionMock');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.editor.FieldMock');
goog.require('goog.testing.editor.TestHelper');
goog.require('goog.testing.events');
goog.require('goog.testing.jsunit');
goog.require('goog.userAgent');
var fieldDiv;
var FIELDMOCK;
var linkBubble;
var link;
var linkChild;
var mockWindowOpen;
var stubs;
var testHelper;
function setUpPage() {
fieldDiv = goog.dom.$('field');
stubs = new goog.testing.PropertyReplacer();
testHelper = new goog.testing.editor.TestHelper(goog.dom.getElement('field'));
}
function setUp() {
testHelper.setUpEditableElement();
FIELDMOCK = new goog.testing.editor.FieldMock();
linkBubble = new goog.editor.plugins.LinkBubble();
linkBubble.fieldObject = FIELDMOCK;
link = fieldDiv.firstChild;
linkChild = link.lastChild;
mockWindowOpen = new goog.testing.FunctionMock('open');
stubs.set(window, 'open', mockWindowOpen);
}
function tearDown() {
linkBubble.closeBubble();
testHelper.tearDownEditableElement();
stubs.reset();
}
function testLinkSelected() {
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
goog.dom.Range.createFromNodeContents(link).select();
linkBubble.handleSelectionChange();
assertBubble();
FIELDMOCK.$verify();
}
function testLinkClicked() {
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
FIELDMOCK.$verify();
}
function testImageLink() {
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
link.setAttribute('imageanchor', 1);
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
FIELDMOCK.$verify();
}
function closeBox() {
var closeBox = goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.DIV,
'tr_bubble_closebox');
assertEquals('Should find only one close box', 1, closeBox.length);
assertNotNull('Found close box', closeBox[0]);
goog.testing.events.fireClickSequence(closeBox[0]);
}
function testCloseBox() {
testLinkClicked();
closeBox();
assertNoBubble();
FIELDMOCK.$verify();
}
function testChangeClicked() {
FIELDMOCK.execCommand(goog.editor.Command.MODAL_LINK_EDITOR,
new goog.editor.Link(link, false));
FIELDMOCK.$registerArgumentListVerifier('execCommand', function(arr1, arr2) {
return arr1.length == arr2.length &&
arr1.length == 2 &&
arr1[0] == goog.editor.Command.MODAL_LINK_EDITOR &&
arr2[0] == goog.editor.Command.MODAL_LINK_EDITOR &&
arr1[1] instanceof goog.editor.Link &&
arr2[1] instanceof goog.editor.Link;
});
FIELDMOCK.$times(1);
FIELDMOCK.$returns(true);
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
goog.testing.events.fireClickSequence(
goog.dom.$(goog.editor.plugins.LinkBubble.CHANGE_LINK_ID_));
assertNoBubble();
FIELDMOCK.$verify();
}
function testChangePressed() {
FIELDMOCK.execCommand(goog.editor.Command.MODAL_LINK_EDITOR,
new goog.editor.Link(link, false));
FIELDMOCK.$registerArgumentListVerifier('execCommand', function(arr1, arr2) {
return arr1.length == arr2.length &&
arr1.length == 2 &&
arr1[0] == goog.editor.Command.MODAL_LINK_EDITOR &&
arr2[0] == goog.editor.Command.MODAL_LINK_EDITOR &&
arr1[1] instanceof goog.editor.Link &&
arr2[1] instanceof goog.editor.Link;
});
FIELDMOCK.$times(1);
FIELDMOCK.$returns(true);
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
var defaultPrevented = !goog.testing.events.fireKeySequence(
goog.dom.$(goog.editor.plugins.LinkBubble.CHANGE_LINK_ID_),
goog.events.KeyCodes.ENTER);
assertTrue(defaultPrevented);
assertNoBubble();
FIELDMOCK.$verify();
}
function testDeleteClicked() {
FIELDMOCK.dispatchBeforeChange();
FIELDMOCK.$times(1);
FIELDMOCK.dispatchChange();
FIELDMOCK.$times(1);
FIELDMOCK.focus();
FIELDMOCK.$times(1);
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
goog.testing.events.fireClickSequence(
goog.dom.$(goog.editor.plugins.LinkBubble.DELETE_LINK_ID_));
var element = goog.userAgent.GECKO ? document.body : fieldDiv;
assertNotEquals('Link removed', element.firstChild.nodeName,
goog.dom.TagName.A);
assertNoBubble();
var range = goog.dom.Range.createFromWindow();
assertEquals('Link selection on link text', linkChild, range.getEndNode());
assertEquals('Link selection on link text end',
goog.dom.getRawTextContent(linkChild).length, range.getEndOffset());
FIELDMOCK.$verify();
}
function testDeletePressed() {
FIELDMOCK.dispatchBeforeChange();
FIELDMOCK.$times(1);
FIELDMOCK.dispatchChange();
FIELDMOCK.$times(1);
FIELDMOCK.focus();
FIELDMOCK.$times(1);
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
var defaultPrevented = !goog.testing.events.fireKeySequence(
goog.dom.$(goog.editor.plugins.LinkBubble.DELETE_LINK_ID_),
goog.events.KeyCodes.ENTER);
assertTrue(defaultPrevented);
var element = goog.userAgent.GECKO ? document.body : fieldDiv;
assertNotEquals('Link removed', element.firstChild.nodeName,
goog.dom.TagName.A);
assertNoBubble();
var range = goog.dom.Range.createFromWindow();
assertEquals('Link selection on link text', linkChild, range.getEndNode());
assertEquals('Link selection on link text end',
goog.dom.getRawTextContent(linkChild).length, range.getEndOffset());
FIELDMOCK.$verify();
}
function testActionClicked() {
var SPAN = 'actionSpanId';
var LINK = 'actionLinkId';
var toShowCount = 0;
var actionCount = 0;
var linkAction = new goog.editor.plugins.LinkBubble.Action(
SPAN, LINK, 'message',
function() {
toShowCount++;
return toShowCount == 1; // Show it the first time.
},
function() {
actionCount++;
});
linkBubble = new goog.editor.plugins.LinkBubble(linkAction);
linkBubble.fieldObject = FIELDMOCK;
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
// The first time the bubble is shown, show our custom action.
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
assertEquals('Should check showing the action', 1, toShowCount);
assertEquals('Action should not have fired yet', 0, actionCount);
assertTrue('Action should be visible 1st time', goog.style.isElementShown(
goog.dom.$(SPAN)));
goog.testing.events.fireClickSequence(goog.dom.$(LINK));
assertEquals('Should not check showing again yet', 1, toShowCount);
assertEquals('Action should be fired', 1, actionCount);
closeBox();
assertNoBubble();
// The action won't be shown the second time around.
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
assertEquals('Should check showing again', 2, toShowCount);
assertEquals('Action should not fire again', 1, actionCount);
assertFalse('Action should not be shown 2nd time', goog.style.isElementShown(
goog.dom.$(SPAN)));
FIELDMOCK.$verify();
}
function testLinkTextClicked() {
mockWindowOpen('http://www.google.com/', '_blank', '');
mockWindowOpen.$replay();
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
goog.testing.events.fireClickSequence(
goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_));
assertBubble();
mockWindowOpen.$verify();
FIELDMOCK.$verify();
}
function testLinkTextClickedCustomUrlFn() {
mockWindowOpen('http://images.google.com/', '_blank', '');
mockWindowOpen.$replay();
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
linkBubble.setTestLinkUrlFn(function(url) {
return url.replace('www', 'images');
});
linkBubble.handleSelectionChange(createMouseEvent(link));
assertBubble();
goog.testing.events.fireClickSequence(
goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_));
assertBubble();
mockWindowOpen.$verify();
FIELDMOCK.$verify();
}
/**
* Urls with invalid schemes shouldn't be linkified.
* @bug 2585360
*/
function testDontLinkifyInvalidScheme() {
mockWindowOpen.$replay();
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
var badLink = document.createElement(goog.dom.TagName.A);
badLink.href = 'javascript:alert(1)';
badLink.innerHTML = 'bad link';
linkBubble.handleSelectionChange(createMouseEvent(badLink));
assertBubble();
// The link shouldn't exist at all
assertNull(goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_));
assertBubble();
mockWindowOpen.$verify();
FIELDMOCK.$verify();
}
function testIsSafeSchemeToOpen() {
// Urls with no scheme at all are ok too since 'http://' will be prepended.
var good = [
'http://google.com', 'http://google.com/', 'https://google.com',
'[email protected]', 'http://www.google.com', 'http://site.com',
'google.com', 'google', 'http://google', 'HTTP://GOOGLE.COM',
'HtTp://www.google.com'
];
var bad = [
'javascript:google.com', 'httpp://google.com', 'data:foo',
'javascript:alert(\'hi\');', 'abc:def'
];
for (var i = 0; i < good.length; i++) {
assertTrue(good[i] + ' should have a safe scheme',
linkBubble.isSafeSchemeToOpen_(good[i]));
}
for (i = 0; i < bad.length; i++) {
assertFalse(bad[i] + ' should have an unsafe scheme',
linkBubble.isSafeSchemeToOpen_(bad[i]));
}
}
function testShouldOpenWithWhitelist() {
linkBubble.setSafeToOpenSchemes(['abc']);
assertTrue('Scheme should be safe',
linkBubble.shouldOpenUrl('abc://google.com'));
assertFalse('Scheme should be unsafe',
linkBubble.shouldOpenUrl('http://google.com'));
linkBubble.setBlockOpeningUnsafeSchemes(false);
assertTrue('Non-whitelisted should now be safe after disabling blocking',
linkBubble.shouldOpenUrl('http://google.com'));
}
/**
* @bug 763211
* @bug 2182147
*/
function testLongUrlTestLinkAnchorTextCorrect() {
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
var longUrl = 'http://www.reallylonglinkthatshouldbetruncated' +
'becauseitistoolong.com';
var truncatedLongUrl = goog.string.truncateMiddle(longUrl, 48);
var longLink = document.createElement(goog.dom.TagName.A);
longLink.href = longUrl;
longLink.innerHTML = 'Google';
fieldDiv.appendChild(longLink);
linkBubble.handleSelectionChange(createMouseEvent(longLink));
assertBubble();
var testLinkEl = goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_);
assertEquals(
'The test link\'s anchor text should be the truncated URL.',
truncatedLongUrl,
testLinkEl.innerHTML);
fieldDiv.removeChild(longLink);
FIELDMOCK.$verify();
}
/**
* @bug 2416024
*/
function testOverridingCreateBubbleContentsDoesntNpeGetTargetUrl() {
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
stubs.set(linkBubble, 'createBubbleContents',
function(elem) {
// getTargetUrl would cause an NPE if urlUtil_ wasn't defined yet.
linkBubble.getTargetUrl();
});
assertNotThrows('Accessing this.urlUtil_ should not NPE',
goog.bind(linkBubble.handleSelectionChange,
linkBubble, createMouseEvent(link)));
FIELDMOCK.$verify();
}
/**
* @bug 15379294
*/
function testUpdateLinkCommandDoesNotTriggerAnException() {
FIELDMOCK.$replay();
linkBubble.enable(FIELDMOCK);
// At this point, the bubble was not created yet using its createBubble
// public method.
assertNotThrows(
'Executing goog.editor.Command.UPDATE_LINK_BUBBLE should not trigger ' +
'an exception even if the bubble was not created yet using its ' +
'createBubble method.',
goog.bind(linkBubble.execCommandInternal, linkBubble,
goog.editor.Command.UPDATE_LINK_BUBBLE));
FIELDMOCK.$verify();
}
function assertBubble() {
assertTrue('Link bubble visible', linkBubble.isVisible());
assertNotNull('Link bubble created',
goog.dom.$(goog.editor.plugins.LinkBubble.LINK_DIV_ID_));
}
function assertNoBubble() {
assertFalse('Link bubble not visible', linkBubble.isVisible());
assertNull('Link bubble not created',
goog.dom.$(goog.editor.plugins.LinkBubble.LINK_DIV_ID_));
}
function createMouseEvent(target) {
var eventObj = new goog.events.Event(goog.events.EventType.MOUSEUP, target);
eventObj.button = goog.events.BrowserEvent.MouseButton.LEFT;
return new goog.events.BrowserEvent(eventObj, target);
}
| Nestor94Gonzalez/robot_blockly | frontend/closure-library/closure/goog/editor/plugins/linkbubble_test.js | JavaScript | gpl-3.0 | 13,917 |
"use strict";
tutao.provide('tutao.entity.base.PersistenceResourcePostReturn');
/**
* @constructor
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.base.PersistenceResourcePostReturn = function(data) {
if (data) {
this.updateData(data);
} else {
this.__format = "0";
this._generatedId = null;
this._permissionListId = null;
}
this._entityHelper = new tutao.entity.EntityHelper(this);
this.prototype = tutao.entity.base.PersistenceResourcePostReturn.prototype;
};
/**
* Updates the data of this entity.
* @param {Object=} data The json data to store in this entity.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.updateData = function(data) {
this.__format = data._format;
this._generatedId = data.generatedId;
this._permissionListId = data.permissionListId;
};
/**
* The version of the model this type belongs to.
* @const
*/
tutao.entity.base.PersistenceResourcePostReturn.MODEL_VERSION = '1';
/**
* The encrypted flag.
* @const
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.ENCRYPTED = false;
/**
* Provides the data of this instances as an object that can be converted to json.
* @return {Object} The json object.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.toJsonData = function() {
return {
_format: this.__format,
generatedId: this._generatedId,
permissionListId: this._permissionListId
};
};
/**
* The id of the PersistenceResourcePostReturn type.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.TYPE_ID = 0;
/**
* The id of the generatedId attribute.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.GENERATEDID_ATTRIBUTE_ID = 2;
/**
* The id of the permissionListId attribute.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.PERMISSIONLISTID_ATTRIBUTE_ID = 3;
/**
* Sets the format of this PersistenceResourcePostReturn.
* @param {string} format The format of this PersistenceResourcePostReturn.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.setFormat = function(format) {
this.__format = format;
return this;
};
/**
* Provides the format of this PersistenceResourcePostReturn.
* @return {string} The format of this PersistenceResourcePostReturn.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.getFormat = function() {
return this.__format;
};
/**
* Sets the generatedId of this PersistenceResourcePostReturn.
* @param {string} generatedId The generatedId of this PersistenceResourcePostReturn.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.setGeneratedId = function(generatedId) {
this._generatedId = generatedId;
return this;
};
/**
* Provides the generatedId of this PersistenceResourcePostReturn.
* @return {string} The generatedId of this PersistenceResourcePostReturn.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.getGeneratedId = function() {
return this._generatedId;
};
/**
* Sets the permissionListId of this PersistenceResourcePostReturn.
* @param {string} permissionListId The permissionListId of this PersistenceResourcePostReturn.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.setPermissionListId = function(permissionListId) {
this._permissionListId = permissionListId;
return this;
};
/**
* Provides the permissionListId of this PersistenceResourcePostReturn.
* @return {string} The permissionListId of this PersistenceResourcePostReturn.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.getPermissionListId = function() {
return this._permissionListId;
};
/**
* Provides the entity helper of this entity.
* @return {tutao.entity.EntityHelper} The entity helper.
*/
tutao.entity.base.PersistenceResourcePostReturn.prototype.getEntityHelper = function() {
return this._entityHelper;
};
| msoftware/tutanota-1 | web/js/generated/entity/base/PersistenceResourcePostReturn.js | JavaScript | gpl-3.0 | 3,838 |
// |jit-test| error: TestComplete
// onPop can change a normal return into a throw.
load(libdir + "asserts.js");
var g = newGlobal('new-compartment');
var dbg = new Debugger(g);
function test(type, provocation) {
var log;
// Help people figure out which 'test' call failed.
print("type: " + uneval(type));
print("provocation: " + uneval(provocation));
dbg.onDebuggerStatement = function handleDebuggerStatement(f) {
log += 'd';
};
dbg.onEnterFrame = function handleEnterFrame(f) {
log += '(';
assertEq(f.type, type);
f.onPop = function handlePop(c) {
log += ')';
assertEq(c.return, 'compliment');
return { throw: 'snow' };
};
};
log = '';
assertThrowsValue(provocation, 'snow');
assertEq(log, "(d)");
print();
}
g.eval("function f() { debugger; return 'compliment'; }");
test("call", g.f);
test("call", function () { return new g.f; });
test("eval", function () { return g.eval("debugger; \'compliment\';"); });
test("global", function () { return g.evaluate("debugger; \'compliment\';"); });
throw 'TestComplete';
| SlateScience/MozillaJS | js/src/jit-test/tests/debug/Frame-onPop-return-throw.js | JavaScript | mpl-2.0 | 1,154 |
//Version-IE: < 9
if ( 'function' !== typeof Array.prototype.reduce ) {
Array.prototype.reduce = function( callback /*, initialValue*/ ) {
'use strict';
if ( null === this || 'undefined' === typeof this ) {
throw new TypeError(
'Array.prototype.reduce called on null or undefined' );
}
if ( 'function' !== typeof callback ) {
throw new TypeError( callback + ' is not a function' );
}
var t = Object( this ), len = t.length >>> 0, k = 0, value;
if ( arguments.length >= 2 ) {
value = arguments[1];
} else {
while ( k < len && ! k in t ) k++;
if ( k >= len )
throw new TypeError('Reduce of empty array with no initial value');
value = t[ k++ ];
}
for ( ; k < len ; k++ ) {
if ( k in t ) {
value = callback( value, t[k], k, t );
}
}
return value;
};
}
//Version-IE: < 9
if ( 'function' !== typeof Array.prototype.reduceRight ) {
Array.prototype.reduceRight = function( callback /*, initialValue*/ ) {
'use strict';
if ( null === this || 'undefined' === typeof this ) {
throw new TypeError(
'Array.prototype.reduce called on null or undefined' );
}
if ( 'function' !== typeof callback ) {
throw new TypeError( callback + ' is not a function' );
}
var t = Object( this ), len = t.length >>> 0, k = len - 1, value;
if ( arguments.length >= 2 ) {
value = arguments[1];
} else {
while ( k >= 0 && ! k in t ) k--;
if ( k < 0 )
throw new TypeError('Reduce of empty array with no initial value');
value = t[ k-- ];
}
for ( ; k >= 0 ; k-- ) {
if ( k in t ) {
value = callback( value, t[k], k, t );
}
}
return value;
};
}
//Version-IE: < 9
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisArg */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(<span style="line-height: normal;">thisArg</span><span style="line-height: normal;">, val, i, t))</span>
res.push(val);
}
}
return res;
};
}
//Version-IE: < 9
if (!Array.prototype.every) {
Array.prototype.every = function (callbackfn, thisArg) {
"use strict";
var T, k;
if (this == null) {
throw new TypeError("this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the this
// value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
if (typeof callbackfn !== "function") {
throw new TypeError();
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let k be 0.
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal
// method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Let testResult be the result of calling the Call internal method
// of callbackfn with T as the this value and argument list
// containing kValue, k, and O.
var testResult = callbackfn.call(T, kValue, k, O);
// iii. If ToBoolean(testResult) is false, return false.
if (!testResult) {
return false;
}
}
k++;
}
return true;
};
}
//Version-IE: < 9
if (!Array.prototype.some)
{
Array.prototype.some = function(fun /*, thisArg */)
{
'use strict';
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function')
throw new TypeError();
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t && fun.call(thisArg, t[i], i, t))
return true;
}
return false;
};
}
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.com/#x15.4.4.19
//Version-IE: < 9
if (!Array.prototype.map) {
Array.prototype.map = function (callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let A be a new array created as if by the expression new Array( len) where Array is
// the standard built-in constructor with that name and len is the value of len.
A = new Array(len);
// 7. Let k be 0
k = 0;
// 8. Repeat, while k < len
while (k < len) {
var kValue, mappedValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Let mappedValue be the result of calling the Call internal method of callback
// with T as the this value and argument list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor {Value: mappedValue, Writable: true, Enumerable: true, Configurable: true},
// and false.
// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty( A, k, { value: mappedValue, writable: true, enumerable: true, configurable: true });
// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
//Version-IE: < 9
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
| OCamlPro-Henry/js_of_ocaml | runtime/polyfill/array.js | JavaScript | lgpl-2.1 | 9,421 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* If x is -Infinity and y>0 and y is an odd integer, Math.pow(x,y) is -Infinity
*
* @path ch15/15.8/15.8.2/15.8.2.13/S15.8.2.13_A13.js
* @description Checking if Math.pow(x,y) equals to -Infinity, where x is -Infinity and y>0
*/
// CHECK#1
x = -Infinity;
y = new Array();
y[0] = 1;
y[1] = 111;
y[2] = 111111;
ynum = 3;
for (i = 0; i < ynum; i++)
{
if (Math.pow(x,y[i]) !== -Infinity)
{
$ERROR("#1: Math.pow(" + x + ", " + y[i] + ") !== -Infinity");
}
}
| popravich/typescript | tests/Fidelity/test262/suite/ch15/15.8/15.8.2/15.8.2.13/S15.8.2.13_A13.js | JavaScript | apache-2.0 | 604 |
var fs = require('fs')
var path = require('path')
var resolve = path.resolve
var osenv = require('osenv')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var test = require('tap').test
var npm = require('../../lib/npm')
var common = require('../common-tap')
var chain = require('slide').chain
var mockPath = resolve(__dirname, 'install-shrinkwrapped')
var parentPath = resolve(mockPath, 'parent')
var parentNodeModulesPath = path.join(parentPath, 'node_modules')
var outdatedNodeModulesPath = resolve(mockPath, 'node-modules-backup')
var childPath = resolve(mockPath, 'child.git')
var gitDaemon
var gitDaemonPID
var git
var parentPackageJSON = JSON.stringify({
name: 'parent',
version: '0.1.0'
})
var childPackageJSON = JSON.stringify({
name: 'child',
version: '0.1.0'
})
test('setup', function (t) {
cleanup()
setup(function (err, result) {
t.ifError(err, 'git started up successfully')
if (!err) {
gitDaemon = result[result.length - 2]
gitDaemonPID = result[result.length - 1]
}
t.end()
})
})
test('shrinkwrapped git dependency got updated', function (t) {
t.comment('test for https://github.com/npm/npm/issues/12718')
// Prepare the child package git repo with two commits
prepareChildAndGetRefs(function (refs) {
chain([
// Install & shrinkwrap child package's first commit
[npm.commands.install, ['git://localhost:1234/child.git#' + refs[0]]],
// Backup node_modules with the first commit
[fs.rename, parentNodeModulesPath, outdatedNodeModulesPath],
// Install & shrinkwrap child package's second commit
[npm.commands.install, ['git://localhost:1234/child.git#' + refs[1]]],
// Restore node_modules with the first commit
[rimraf, parentNodeModulesPath],
[fs.rename, outdatedNodeModulesPath, parentNodeModulesPath],
// Update node_modules
[npm.commands.install, []]
], function () {
var childPackageJSON = require(path.join(parentNodeModulesPath, 'child', 'package.json'))
t.equal(
childPackageJSON._resolved,
'git://localhost:1234/child.git#' + refs[1],
"Child package wasn't updated"
)
t.end()
})
})
})
test('clean', function (t) {
gitDaemon.on('close', function () {
cleanup()
t.end()
})
process.kill(gitDaemonPID)
})
function setup (cb) {
// Setup parent package
mkdirp.sync(parentPath)
fs.writeFileSync(resolve(parentPath, 'package.json'), parentPackageJSON)
process.chdir(parentPath)
// Setup child
mkdirp.sync(childPath)
fs.writeFileSync(resolve(childPath, 'package.json'), childPackageJSON)
// Setup npm and then git
npm.load({
registry: common.registry,
loglevel: 'silent',
save: true // Always install packages with --save
}, function () {
// It's important to initialize git after npm because it uses config
initializeGit(cb)
})
}
function cleanup () {
process.chdir(osenv.tmpdir())
rimraf.sync(mockPath)
rimraf.sync(common['npm_config_cache'])
}
function prepareChildAndGetRefs (cb) {
var opts = { cwd: childPath, env: { PATH: process.env.PATH } }
chain([
[fs.writeFile, path.join(childPath, 'README.md'), ''],
git.chainableExec(['add', 'README.md'], opts),
git.chainableExec(['commit', '-m', 'Add README'], opts),
git.chainableExec(['log', '--pretty=format:"%H"', '-2'], opts)
], function () {
var gitLogStdout = arguments[arguments.length - 1]
var refs = gitLogStdout[gitLogStdout.length - 1].split('\n').map(function (ref) {
return ref.match(/^"(.+)"$/)[1]
}).reverse() // Reverse refs order: last, first -> first, last
cb(refs)
})
}
function initializeGit (cb) {
git = require('../../lib/utils/git')
common.makeGitRepo({
path: childPath,
commands: [startGitDaemon]
}, cb)
}
function startGitDaemon (cb) {
var daemon = git.spawn(
[
'daemon',
'--verbose',
'--listen=localhost',
'--export-all',
'--base-path=' + mockPath, // Path to the dir that contains child.git
'--reuseaddr',
'--port=1234'
],
{
cwd: parentPath,
env: process.env,
stdio: ['pipe', 'pipe', 'pipe']
}
)
daemon.stderr.on('data', function findChild (c) {
var cpid = c.toString().match(/^\[(\d+)\]/)
if (cpid[1]) {
this.removeListener('data', findChild)
cb(null, [daemon, cpid[1]])
}
})
}
| mrtequino/JSW | nodejs/pos-server/node_modules/npm/test/tap/install-shrinkwrapped-git.js | JavaScript | apache-2.0 | 4,407 |
// test cube
var assert = require('assert'),
math = require('../../../index'),
error = require('../../../lib/error/index'),
unit = math.unit,
bignumber = math.bignumber,
matrix = math.matrix,
range = math.range,
cube = math.cube;
describe('cube', function() {
it('should return the cube of a boolean', function () {
assert.equal(cube(true), 1);
assert.equal(cube(false), 0);
});
it('should return the cube of null', function () {
assert.equal(math.ceil(null), 0);
});
it('should return the cube of a number', function() {
assert.equal(cube(4), 64);
assert.equal(cube(-2), -8);
assert.equal(cube(0), 0);
});
it('should return the cube of a big number', function() {
assert.deepEqual(cube(bignumber(4)), bignumber(64));
assert.deepEqual(cube(bignumber(-2)), bignumber(-8));
assert.deepEqual(cube(bignumber(0)), bignumber(0));
});
it('should return the cube of a complex number', function() {
assert.deepEqual(cube(math.complex('2i')), math.complex('-8i'));
assert.deepEqual(cube(math.complex('2+3i')), math.complex('-46+9i'));
assert.deepEqual(cube(math.complex('2')), math.complex('8'));
});
it('should throw an error with strings', function() {
assert.throws(function () {cube('text')});
});
it('should throw an error with units', function() {
assert.throws(function () {cube(unit('5cm'))});
});
it('should throw an error if there\'s wrong number of args', function() {
assert.throws(function () {cube()}, error.ArgumentsError);
assert.throws(function () {cube(1, 2)}, error.ArgumentsError);
});
it('should cube each element in a matrix, array or range', function() {
// array, matrix, range
// arrays are evaluated element wise
assert.deepEqual(cube([2,3,4,5]), [8,27,64,125]);
assert.deepEqual(cube(matrix([2,3,4,5])), matrix([8,27,64,125]));
assert.deepEqual(cube(matrix([[1,2],[3,4]])), matrix([[1,8],[27,64]]));
});
}); | owenversteeg/mathjs | test/function/arithmetic/cube.test.js | JavaScript | apache-2.0 | 1,982 |
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.id');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Tambahkan sebuah comment";
Blockly.Msg.CHANGE_VALUE_TITLE = "Ubah nilai:";
Blockly.Msg.COLLAPSE_ALL = "Tutup blok";
Blockly.Msg.COLLAPSE_BLOCK = "Tutup blok";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "Warna 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "Warna 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/";
Blockly.Msg.COLOUR_BLEND_RATIO = "rasio";
Blockly.Msg.COLOUR_BLEND_TITLE = "Tertutup";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "mencampur dua warna secara bersamaan dengan perbandingan (0.0-1.0).";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/Color";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Pilih warna dari daftar warna.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "Warna acak";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Pilih warna secara acak.";
Blockly.Msg.COLOUR_RGB_BLUE = "biru";
Blockly.Msg.COLOUR_RGB_GREEN = "hijau";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "merah";
Blockly.Msg.COLOUR_RGB_TITLE = "Dengan warna";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Buatlah warna dengan jumlah yang ditentukan dari merah, hijau dan biru. Semua nilai harus antarai 0 sampai 100.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#Loop_Termination_Blocks";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "Keluar dari perulangan";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "Lanjutkan dengan langkah penggulangan berikutnya";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Keluar sementara dari perulanggan.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Abaikan sisa dari loop ini, dan lanjutkan dengan iterasi berikutnya.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Peringatan: Blok ini hanya dapat digunakan dalam loop.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#for_each for each block";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "di dalam list";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "untuk setiap item";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Untuk tiap-tiap item di dalam list, tetapkan variabel '%1' ke dalam item, selanjutnya kerjakan beberapa statement.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#count_with";
Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO_BY = "dari %1 ke %2 dengan step / penambahan %3";
Blockly.Msg.CONTROLS_FOR_INPUT_WITH = "Cacah dengan";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Menggunakan variabel %1 dengan mengambil nilai dari batas awal hingga ke batas akhir, dengan interval tertentu, dan mengerjakan block tertentu.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "tambahkan prasyarat ke dalam blok IF.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Terakhir, tambahkan tangkap-semua kondisi kedalam blok jika (if).";
Blockly.Msg.CONTROLS_IF_HELPURL = "http://code.google.com/p/blockly/wiki/If_Then";
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Menambahkan, menghapus, atau menyusun kembali bagian untuk mengkonfigurasi blok IF ini.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "else";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "else if";
Blockly.Msg.CONTROLS_IF_MSG_IF = "Jika";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "jika nilainya benar maka kerjakan perintah berikutnya.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "jika nilainya benar, maka kerjakan blok perintah yang pertama. Jika tidak, kerjakan blok perintah yang kedua.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Jika nilai pertama adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok pertama. Jika nilai kedua adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok kedua.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Jika blok pertama adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok pertama. Atau jika blok kedua adalah benar (true), maka lakukan perintah-perintah yang berada didalam blok kedua.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "kerjakan";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "ulangi %1 kali";
Blockly.Msg.CONTROLS_REPEAT_TITLE_REPEAT = "ulangi";
Blockly.Msg.CONTROLS_REPEAT_TITLE_TIMES = "kali";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Lakukan beberapa perintah beberapa kali.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "http://code.google.com/p/blockly/wiki/Repeat";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "Ulangi sampai";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "Ulangi jika";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Jika sementara nilai tidak benar (false), maka lakukan beberapa perintah.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Jika sementara nilai benar (true), maka lakukan beberapa perintah.";
Blockly.Msg.DELETE_BLOCK = "Hapus blok";
Blockly.Msg.DELETE_X_BLOCKS = "Hapus %1 blok";
Blockly.Msg.DISABLE_BLOCK = "Nonaktifkan blok";
Blockly.Msg.DUPLICATE_BLOCK = "Duplikat";
Blockly.Msg.ENABLE_BLOCK = "Aktifkan blok";
Blockly.Msg.EXPAND_ALL = "Kembangkan blok-blok";
Blockly.Msg.EXPAND_BLOCK = "Kembangkan blok";
Blockly.Msg.EXTERNAL_INPUTS = "Input-input eksternal";
Blockly.Msg.HELP = "Tolong";
Blockly.Msg.INLINE_INPUTS = "Input inline";
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists";
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "buat list kosong";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Mengembalikan daftar, dengan panjang 0, tidak berisi data";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "list";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Tambahkan, hapus, atau susun ulang bagian untuk mengkonfigurasi blok LIST (daftar) ini.";
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "buat daftar (list) dengan";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Tambahkan sebuah item ke daftar (list).";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Buat sebuah daftar (list) dengan sejumlah item.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "pertama";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# dari akhir";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#";
Blockly.Msg.LISTS_GET_INDEX_GET = "dapatkan";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "dapatkan dan hapus";
Blockly.Msg.LISTS_GET_INDEX_LAST = "terakhir";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "acak";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "Hapus";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Kembalikan item pertama dalam daftar (list).";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Sisipkan item ke dalam posisi yang telah ditentukan didalam list (daftar). Item pertama adalah item yang terakhir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Sisipkan item ke dalam posisi yang telah ditentukan didalam list (daftar). Item pertama adalah item terakhir (yg paling akhir).";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Mengembalikan item pertama dalam list (daftar).";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Mengembalikan item acak dalam list (daftar).";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Menghilangkan dan mengembalikan item pertama dalam list (daftar).";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Menghilangkan dan mengembalikan barang di posisi tertentu dalam list (daftar). #1 adalah item terakhir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Menghilangkan dan mengembalikan barang di posisi tertentu dalam list (daftar). #1 adalah item pertama.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Menghilangkan dan mengembalikan item terakhir dalam list (daftar).";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Menghilangkan dan mengembalikan barang dengan acak dalam list (daftar).";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Menghapus item pertama dalam daftar.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Menghapus item dengan posisi tertentu dalam daftar. Item pertama adalah item yang terakhir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Menghapus item dengan posisi tertentu dalam daftar. Item pertama adalah item yang terakhir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Menghapus item terakhir dalam daftar.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Menghapus sebuah item secara acak dalam list.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "ke # dari akhir";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "ke #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "ke yang paling akhir";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_a_sublist";
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "Dapatkan bagian pertama dari list";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "Dapatkan bagian list nomor # dari akhir";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "Dapatkan bagian daftar dari #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Membuat salinan dari bagian tertentu dari list.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "cari kejadian pertama item";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_Items_from_a_List";
Blockly.Msg.LISTS_INDEX_OF_LAST = "Cari kejadian terakhir item";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Mengembalikan indeks dari kejadian pertama/terakhir item dalam daftar. Menghasilkan 0 jika teks tidak ditemukan.";
Blockly.Msg.LISTS_INLIST = "dalam daftar";
Blockly.Msg.LISTS_IS_EMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#is_empty";
Blockly.Msg.LISTS_IS_EMPTY_TITLE = "%1 kosong";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#length_of";
Blockly.Msg.LISTS_LENGTH_TITLE = "panjang dari %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Mengembalikan panjang daftar.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#create_list_with";
Blockly.Msg.LISTS_REPEAT_TITLE = "membuat daftar dengan item %1 diulang %2 kali";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Ciptakan daftar yang terdiri dari nilai yang diberikan diulang jumlah waktu yang ditentukan.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#in_list_..._set";
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "sebagai";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "sisipkan di";
Blockly.Msg.LISTS_SET_INDEX_SET = "tetapkan";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Sisipkan item di bagian awal dari list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Sisipkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang terakhir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Sisipkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang pertama.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Tambahkan item ke bagian akhir list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Sisipkan item secara acak ke dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Tetapkan item pertama di dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Tetapkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang terakhir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Tetapkan item ke dalam posisi yang telah ditentukan di dalam list. #1 adalah item yang pertama.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Menetapkan item terakhir dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Tetapkan secara acak sebuah item dalam list.";
Blockly.Msg.LISTS_TOOLTIP = "Mengembalikan nilai benar (true) jika list kosong.";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "Salah";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "http://code.google.com/p/blockly/wiki/True_False";
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Mengembalikan betul (true) atau salah (false).";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "Benar";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Mengembalikan betul jika input kedua-duanya sama dengan satu sama lain.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Mengembalikan nilai benar (true) jika input yang pertama lebih besar dari input yang kedua.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Mengembalikan nilai benar (true) jika input yang pertama lebih besar dari atau sama dengan input yang kedua.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Mengembalikan nilai benar (true) jika input yang pertama lebih kecil dari input yang kedua.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Mengembalikan nilai benar (true) jika input yang pertama lebih kecil atau sama dengan input yang kedua .";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Mengembalikan nilai benar (true) jika kedua input tidak sama satu dengan yang lain.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "http://code.google.com/p/blockly/wiki/Not";
Blockly.Msg.LOGIC_NEGATE_TITLE = "bukan (not) %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Mengembalikan nilai benar (true) jika input false. Mengembalikan nilai salah (false) jika input true.";
Blockly.Msg.LOGIC_NULL = "null";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type";
Blockly.Msg.LOGIC_NULL_TOOLTIP = "mengembalikan kosong.";
Blockly.Msg.LOGIC_OPERATION_AND = "dan";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "http://code.google.com/p/blockly/wiki/And_Or";
Blockly.Msg.LOGIC_OPERATION_OR = "atau";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Kembalikan betul jika kedua-dua input adalah betul.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Mengembalikan nilai benar (true) jika setidaknya salah satu masukan nilainya benar (true).";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "test";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:";
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "jika tidak benar (false)";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "jika benar (true)";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Periksa kondisi di \"test\". Jika kondisi benar (true), mengembalikan nilai \"jika benar\" ; Jik sebaliknya akan mengembalikan nilai \"jika salah\".";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+";
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://id.wikipedia.org/wiki/Aritmetika";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Kembalikan jumlah dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Kembalikan hasil bagi dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Kembalikan selisih dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Kembalikan perkalian dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Kembalikan angka pertama pangkat angka kedua.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter";
Blockly.Msg.MATH_CHANGE_INPUT_BY = "oleh";
Blockly.Msg.MATH_CHANGE_TITLE_CHANGE = "ubah";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Tambahkan angka kedalam variabel '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Kembalikan salah satu konstant: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), atau ∞ (infinity).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29";
Blockly.Msg.MATH_CONSTRAIN_TITLE = "Batasi %1 rendah %2 tinggi %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Batasi angka antara batas yang ditentukan (inklusif).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷";
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "dibagi oleh";
Blockly.Msg.MATH_IS_EVEN = "adalah bilangan genap";
Blockly.Msg.MATH_IS_NEGATIVE = "adalah bilangan negatif";
Blockly.Msg.MATH_IS_ODD = "adalah bilangan ganjil";
Blockly.Msg.MATH_IS_POSITIVE = "adalah bilangan positif";
Blockly.Msg.MATH_IS_PRIME = "adalah bilangan pokok";
Blockly.Msg.MATH_IS_TOOLTIP = "Periksa apakah angka adalah bilangan genap, bilangan pokok, bilangan bulat, bilangan positif, bilangan negatif, atau apakan bisa dibagi oleh angka tertentu. Mengembalikan benar (true) atau salah (false).";
Blockly.Msg.MATH_IS_WHOLE = "adalah bilangan bulat";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation";
Blockly.Msg.MATH_MODULO_TITLE = "sisa %1 ÷ %2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "Kembalikan sisa dari pembagian ke dua angka.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×";
Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Suatu angka.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "rata-rata dari list (daftar)";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "maximum dari list (daftar)";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "median dari list (daftar)";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "minimum dari list (daftar)";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "mode-mode dari list (daftar)";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "item acak dari list (daftar)";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "deviasi standar dari list (daftar)";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "jumlah dari list (daftar)";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Kembalikan rata-rata (mean aritmetik) dari nilai numerik dari list (daftar).";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Kembalikan angka terbesar dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Kembalikan median dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Kembalikan angka terkecil dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Kembalikan list berisi item-item yang paling umum dari dalam list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Kembalikan element acak dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Kembalikan standard deviasi dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Kembalikan jumlah dari seluruh bilangan dari list.";
Blockly.Msg.MATH_POWER_SYMBOL = "^";
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "Nilai pecahan acak";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Mengembalikan nilai acak pecahan antara 0.0 (inklusif) dan 1.0 (ekslusif).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "acak bulat dari %1 sampai %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Mengembalikan bilangan acak antara dua batas yang ditentukan, inklusif.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "membulatkan";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "membulatkan kebawah";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "mengumpulkan";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Bulatkan suatu bilangan naik atau turun.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "mutlak";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "akar";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Kembalikan nilai absolut angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Kembalikan 10 pangkat angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Kembalikan logaritma natural dari angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Kembalikan dasar logaritma 10 dari angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Kembalikan penyangkalan terhadap angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Kembalikan 10 pangkat angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Kembalikan akar dari angka.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-";
Blockly.Msg.MATH_TRIG_ACOS = "acos";
Blockly.Msg.MATH_TRIG_ASIN = "asin";
Blockly.Msg.MATH_TRIG_ATAN = "atan";
Blockly.Msg.MATH_TRIG_COS = "cos";
Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions";
Blockly.Msg.MATH_TRIG_SIN = "sin";
Blockly.Msg.MATH_TRIG_TAN = "tan";
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Kembalikan acosine dari angka.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Kembalikan asin dari angka.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Kembalikan atan dari angka.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Kembalikan cos dari derajat (bukan radian).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Kembalikan sinus dari derajat (bukan radian).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Kembalikan tangen dari derajat (tidak radian).";
Blockly.Msg.NEW_VARIABLE = "Pembolehubah baru...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Nama pembolehubah baru:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "dengan:";
Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Menjalankan fungsi '%1' yang ditetapkan pengguna.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Menjalankan fungsi '%1' yang ditetapkan pengguna dan menggunakan outputnya.";
Blockly.Msg.PROCEDURES_CREATE_DO = "Buat '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "buat sesuatu";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "untuk";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Menciptakan sebuah fungsi dengan tiada output.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "kembali";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Menciptakan sebuah fungsi dengan satu output.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Peringatan: Fungsi ini memiliki parameter duplikat.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Sorot definisi fungsi";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Jika nilai yang benar, kemudian kembalikan nilai kedua.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Peringatan: Blok ini dapat digunakan hanya dalam definisi fungsi.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "masukan Nama:";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "input";
Blockly.Msg.REMOVE_COMMENT = "Hapus komentar";
Blockly.Msg.RENAME_VARIABLE = "namai ulang variabel...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Ubah nama semua variabel '%1' menjadi:";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "tambahkan teks";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification";
Blockly.Msg.TEXT_APPEND_TO = "untuk";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Tambahkan beberapa teks ke variabel '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Adjusting_text_case";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "menjadi huruf kecil";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "menjadi huruf pertama kapital";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "menjadi huruf kapital";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Kembalikan kopi dari text dengan kapitalisasi yang berbeda.";
Blockly.Msg.TEXT_CHARAT_FIRST = "ambil huruf pertama";
Blockly.Msg.TEXT_CHARAT_FROM_END = "ambil huruf nomor # dari belakang";
Blockly.Msg.TEXT_CHARAT_FROM_START = "ambil huruf ke #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_text";
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "dalam teks";
Blockly.Msg.TEXT_CHARAT_LAST = "ambil huruf terakhir";
Blockly.Msg.TEXT_CHARAT_RANDOM = "ambil huruf secara acak";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Kembalikan karakter dari posisi tertentu.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Tambahkan suatu item ke dalam teks.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "join";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Tambah, ambil, atau susun ulang teks blok.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "pada huruf nomer # dari terakhir";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "pada huruf #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "pada huruf terakhir";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "http://code.google.com/p/blockly/wiki/Text#Extracting_a_region_of_text";
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "in teks";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "ambil bagian teks (substring) dari huruf pertama";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "ambil bagian teks (substring) dari huruf ke # dari terakhir";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "ambil bagian teks (substring) dari huruf no #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Mengembalikan spesifik bagian dari teks.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Finding_text";
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "dalam teks";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "temukan kejadian pertama dalam teks";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "temukan kejadian terakhir dalam teks";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Kembalikan indeks pertama dan terakhir dari kejadian pertama/terakhir dari teks pertama dalam teks kedua. Kembalikan 0 jika teks tidak ditemukan.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Checking_for_empty_text";
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 kosong";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Kembalikan benar (true) jika teks yang disediakan kosong.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_creation";
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "Buat teks dengan";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Buat teks dengan cara gabungkan sejumlah item.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification";
Blockly.Msg.TEXT_LENGTH_TITLE = "panjang dari %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Kembalikan sejumlah huruf (termasuk spasi) dari teks yang disediakan.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Printing_text";
Blockly.Msg.TEXT_PRINT_TITLE = "cetak %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Cetak teks yant ditentukan, angka atau ninlai lainnya.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Getting_input_from_the_user";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Meminta pengguna untuk memberi sebuah angka.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Meminta pengguna untuk memberi beberapa teks.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "Meminta angka dengan pesan";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "meminta teks dengan pesan";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Huruf, kata atau baris teks.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Trimming_%28removing%29_spaces";
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "pangkas ruang dari kedua belah sisi";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "pangkas ruang dari sisi kiri";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "pangkas ruang dari sisi kanan";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Kembali salinan teks dengan spasi dihapus dari satu atau kedua ujungnya.";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "item";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Membuat 'tetapkan %1'";
Blockly.Msg.VARIABLES_GET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Get";
Blockly.Msg.VARIABLES_GET_TAIL = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TITLE = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Mengembalikan nilai variabel ini.";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Membuat 'dapatkan %1'";
Blockly.Msg.VARIABLES_SET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Set";
Blockly.Msg.VARIABLES_SET_TAIL = "untuk";
Blockly.Msg.VARIABLES_SET_TITLE = "tetapkan";
Blockly.Msg.VARIABLES_SET_TOOLTIP = "tetapkan variabel ini dengan input yang sama.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; | TechplexEngineer/blockly-old | msg/js/id.js | JavaScript | apache-2.0 | 29,832 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The following is taken from Closure Library:
//
// buildFromEncodedParts
// splitRe
// ComponentIndex
// split
// removeDotSegments
/**
* Builds a URI string from already-encoded parts.
*
* No encoding is performed. Any component may be omitted as either null or
* undefined.
*
* @param {?string=} opt_scheme The scheme such as 'http'.
* @param {?string=} opt_userInfo The user name before the '@'.
* @param {?string=} opt_domain The domain such as 'www.google.com', already
* URI-encoded.
* @param {(string|number|null)=} opt_port The port number.
* @param {?string=} opt_path The path, already URI-encoded. If it is not
* empty, it must begin with a slash.
* @param {?string=} opt_queryData The URI-encoded query data.
* @param {?string=} opt_fragment The URI-encoded fragment identifier.
* @return {string} The fully combined URI.
*/
function buildFromEncodedParts(opt_scheme, opt_userInfo,
opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
};
/**
* A regular expression for breaking a URI into its component parts.
*
* {@link http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#RFC2234} says
* As the "first-match-wins" algorithm is identical to the "greedy"
* disambiguation method used by POSIX regular expressions, it is natural and
* commonplace to use a regular expression for parsing the potential five
* components of a URI reference.
*
* The following line is the regular expression for breaking-down a
* well-formed URI reference into its components.
*
* <pre>
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
* 12 3 4 5 6 7 8 9
* </pre>
*
* The numbers in the second line above are only to assist readability; they
* indicate the reference points for each subexpression (i.e., each paired
* parenthesis). We refer to the value matched for subexpression <n> as $<n>.
* For example, matching the above expression to
* <pre>
* http://www.ics.uci.edu/pub/ietf/uri/#Related
* </pre>
* results in the following subexpression matches:
* <pre>
* $1 = http:
* $2 = http
* $3 = //www.ics.uci.edu
* $4 = www.ics.uci.edu
* $5 = /pub/ietf/uri/
* $6 = <undefined>
* $7 = <undefined>
* $8 = #Related
* $9 = Related
* </pre>
* where <undefined> indicates that the component is not present, as is the
* case for the query component in the above example. Therefore, we can
* determine the value of the five components as
* <pre>
* scheme = $2
* authority = $4
* path = $5
* query = $7
* fragment = $9
* </pre>
*
* The regular expression has been modified slightly to expose the
* userInfo, domain, and port separately from the authority.
* The modified version yields
* <pre>
* $1 = http scheme
* $2 = <undefined> userInfo -\
* $3 = www.ics.uci.edu domain | authority
* $4 = <undefined> port -/
* $5 = /pub/ietf/uri/ path
* $6 = <undefined> query without ?
* $7 = Related fragment without #
* </pre>
* @type {!RegExp}
* @private
*/
var splitRe = new RegExp(
'^' +
'(?:' +
'([^:/?#.]+)' + // scheme - ignore special characters
// used by other URL parts such as :,
// ?, /, #, and .
':)?' +
'(?://' +
'(?:([^/?#]*)@)?' + // userInfo
'([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
// digits, dashes, dots, percent
// escapes, and unicode characters.
'(?::([0-9]+))?' + // port
')?' +
'([^?#]+)?' + // path
'(?:\\?([^#]*))?' + // query
'(?:#(.*))?' + // fragment
'$');
/**
* The index of each URI component in the return value of goog.uri.utils.split.
* @enum {number}
*/
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
/**
* Splits a URI into its component parts.
*
* Each component can be accessed via the component indices; for example:
* <pre>
* goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
* </pre>
*
* @param {string} uri The URI string to examine.
* @return {!Array.<string|undefined>} Each component still URI-encoded.
* Each component that is present will contain the encoded value, whereas
* components that are not present will be undefined or empty, depending
* on the browser's regular expression implementation. Never null, since
* arbitrary strings may still look like path names.
*/
function split(uri) {
// See @return comment -- never null.
return /** @type {!Array.<string|undefined>} */ (
uri.match(splitRe));
}
/**
* Removes dot segments in given path component, as described in
* RFC 3986, section 5.2.4.
*
* @param {string} path A non-empty path component.
* @return {string} Path component with removed dot segments.
*/
export function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
/**
* Takes an array of the parts from split and canonicalizes the path part
* and then joins all the parts.
* @param {Array.<string?} parts
* @return {string}
*/
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH];
path = removeDotSegments(path.replace(/\/\//.g, '/'));
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(
parts[ComponentIndex.SCHEME],
parts[ComponentIndex.USER_INFO],
parts[ComponentIndex.DOMAIN],
parts[ComponentIndex.PORT],
parts[ComponentIndex.PATH],
parts[ComponentIndex.QUERY_DATA],
parts[ComponentIndex.FRAGMENT]);
}
/**
* Canonicalizes a URL by eliminating ./ path entries,
* canonicalizing ../ entries, and collapsing occurrences of //.
*
* @param {string} url
* @return {string}
*/
export function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
/**
* Resovles a URL.
* @param {string} base The URL acting as the base URL.
* @param {string} to The URL to resolve.
* @return {string}
*/
export function resolveUrl(base, url) {
if (url[0] === '@')
return url;
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
| passy/traceur-todomvc | src/util/url.js | JavaScript | apache-2.0 | 8,826 |
/*
* Copyright 2012 Amadeus s.a.s.
* 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.
*/
Aria.classDefinition({
$classpath : "test.aria.storage.localStorage.NamespaceTestCase",
$dependencies : ["aria.storage.LocalStorage"],
$extends : "test.aria.storage.base.GeneralNamespaceBase",
$constructor : function () {
this.storageLocation = "localStorage";
this.$GeneralNamespaceBase.constructor.call(this);
},
$prototype : {
/**
* Check what happens when you use namespaces, one namespaced shouldn't affect the others
*/
testNamespaceAPI : function () {
if (this.canRunHTML5Tests(false) || this.canRunUserDataTests()) {
this.$GeneralNamespaceBase.testNamespaceAPI.call(this);
}
},
/**
* Verify if the events are raised correctly
*/
testNamespaceEvents : function () {
if (this.canRunHTML5Tests(false) || this.canRunUserDataTests()) {
this.$GeneralNamespaceBase.testNamespaceEvents.call(this);
}
}
}
});
| vcarle/ariatemplates | test/aria/storage/localStorage/NamespaceTestCase.js | JavaScript | apache-2.0 | 1,613 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Number.NEGATIVE_INFINITY is -Infinity
*
* @path ch15/15.7/15.7.3/15.7.3.5/S15.7.3.5_A1.js
* @description Checking sign and finiteness of Number.NEGATIVE_INFINITY
*/
// CHECK#1
if (isFinite(Number.NEGATIVE_INFINITY) !== false) {
$ERROR('#1: Number.NEGATIVE_INFINITY === Not-a-Finite');
} else {
if ((Number.NEGATIVE_INFINITY < 0) !== true) {
$ERROR('#1: Number.NEGATIVE_INFINITY === -Infinity');
}
}
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.7/15.7.3/15.7.3.5/S15.7.3.5_A1.js | JavaScript | apache-2.0 | 555 |
/*!
* Module dependencies.
*/
var Command = require('./util/command'),
phonegapbuild = require('./util/phonegap-build'),
util = require('util');
/*!
* Command setup.
*/
module.exports = {
create: function(phonegap) {
return new RemoteLogoutCommand(phonegap);
}
};
function RemoteLogoutCommand(phonegap) {
return Command.apply(this, arguments);
}
util.inherits(RemoteLogoutCommand, Command);
/**
* Logout.
*
* Logout of PhoneGap/Build.
*
* Options:
*
* - `options` {Object} is unused and should be `{}`.
* - [`callback`] {Function} is a callback function.
* - `e` {Error} is null unless there is an error.
*
* Returns:
*
* {PhoneGap} for chaining.
*/
RemoteLogoutCommand.prototype.run = function(options, callback) {
var self = this;
// require options
if (!options) throw new Error('requires options parameter');
// optional callback
callback = callback || function() {};
// logout
phonegapbuild.logout(options, function(e) {
callback(e);
});
return self.phonegap;
};
| mati191188/ecopueblo-mobile | node_modules/phonegap/lib/phonegap/remote.logout.js | JavaScript | apache-2.0 | 1,079 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-skipped.case
// - src/dstr-binding/default/cls-decl-async-gen-meth-dflt.template
/*---
description: Destructuring initializer is not evaluated when value is not `undefined` (class expression async generator method (default parameters))
esid: sec-class-definitions-runtime-semantics-evaluation
features: [async-iteration]
flags: [generated, async]
info: |
ClassDeclaration : class BindingIdentifier ClassTail
1. Let className be StringValue of BindingIdentifier.
2. Let value be the result of ClassDefinitionEvaluation of ClassTail with
argument className.
[...]
14.5.14 Runtime Semantics: ClassDefinitionEvaluation
21. For each ClassElement m in order from methods
a. If IsStatic of m is false, then
i. Let status be the result of performing
PropertyDefinitionEvaluation for m with arguments proto and
false.
[...]
Runtime Semantics: PropertyDefinitionEvaluation
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters )
{ AsyncGeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true.
Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters,
AsyncGeneratorBody, scope, strict).
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
[...]
[...]
---*/
var initCount = 0;
function counter() {
initCount += 1;
}
var callCount = 0;
class C {
async *method({ w = counter(), x = counter(), y = counter(), z = counter() } = { w: null, x: 0, y: false, z: '' }) {
assert.sameValue(w, null);
assert.sameValue(x, 0);
assert.sameValue(y, false);
assert.sameValue(z, '');
assert.sameValue(initCount, 0);
callCount = callCount + 1;
}
};
new C().method().next().then(() => {
assert.sameValue(callCount, 1, 'invoked exactly once');
}).then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/class/dstr-async-gen-meth-dflt-obj-ptrn-id-init-skipped.js | JavaScript | bsd-2-clause | 2,395 |
/**
* 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.
*
* @format
* @flow
*/
'use strict';
const EventEmitter = require('../../vendor/emitter/EventEmitter');
const RCTDeviceEventEmitter = require('../RCTDeviceEventEmitter');
/**
* Mock the NativeEventEmitter as a normal JS EventEmitter.
*/
class NativeEventEmitter extends EventEmitter {
constructor() {
super(RCTDeviceEventEmitter.sharedSubscriber);
}
}
module.exports = NativeEventEmitter;
| exponentjs/react-native | Libraries/EventEmitter/__mocks__/NativeEventEmitter.js | JavaScript | bsd-3-clause | 592 |
/*!
* jQuery twitter bootstrap wizard plugin
* Examples and documentation at: http://github.com/VinceG/twitter-bootstrap-wizard
* version 1.0
* Requires jQuery v1.3.2 or later
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Authors: Vadim Vincent Gabriel (http://vadimg.com)
*/
;
(function ($) {
var bootstrapWizardCreate = function (element, options) {
var element = $(element);
var obj = this;
// Merge options with defaults
//var $settings = $.extend($.fn.bootstrapWizard.defaults, options || {});
var $settings = $.extend({}, $.fn.bootstrapWizard.defaults, options);
var $activeTab = null;
var $navigation = null;
this.fixNavigationButtons = function () {
// Get the current active tab
if (!$activeTab.length) {
// Select first one
$navigation.find('a:first').tab('show');
$activeTab = $navigation.find('li:first');
}
// See if we currently in the first then disable the previous and last buttons
if (obj.firstIndex() >= obj.currentIndex()) {
$('li.previous', element).addClass('disabled');
} else {
$('li.previous', element).removeClass('disabled');
}
if (obj.currentIndex() >= obj.navigationLength()) {
$('li.next', element).addClass('disabled');
} else {
$('li.next', element).removeClass('disabled');
}
if ($settings.onTabShow && typeof $settings.onTabShow === 'function' && $settings.onTabShow($activeTab, $navigation, obj.currentIndex()) === false) {
return false;
}
};
this.next = function (e) {
// If we clicked the last then dont activate this
if (element.hasClass('last')) {
return false;
}
if ($settings.onNext && typeof $settings.onNext === 'function' && $settings.onNext($activeTab, $navigation, obj.nextIndex()) === false) {
return false;
}
// Did we click the last button
$index = obj.nextIndex();
if ($index > obj.navigationLength()) {
} else {
$navigation.find('li:eq(' + $index + ') a').tab('show');
}
};
this.previous = function (e) {
// If we clicked the first then dont activate this
if (element.hasClass('first')) {
return false;
}
if ($settings.onPrevious && typeof $settings.onPrevious === 'function' && $settings.onPrevious($activeTab, $navigation, obj.previousIndex()) === false) {
return false;
}
$index = obj.previousIndex();
if ($index < 0) {
} else {
$navigation.find('li:eq(' + $index + ') a').tab('show');
}
};
this.first = function (e) {
if ($settings.onFirst && typeof $settings.onFirst === 'function' && $settings.onFirst($activeTab, $navigation, obj.firstIndex()) === false) {
return false;
}
// If the element is disabled then we won't do anything
if (element.hasClass('disabled')) {
return false;
}
$navigation.find('li:eq(0) a').tab('show');
};
this.last = function (e) {
if ($settings.onLast && typeof $settings.onLast === 'function' && $settings.onLast($activeTab, $navigation, obj.lastIndex()) === false) {
return false;
}
// If the element is disabled then we won't do anything
if (element.hasClass('disabled')) {
return false;
}
$navigation.find('li:eq(' + obj.navigationLength() + ') a').tab('show');
};
this.currentIndex = function () {
return $navigation.find('li').index($activeTab);
};
this.firstIndex = function () {
return 0;
};
this.lastIndex = function () {
return obj.navigationLength();
};
this.getIndex = function (elem) {
return $navigation.find('li').index(elem);
};
this.nextIndex = function () {
return $navigation.find('li').index($activeTab) + 1;
};
this.previousIndex = function () {
return $navigation.find('li').index($activeTab) - 1;
};
this.navigationLength = function () {
return $navigation.find('li').length - 1;
};
this.activeTab = function () {
return $activeTab;
};
this.nextTab = function () {
return $navigation.find('li:eq(' + (obj.currentIndex() + 1) + ')').length ? $navigation.find('li:eq(' + (obj.currentIndex() + 1) + ')') : null;
};
this.previousTab = function () {
if (obj.currentIndex() <= 0) {
return null;
}
return $navigation.find('li:eq(' + parseInt(obj.currentIndex() - 1) + ')');
};
$navigation = element.find('ul:first', element);
$activeTab = $navigation.find('li.active', element);
if (!$navigation.hasClass($settings.class)) {
$navigation.addClass($settings.class);
}
// Load onShow
if ($settings.onInit && typeof $settings.onInit === 'function') {
$settings.onInit($activeTab, $navigation, 0);
}
// Next/Previous events
$($settings.nextSelector, element).bind('click', obj.next);
$($settings.previousSelector, element).bind('click', obj.previous);
$($settings.lastSelector, element).bind('click', obj.last);
$($settings.firstSelector, element).bind('click', obj.first);
// Load onShow
if ($settings.onShow && typeof $settings.onShow === 'function') {
$settings.onShow($activeTab, $navigation, obj.nextIndex());
}
// Work the next/previous buttons
obj.fixNavigationButtons();
$('a[data-toggle="tab"]', element).on('click', function (e) {
if ($settings.onTabClick && typeof $settings.onTabClick === 'function' && $settings.onTabClick($activeTab, $navigation, obj.currentIndex()) === false) {
return false;
}
});
$('a[data-toggle="tab"]', element).on('show', function (e) {
$element = $(e.target).parent();
// If it's disabled then do not change
if ($element.hasClass('disabled')) {
return false;
}
$activeTab = $element; // activated tab
obj.fixNavigationButtons();
});
};
$.fn.bootstrapWizard = function (options) {
return this.each(function (index) {
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('bootstrapWizard')) return;
// pass options to plugin constructor
var wizard = new bootstrapWizardCreate(element, options);
// Store plugin object in this element's data
element.data('bootstrapWizard', wizard);
});
};
// expose options
$.fn.bootstrapWizard.defaults = {
'class':'nav nav-pills',
'nextSelector':'.wizard li.next',
'previousSelector':'.wizard li.previous',
'firstSelector':'.wizard li.first',
'lastSelector':'.wizard li.last',
'onShow':null,
'onInit':null,
'onNext':null,
'onPrevious':null,
'onLast':null,
'onFirst':null,
'onTabClick':null,
'onTabShow':null
};
})(jQuery);
| flesch91/uaweb-work.github.com | web/booster-install/assets/js/jquery.bootstrap.wizard.js | JavaScript | bsd-3-clause | 7,891 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
__ace_shadowed__.define('ace/mode/ruby', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ruby_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/folding/coffee'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var FoldMode = require("./folding/coffee").FoldMode;
var Mode = function() {
this.HighlightRules = RubyHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "#";
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/);
var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/);
var startingConditional = line.match(/^\s*(if|else)\s*/)
if (match || startingClassOrMethod || startingDoBlock || startingConditional) {
indent += tab;
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return /^\s+end$/.test(line + input) || /^\s+}$/.test(line + input) || /^\s+else$/.test(line + input);
};
this.autoOutdent = function(state, doc, row) {
var indent = this.$getIndent(doc.getLine(row));
var tab = doc.getTabString();
if (indent.slice(-tab.length) == tab)
doc.remove(new Range(row, indent.length-tab.length, row, indent.length));
};
this.$id = "ace/mode/ruby";
}).call(Mode.prototype);
exports.Mode = Mode;
});
__ace_shadowed__.define('ace/mode/ruby_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var constantOtherSymbol = exports.constantOtherSymbol = {
token : "constant.other.symbol.ruby", // symbol
regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?"
};
var qString = exports.qString = {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
};
var qqString = exports.qqString = {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
};
var tString = exports.tString = {
token : "string", // backtick string
regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]"
};
var constantNumericHex = exports.constantNumericHex = {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b"
};
var constantNumericFloat = exports.constantNumericFloat = {
token : "constant.numeric", // float
regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b"
};
var RubyHighlightRules = function() {
var builtinFunctions = (
"abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" +
"assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" +
"assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" +
"assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" +
"assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" +
"assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" +
"attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" +
"caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" +
"exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" +
"gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" +
"link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" +
"p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" +
"raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" +
"set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" +
"throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" +
"render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" +
"content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" +
"fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" +
"time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" +
"select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" +
"file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" +
"protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" +
"send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" +
"validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" +
"validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" +
"authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" +
"filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" +
"translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" +
"cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" +
"has_many|has_one|belongs_to|has_and_belongs_to_many"
);
var keywords = (
"alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" +
"__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" +
"redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield"
);
var buildinConstants = (
"true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" +
"RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING"
);
var builtinVariables = (
"\$DEBUG|\$defout|\$FILENAME|\$LOAD_PATH|\$SAFE|\$stdin|\$stdout|\$stderr|\$VERBOSE|" +
"$!|root_url|flash|session|cookies|params|request|response|logger|self"
);
var keywordMapper = this.$keywords = this.createKeywordMapper({
"keyword": keywords,
"constant.language": buildinConstants,
"variable.language": builtinVariables,
"support.function": builtinFunctions,
"invalid.deprecated": "debugger" // TODO is this a remnant from js mode?
}, "identifier");
this.$rules = {
"start" : [
{
token : "comment",
regex : "#.*$"
}, {
token : "comment", // multi line comment
regex : "^=begin(?:$|\\s.*$)",
next : "comment"
}, {
token : "string.regexp",
regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
},
qString,
qqString,
tString,
{
token : "text", // namespaces aren't symbols
regex : "::"
}, {
token : "variable.instance", // instance variable
regex : "@{1,2}[a-zA-Z_\\d]+"
}, {
token : "support.class", // class name
regex : "[A-Z][a-zA-Z_\\d]+"
},
constantOtherSymbol,
constantNumericHex,
constantNumericFloat,
{
token : "constant.language.boolean",
regex : "(?:true|false)\\b"
}, {
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "punctuation.separator.key-value",
regex : "=>"
}, {
stateName: "heredoc",
onMatch : function(value, currentState, stack) {
var next = value[2] == '-' ? "indentedHeredoc" : "heredoc";
var tokens = value.split(this.splitRegex);
stack.push(next, tokens[3]);
return [
{type:"constant", value: tokens[1]},
{type:"string", value: tokens[2]},
{type:"support.class", value: tokens[3]},
{type:"string", value: tokens[4]}
];
},
regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)",
rules: {
heredoc: [{
onMatch: function(value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}],
indentedHeredoc: [{
token: "string",
regex: "^ +"
}, {
onMatch: function(value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}]
}
}, {
regex : "$",
token : "empty",
next : function(currentState, stack) {
if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc")
return stack[0];
return currentState;
}
}, {
token : "keyword.operator",
regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : "^=end(?:$|\\s.*$)",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
]
};
this.normalizeRules();
};
oop.inherits(RubyHighlightRules, TextHighlightRules);
exports.RubyHighlightRules = RubyHighlightRules;
});
__ace_shadowed__.define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
__ace_shadowed__.define('ace/mode/folding/coffee', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) {
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidgetRange = function(session, foldStyle, row) {
var range = this.indentationBlock(session, row);
if (range)
return range;
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1 || line[startLevel] != "#")
return;
var startColumn = line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
line = session.getLine(row);
var level = line.search(re);
if (level == -1)
continue;
if (line[level] != "#")
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
var indent = line.search(/\S/);
var next = session.getLine(row + 1);
var prev = session.getLine(row - 1);
var prevIndent = prev.search(/\S/);
var nextIndent = next.search(/\S/);
if (indent == -1) {
session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : "";
return "";
}
if (prevIndent == -1) {
if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") {
session.foldWidgets[row - 1] = "";
session.foldWidgets[row + 1] = "";
return "start";
}
} else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") {
if (session.getLine(row - 2).search(/\S/) == -1) {
session.foldWidgets[row - 1] = "start";
session.foldWidgets[row + 1] = "";
return "";
}
}
if (prevIndent!= -1 && prevIndent < indent)
session.foldWidgets[row - 1] = "start";
else
session.foldWidgets[row - 1] = "";
if (indent < nextIndent)
return "start";
else
return "";
};
}).call(FoldMode.prototype);
});
| kang/ace-builds | textarea/src/mode-ruby.js | JavaScript | bsd-3-clause | 17,646 |
'use strict';
// Load modules
const Http = require('http');
const Stream = require('stream');
// Declare internals
const internals = {};
exports = module.exports = class Response extends Http.ServerResponse {
constructor(req, onEnd) {
super({ method: req.method, httpVersionMajor: 1, httpVersionMinor: 1 });
this._shot = { headers: null, trailers: {}, payloadChunks: [] };
this._headers = {}; // This forces node@8 to always render the headers
this.assignSocket(internals.nullSocket());
this.once('finish', () => {
const res = internals.payload(this);
res.raw.req = req;
process.nextTick(() => onEnd(res));
});
}
writeHead() {
const result = super.writeHead.apply(this, arguments);
this._shot.headers = Object.assign({}, this._headers); // Should be .getHeaders() since node v7.7
// Add raw headers
['Date', 'Connection', 'Transfer-Encoding'].forEach((name) => {
const regex = new RegExp('\\r\\n' + name + ': ([^\\r]*)\\r\\n');
const field = this._header.match(regex);
if (field) {
this._shot.headers[name.toLowerCase()] = field[1];
}
});
return result;
}
write(data, encoding, callback) {
super.write(data, encoding, callback);
this._shot.payloadChunks.push(new Buffer(data, encoding));
return true; // Write always returns false when disconnected
}
end(data, encoding, callback) {
if (data) {
this.write(data, encoding);
}
super.end(callback);
this.emit('finish');
}
destroy() {
}
addTrailers(trailers) {
for (const key in trailers) {
this._shot.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim();
}
}
};
internals.payload = function (response) {
// Prepare response object
const res = {
raw: {
res: response
},
headers: response._shot.headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
trailers: {}
};
// Prepare payload and trailers
const rawBuffer = Buffer.concat(response._shot.payloadChunks);
res.rawPayload = rawBuffer;
res.payload = rawBuffer.toString();
res.trailers = response._shot.trailers;
return res;
};
// Throws away all written data to prevent response from buffering payload
internals.nullSocket = function () {
return new Stream.Writable({
write(chunk, encoding, callback) {
setImmediate(callback);
}
});
};
| shikun2014010800/manga | web/backend/node_modules/shot/lib/response.js | JavaScript | mit | 2,749 |
var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var os = require('os')
var win32 = os.platform() === 'win32'
var noop = function () {}
var echo = function (name) {
return name
}
var normalize = !win32 ? echo : function (name) {
return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}
var statAll = function (fs, stat, cwd, ignore, entries, sort) {
var queue = entries || ['.']
return function loop (callback) {
if (!queue.length) return callback()
var next = queue.shift()
var nextAbs = path.join(cwd, next)
stat(nextAbs, function (err, stat) {
if (err) return callback(err)
if (!stat.isDirectory()) return callback(null, next, stat)
fs.readdir(nextAbs, function (err, files) {
if (err) return callback(err)
if (sort) files.sort()
for (var i = 0; i < files.length; i++) {
if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
}
callback(null, next, stat)
})
})
}
}
var strip = function (map, level) {
return function (header) {
header.name = header.name.split('/').slice(level).join('/')
var linkname = header.linkname
if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
header.linkname = linkname.split('/').slice(level).join('/')
}
return map(header)
}
}
exports.pack = function (cwd, opts) {
if (!cwd) cwd = '.'
if (!opts) opts = {}
var xfs = opts.fs || fs
var ignore = opts.ignore || opts.filter || noop
var map = opts.map || noop
var mapStream = opts.mapStream || echo
var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
var strict = opts.strict !== false
var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
var pack = opts.pack || tar.pack()
var finish = opts.finish || noop
if (opts.strip) map = strip(map, opts.strip)
if (opts.readable) {
dmode |= parseInt(555, 8)
fmode |= parseInt(444, 8)
}
if (opts.writable) {
dmode |= parseInt(333, 8)
fmode |= parseInt(222, 8)
}
var onsymlink = function (filename, header) {
xfs.readlink(path.join(cwd, filename), function (err, linkname) {
if (err) return pack.destroy(err)
header.linkname = normalize(linkname)
pack.entry(header, onnextentry)
})
}
var onstat = function (err, filename, stat) {
if (err) return pack.destroy(err)
if (!filename) {
if (opts.finalize !== false) pack.finalize()
return finish(pack)
}
if (stat.isSocket()) return onnextentry() // tar does not support sockets...
var header = {
name: normalize(filename),
mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
mtime: stat.mtime,
size: stat.size,
type: 'file',
uid: stat.uid,
gid: stat.gid
}
if (stat.isDirectory()) {
header.size = 0
header.type = 'directory'
header = map(header) || header
return pack.entry(header, onnextentry)
}
if (stat.isSymbolicLink()) {
header.size = 0
header.type = 'symlink'
header = map(header) || header
return onsymlink(filename, header)
}
// TODO: add fifo etc...
header = map(header) || header
if (!stat.isFile()) {
if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
return onnextentry()
}
var entry = pack.entry(header, onnextentry)
if (!entry) return
var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)
rs.on('error', function (err) { // always forward errors on destroy
entry.destroy(err)
})
pump(rs, entry)
}
var onnextentry = function (err) {
if (err) return pack.destroy(err)
statNext(onstat)
}
onnextentry()
return pack
}
var head = function (list) {
return list.length ? list[list.length - 1] : null
}
var processGetuid = function () {
return process.getuid ? process.getuid() : -1
}
var processUmask = function () {
return process.umask ? process.umask() : 0
}
exports.extract = function (cwd, opts) {
if (!cwd) cwd = '.'
if (!opts) opts = {}
var xfs = opts.fs || fs
var ignore = opts.ignore || opts.filter || noop
var map = opts.map || noop
var mapStream = opts.mapStream || echo
var own = opts.chown !== false && !win32 && processGetuid() === 0
var extract = opts.extract || tar.extract()
var stack = []
var now = new Date()
var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
var strict = opts.strict !== false
if (opts.strip) map = strip(map, opts.strip)
if (opts.readable) {
dmode |= parseInt(555, 8)
fmode |= parseInt(444, 8)
}
if (opts.writable) {
dmode |= parseInt(333, 8)
fmode |= parseInt(222, 8)
}
var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
var top
while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
if (!top) return cb()
xfs.utimes(top[0], now, top[1], cb)
}
var utimes = function (name, header, cb) {
if (opts.utimes === false) return cb()
if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?
xfs.utimes(name, now, header.mtime, function (err) {
if (err) return cb(err)
utimesParent(name, cb)
})
}
var chperm = function (name, header, cb) {
var link = header.type === 'symlink'
var chmod = link ? xfs.lchmod : xfs.chmod
var chown = link ? xfs.lchown : xfs.chown
if (!chmod) return cb()
var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
chmod(name, mode, function (err) {
if (err) return cb(err)
if (!own) return cb()
if (!chown) return cb()
chown(name, header.uid, header.gid, cb)
})
}
extract.on('entry', function (header, stream, next) {
header = map(header) || header
header.name = normalize(header.name)
var name = path.join(cwd, path.join('/', header.name))
if (ignore(name, header)) {
stream.resume()
return next()
}
var stat = function (err) {
if (err) return next(err)
utimes(name, header, function (err) {
if (err) return next(err)
if (win32) return next()
chperm(name, header, next)
})
}
var onsymlink = function () {
if (win32) return next() // skip symlinks on win for now before it can be tested
xfs.unlink(name, function () {
xfs.symlink(header.linkname, name, stat)
})
}
var onlink = function () {
if (win32) return next() // skip links on win for now before it can be tested
xfs.unlink(name, function () {
var srcpath = path.join(cwd, path.join('/', header.linkname))
xfs.link(srcpath, name, function (err) {
if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
stream = xfs.createReadStream(srcpath)
return onfile()
}
stat(err)
})
})
}
var onfile = function () {
var ws = xfs.createWriteStream(name)
var rs = mapStream(stream, header)
ws.on('error', function (err) { // always forward errors on destroy
rs.destroy(err)
})
pump(rs, ws, function (err) {
if (err) return next(err)
ws.on('close', stat)
})
}
if (header.type === 'directory') {
stack.push([name, header.mtime])
return mkdirfix(name, {
fs: xfs, own: own, uid: header.uid, gid: header.gid
}, stat)
}
var dir = path.dirname(name)
validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
if (err) return next(err)
if (!valid) return next(new Error(dir + ' is not a valid path'))
mkdirfix(dir, {
fs: xfs, own: own, uid: header.uid, gid: header.gid
}, function (err) {
if (err) return next(err)
switch (header.type) {
case 'file': return onfile()
case 'link': return onlink()
case 'symlink': return onsymlink()
}
if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))
stream.resume()
next()
})
})
})
if (opts.finish) extract.on('finish', opts.finish)
return extract
}
function validate (fs, name, root, cb) {
if (name === root) return cb(null, true)
fs.lstat(name, function (err, st) {
if (err && err.code !== 'ENOENT') return cb(err)
if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
cb(null, false)
})
}
function mkdirfix (name, opts, cb) {
mkdirp(name, {fs: opts.fs}, function (err, made) {
if (!err && made && opts.own) {
chownr(made, opts.uid, opts.gid, cb)
} else {
cb(err)
}
})
}
| february29/Learning | web/vue/AccountBook-Express/node_modules/.staging/tar-fs-f8fd0786/index.js | JavaScript | mit | 9,349 |
"use strict";
// local import of the exported AngularPage class
var angularPage_1 = require('./angularPage');
// The jasmine typings are brought in via DefinitelyTyped ambient typings.
describe('angularjs homepage', function () {
it('should greet the named user', function () {
var angularHomepage = new angularPage_1.AngularHomepage();
angularHomepage.get();
angularHomepage.setName('Julie');
expect(angularHomepage.getGreeting()).toEqual('Hello Julie!');
});
});
| bhavateja/Developer-Test-Angular-JS-Web-App | node_modules/protractor/built/spec/install/node_modules/protractor/exampleTypescript/specPageObjects.js | JavaScript | mit | 505 |
import answer from './answer';
var answer2 = answer;
export default answer2;
| lukeapage/rollup | test/function/statement-order/main.js | JavaScript | mit | 77 |
import { Quaternion } from '../math/Quaternion';
import { Vector3 } from '../math/Vector3';
import { Matrix4 } from '../math/Matrix4';
import { EventDispatcher } from './EventDispatcher';
import { Euler } from '../math/Euler';
import { Layers } from './Layers';
import { Matrix3 } from '../math/Matrix3';
import { _Math } from '../math/Math';
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author elephantatwork / www.elephantatwork.ch
*/
var object3DId = 0;
function Object3D() {
Object.defineProperty( this, 'id', { value: object3DId ++ } );
this.uuid = _Math.generateUUID();
this.name = '';
this.type = 'Object3D';
this.parent = null;
this.children = [];
this.up = Object3D.DefaultUp.clone();
var position = new Vector3();
var rotation = new Euler();
var quaternion = new Quaternion();
var scale = new Vector3( 1, 1, 1 );
function onRotationChange() {
quaternion.setFromEuler( rotation, false );
}
function onQuaternionChange() {
rotation.setFromQuaternion( quaternion, undefined, false );
}
rotation.onChange( onRotationChange );
quaternion.onChange( onQuaternionChange );
Object.defineProperties( this, {
position: {
enumerable: true,
value: position
},
rotation: {
enumerable: true,
value: rotation
},
quaternion: {
enumerable: true,
value: quaternion
},
scale: {
enumerable: true,
value: scale
},
modelViewMatrix: {
value: new Matrix4()
},
normalMatrix: {
value: new Matrix3()
}
} );
this.matrix = new Matrix4();
this.matrixWorld = new Matrix4();
this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
this.matrixWorldNeedsUpdate = false;
this.layers = new Layers();
this.visible = true;
this.castShadow = false;
this.receiveShadow = false;
this.frustumCulled = true;
this.renderOrder = 0;
this.userData = {};
}
Object3D.DefaultUp = new Vector3( 0, 1, 0 );
Object3D.DefaultMatrixAutoUpdate = true;
Object.assign( Object3D.prototype, EventDispatcher.prototype, {
isObject3D: true,
onBeforeRender: function () {},
onAfterRender: function () {},
applyMatrix: function ( matrix ) {
this.matrix.multiplyMatrices( matrix, this.matrix );
this.matrix.decompose( this.position, this.quaternion, this.scale );
},
applyQuaternion: function ( q ) {
this.quaternion.premultiply( q );
return this;
},
setRotationFromAxisAngle: function ( axis, angle ) {
// assumes axis is normalized
this.quaternion.setFromAxisAngle( axis, angle );
},
setRotationFromEuler: function ( euler ) {
this.quaternion.setFromEuler( euler, true );
},
setRotationFromMatrix: function ( m ) {
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
this.quaternion.setFromRotationMatrix( m );
},
setRotationFromQuaternion: function ( q ) {
// assumes q is normalized
this.quaternion.copy( q );
},
rotateOnAxis: function () {
// rotate object on axis in object space
// axis is assumed to be normalized
var q1 = new Quaternion();
return function rotateOnAxis( axis, angle ) {
q1.setFromAxisAngle( axis, angle );
this.quaternion.multiply( q1 );
return this;
};
}(),
rotateX: function () {
var v1 = new Vector3( 1, 0, 0 );
return function rotateX( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
rotateY: function () {
var v1 = new Vector3( 0, 1, 0 );
return function rotateY( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
rotateZ: function () {
var v1 = new Vector3( 0, 0, 1 );
return function rotateZ( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
translateOnAxis: function () {
// translate object by distance along axis in object space
// axis is assumed to be normalized
var v1 = new Vector3();
return function translateOnAxis( axis, distance ) {
v1.copy( axis ).applyQuaternion( this.quaternion );
this.position.add( v1.multiplyScalar( distance ) );
return this;
};
}(),
translateX: function () {
var v1 = new Vector3( 1, 0, 0 );
return function translateX( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
translateY: function () {
var v1 = new Vector3( 0, 1, 0 );
return function translateY( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
translateZ: function () {
var v1 = new Vector3( 0, 0, 1 );
return function translateZ( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
localToWorld: function ( vector ) {
return vector.applyMatrix4( this.matrixWorld );
},
worldToLocal: function () {
var m1 = new Matrix4();
return function worldToLocal( vector ) {
return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
};
}(),
lookAt: function () {
// This method does not support objects with rotated and/or translated parent(s)
var m1 = new Matrix4();
return function lookAt( vector ) {
if ( this.isCamera ) {
m1.lookAt( this.position, vector, this.up );
} else {
m1.lookAt( vector, this.position, this.up );
}
this.quaternion.setFromRotationMatrix( m1 );
};
}(),
add: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.add( arguments[ i ] );
}
return this;
}
if ( object === this ) {
console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
return this;
}
if ( ( object && object.isObject3D ) ) {
if ( object.parent !== null ) {
object.parent.remove( object );
}
object.parent = this;
object.dispatchEvent( { type: 'added' } );
this.children.push( object );
} else {
console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
}
return this;
},
remove: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.remove( arguments[ i ] );
}
return this;
}
var index = this.children.indexOf( object );
if ( index !== - 1 ) {
object.parent = null;
object.dispatchEvent( { type: 'removed' } );
this.children.splice( index, 1 );
}
return this;
},
getObjectById: function ( id ) {
return this.getObjectByProperty( 'id', id );
},
getObjectByName: function ( name ) {
return this.getObjectByProperty( 'name', name );
},
getObjectByProperty: function ( name, value ) {
if ( this[ name ] === value ) return this;
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
var object = child.getObjectByProperty( name, value );
if ( object !== undefined ) {
return object;
}
}
return undefined;
},
getWorldPosition: function ( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.updateMatrixWorld( true );
return result.setFromMatrixPosition( this.matrixWorld );
},
getWorldQuaternion: function () {
var position = new Vector3();
var scale = new Vector3();
return function getWorldQuaternion( optionalTarget ) {
var result = optionalTarget || new Quaternion();
this.updateMatrixWorld( true );
this.matrixWorld.decompose( position, result, scale );
return result;
};
}(),
getWorldRotation: function () {
var quaternion = new Quaternion();
return function getWorldRotation( optionalTarget ) {
var result = optionalTarget || new Euler();
this.getWorldQuaternion( quaternion );
return result.setFromQuaternion( quaternion, this.rotation.order, false );
};
}(),
getWorldScale: function () {
var position = new Vector3();
var quaternion = new Quaternion();
return function getWorldScale( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.updateMatrixWorld( true );
this.matrixWorld.decompose( position, quaternion, result );
return result;
};
}(),
getWorldDirection: function () {
var quaternion = new Quaternion();
return function getWorldDirection( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.getWorldQuaternion( quaternion );
return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
};
}(),
raycast: function () {},
traverse: function ( callback ) {
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverse( callback );
}
},
traverseVisible: function ( callback ) {
if ( this.visible === false ) return;
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverseVisible( callback );
}
},
traverseAncestors: function ( callback ) {
var parent = this.parent;
if ( parent !== null ) {
callback( parent );
parent.traverseAncestors( callback );
}
},
updateMatrix: function () {
this.matrix.compose( this.position, this.quaternion, this.scale );
this.matrixWorldNeedsUpdate = true;
},
updateMatrixWorld: function ( force ) {
if ( this.matrixAutoUpdate ) this.updateMatrix();
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent === null ) {
this.matrixWorld.copy( this.matrix );
} else {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].updateMatrixWorld( force );
}
},
toJSON: function ( meta ) {
// meta is '' when called from JSON.stringify
var isRootObject = ( meta === undefined || meta === '' );
var output = {};
// meta is a hash used to collect geometries, materials.
// not providing it implies that this is the root object
// being serialized.
if ( isRootObject ) {
// initialize meta obj
meta = {
geometries: {},
materials: {},
textures: {},
images: {}
};
output.metadata = {
version: 4.5,
type: 'Object',
generator: 'Object3D.toJSON'
};
}
// standard Object3D serialization
var object = {};
object.uuid = this.uuid;
object.type = this.type;
if ( this.name !== '' ) object.name = this.name;
if ( this.castShadow === true ) object.castShadow = true;
if ( this.receiveShadow === true ) object.receiveShadow = true;
if ( this.visible === false ) object.visible = false;
if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
object.matrix = this.matrix.toArray();
//
function serialize( library, element ) {
if ( library[ element.uuid ] === undefined ) {
library[ element.uuid ] = element.toJSON( meta );
}
return element.uuid;
}
if ( this.geometry !== undefined ) {
object.geometry = serialize( meta.geometries, this.geometry );
}
if ( this.material !== undefined ) {
if ( Array.isArray( this.material ) ) {
var uuids = [];
for ( var i = 0, l = this.material.length; i < l; i ++ ) {
uuids.push( serialize( meta.materials, this.material[ i ] ) );
}
object.material = uuids;
} else {
object.material = serialize( meta.materials, this.material );
}
}
//
if ( this.children.length > 0 ) {
object.children = [];
for ( var i = 0; i < this.children.length; i ++ ) {
object.children.push( this.children[ i ].toJSON( meta ).object );
}
}
if ( isRootObject ) {
var geometries = extractFromCache( meta.geometries );
var materials = extractFromCache( meta.materials );
var textures = extractFromCache( meta.textures );
var images = extractFromCache( meta.images );
if ( geometries.length > 0 ) output.geometries = geometries;
if ( materials.length > 0 ) output.materials = materials;
if ( textures.length > 0 ) output.textures = textures;
if ( images.length > 0 ) output.images = images;
}
output.object = object;
return output;
// extract data from the cache hash
// remove metadata on each item
// and return as array
function extractFromCache( cache ) {
var values = [];
for ( var key in cache ) {
var data = cache[ key ];
delete data.metadata;
values.push( data );
}
return values;
}
},
clone: function ( recursive ) {
return new this.constructor().copy( this, recursive );
},
copy: function ( source, recursive ) {
if ( recursive === undefined ) recursive = true;
this.name = source.name;
this.up.copy( source.up );
this.position.copy( source.position );
this.quaternion.copy( source.quaternion );
this.scale.copy( source.scale );
this.matrix.copy( source.matrix );
this.matrixWorld.copy( source.matrixWorld );
this.matrixAutoUpdate = source.matrixAutoUpdate;
this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
this.layers.mask = source.layers.mask;
this.visible = source.visible;
this.castShadow = source.castShadow;
this.receiveShadow = source.receiveShadow;
this.frustumCulled = source.frustumCulled;
this.renderOrder = source.renderOrder;
this.userData = JSON.parse( JSON.stringify( source.userData ) );
if ( recursive === true ) {
for ( var i = 0; i < source.children.length; i ++ ) {
var child = source.children[ i ];
this.add( child.clone() );
}
}
return this;
}
} );
export { Object3D };
| carlosanunes/three.js | src/core/Object3D.js | JavaScript | mit | 13,558 |
export default window['%testCafeAutomation%'];
| AlexanderMoskovkin/testcafe | src/client/driver/deps/testcafe-automation.js | JavaScript | mit | 47 |
// sensible server which advertises itself via Bonjour
// NODE INCLUDES
var dgram = require ("dgram");
var fs = require ("fs");
var http = require ("http");
var os = require ("os");
var url = require ("url");
// REGULAR JS INCLUDES
// assume that sensible.js lives in the same directory as our mainline
var code = fs.readFileSync (require ("path").dirname (process.argv [1]) + "/sensible.js");
eval (code.toString ());
// MAINLINE
sensible.ApplicationFactory.createApplication
(
function (inError)
{
if (inError)
{
console.error ("error during sensible application startup");
console.error (inError);
}
else
{
console.log ("sensible application startup");
}
}
);
// called just before sensible.Application.start()
sensible.node.Application.prototype.onBeforeStart = function (inCallback)
{
console.log ("node.Application.onBeforeStart()");
inCallback ();
}
// called just after sensible.Application.start()
sensible.node.Application.prototype.onAfterStart = function (inCallback)
{
console.log ("node.Application.onAfterStart()");
inCallback ();
}
| gbraad/sensible | apps/node/waiter/sensible-app.js | JavaScript | mit | 1,089 |
/**
* @fileoverview Restrict usage of duplicate imports.
* @author Simen Bekkhus
* @copyright 2016 Simen Bekkhus. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/**
* Returns the name of the module imported or re-exported.
*
* @param {ASTNode} node - A node to get.
* @returns {string} the name of the module, or empty string if no name.
*/
function getValue(node) {
if (node && node.source && node.source.value) {
return node.source.value.trim();
}
return "";
}
/**
* Checks if the name of the import or export exists in the given array, and reports if so.
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {ASTNode} node - A node to get.
* @param {string} value - The name of the imported or exported module.
* @param {string[]} array - The array containing other imports or exports in the file.
* @param {string} message - A message to be reported after the name of the module
*
* @returns {void} No return value
*/
function checkAndReport(context, node, value, array, message) {
if (array.indexOf(value) !== -1) {
context.report({
node: node,
message: "'{{module}}' " + message,
data: {module: value}
});
}
}
/**
* @callback nodeCallback
* @param {ASTNode} node - A node to handle.
*/
/**
* Returns a function handling the imports of a given file
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {boolean} includeExports - Whether or not to check for exports in addition to imports.
* @param {string[]} importsInFile - The array containing other imports in the file.
* @param {string[]} exportsInFile - The array containing other exports in the file.
*
* @returns {nodeCallback} A function passed to ESLint to handle the statement.
*/
function handleImports(context, includeExports, importsInFile, exportsInFile) {
return function(node) {
var value = getValue(node);
if (value) {
checkAndReport(context, node, value, importsInFile, "import is duplicated.");
if (includeExports) {
checkAndReport(context, node, value, exportsInFile, "import is duplicated as export.");
}
importsInFile.push(value);
}
};
}
/**
* Returns a function handling the exports of a given file
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {string[]} importsInFile - The array containing other imports in the file.
* @param {string[]} exportsInFile - The array containing other exports in the file.
*
* @returns {nodeCallback} A function passed to ESLint to handle the statement.
*/
function handleExports(context, importsInFile, exportsInFile) {
return function(node) {
var value = getValue(node);
if (value) {
checkAndReport(context, node, value, exportsInFile, "export is duplicated.");
checkAndReport(context, node, value, importsInFile, "export is duplicated as import.");
exportsInFile.push(value);
}
};
}
module.exports = function(context) {
var includeExports = (context.options[0] || {}).includeExports,
importsInFile = [],
exportsInFile = [];
var handlers = {
"ImportDeclaration": handleImports(context, includeExports, importsInFile, exportsInFile)
};
if (includeExports) {
handlers.ExportNamedDeclaration = handleExports(context, importsInFile, exportsInFile);
handlers.ExportAllDeclaration = handleExports(context, importsInFile, exportsInFile);
}
return handlers;
};
module.exports.schema = [{
"type": "object",
"properties": {
"includeExports": {
"type": "boolean"
}
},
"additionalProperties": false
}];
| sauceSquatch/we_are_razorfish_experience | node_modules/eslint/lib/rules/no-duplicate-imports.js | JavaScript | mit | 4,014 |
import{generateUtilityClass,generateUtilityClasses}from"@material-ui/unstyled";export function getCardActionAreaUtilityClass(t){return generateUtilityClass("MuiCardActionArea",t)};var cardActionAreaClasses=generateUtilityClasses("MuiCardActionArea",["root","focusVisible","focusHighlight"]);export default cardActionAreaClasses; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.31/legacy/CardActionArea/cardActionAreaClasses.min.js | JavaScript | mit | 328 |
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var strings={prefixAgo:null,prefixFromNow:null,suffixAgo:"",suffixFromNow:"",seconds:"1m",minute:"1m",minutes:"%dm",hour:"1h",hours:"%dh",day:"1g",days:"%dg",month:"1me",months:"%dme",year:"1a",years:"%da",wordSeparator:" "},_default=strings;exports.default=_default; | cdnjs/cdnjs | ajax/libs/react-timeago/6.2.1/language-strings/it-short.min.js | JavaScript | mit | 358 |
module.exports={A:{A:{"1":"K C G E A B","16":"CB"},B:{"1":"D v Z I M H"},C:{"1":"0 1 2 3 5 6 7 y F J K C G E A B D v Z I M H N O P Q R S T U V W X Y x a b c d e f L h i j k l m n o p q r s t u z w TB SB","16":"VB"},D:{"1":"0 1 2 3 5 6 7 I M H N O P Q R S T U V W X Y x a b c d e f L h i j k l m n o p q r s t u z w HB g DB XB EB FB","16":"F J K C G E A B D v Z"},E:{"1":"J K C G E A B IB JB KB LB MB NB","16":"F GB AB"},F:{"1":"8 9 B D I M H N O P Q R S T U V W X Y x a b c d e f L h i j k l m n o p q r s t u UB BB","16":"E OB PB QB RB"},G:{"1":"4 G WB YB ZB aB bB cB dB eB fB gB","16":"AB"},H:{"1":"hB"},I:{"1":"4 y F g kB lB mB nB","16":"iB jB"},J:{"1":"C A"},K:{"1":"D L BB","16":"8 9 A B"},L:{"1":"g"},M:{"1":"w"},N:{"1":"A B"},O:{"1":"oB"},P:{"1":"F J pB"},Q:{"1":"qB"},R:{"1":"rB"}},B:5,C:"document.elementFromPoint()"};
| parkerjgit/openarch-d8 | themes/open_scratch/node_modules/caniuse-lite/data/features/element-from-point.js | JavaScript | gpl-2.0 | 828 |
// I18N constants
// LANG: "pl", ENCODING: UTF-8
// translated: Krzysztof Kotowicz [email protected]
{
"Align": "Wyrównanie",
"All four sides": "Wszystkie 4 strony",
"Background": "Tło",
"Baseline": "Linia bazowa",
"Border": "Ramka",
"Borders": "Ramki",
"Bottom": "Dół",
"Style [CSS]": "Styl [CSS]",
"CSS Style": "Styl CSS",
"Caption": "Podpis",
"Cell Properties": "Właściwości komórki",
"Center": "Środek",
"Char": "Znak",
"Collapsed borders": "Ramki skolapsowane",
"Color": "Kolor",
"Description": "Opis",
"FG Color": "Kolor czcionek",
"Float": "Opływanie",
"Frames": "Ramki zewn.",
"Frame and borders": "Obramowania",
"Height": "Wysokość",
"How many columns would you like to merge?": "Ile kolumn chcesz scalić?",
"How many rows would you like to merge?": "Ile wierszy chcesz scalić?",
"Image URL": "URL obrazka",
"Justify": "Wyjustuj",
"Layout": "Layout",
"Left": "Lewo",
"Margin": "Margines",
"Middle": "Środek",
"No rules": "Bez wewnętrzych",
"No sides": "Bez ramek",
"None": "Brak",
"Padding": "Wcięcia",
"Please click into some cell": "Kliknij w jakąś komórkę",
"Right": "Prawo",
"Row Properties": "Właściwości wiersza",
"Rules will appear between all rows and columns": "Linie będą widoczne pomiędzy kolumnami i wierszami",
"Rules will appear between columns only": "Linie będą widoczne tylko pomiędzy kolumnami",
"Rules will appear between rows only": "Linie będą widoczne tylko pomiędzy wierszami",
"Rules": "Linie wewn.",
"Spacing and padding": "Spacjowanie",
"Spacing": "Odstęp",
"Summary": "Podsumowanie",
"Delete cell": "Usuń komórkę",
"Insert cell after": "Wstaw komórkę po",
"Insert cell before": "Wstaw komórkę przed",
"Merge cells": "Scal komórki",
"Cell properties": "Właściwości komórki",
"Split cell": "Rozdziel komórkę",
"Delete column": "Usuń kolumnę",
"Insert column after": "Wstaw kolumnę po",
"Insert column before": "Wstaw kolumnę przed",
"Split column": "Rozdziel kolumnę",
"Delete row": "Usuń wiersz",
"Insert row before": "Wstaw wiersz przed",
"Insert row after": "Wstaw wiersz po",
"Row properties": "Właściwości wiersza",
"Split row": "Rozdziel wiersz",
"Table properties": "Właściwości tabeli",
"Table Properties": "Właściwości tabeli",
"Text align": "Wyr. w poziomie",
"The bottom side only": "Tylko dolna linia",
"The left-hand side only": "Tylko lewa linia",
"The right and left sides only": "Lewa i prawa linia",
"The right-hand side only": "Tylko prawa linia",
"The top and bottom sides only": "Górna i dolna linia",
"The top side only": "Tylko górna linia",
"Top": "Góra",
"Unset color": "Usuń kolor",
"Vertical align": "Wyr. w pionie",
"Width": "Szerokość",
"HTMLArea cowardly refuses to delete the last cell in row.": "Nie możesz skasować ostatniej komórki w wierszu.",
"HTMLArea cowardly refuses to delete the last column in table.": "Nie możesz skasować ostatniej kolumny w tabeli.",
"HTMLArea cowardly refuses to delete the last row in table.": "Nie możesz skasować ostatniego wiersza w tabeli.",
"percent": "%",
"pixels": "pikseli",
"OK": "OK",
"Cancel": "Anuluj"
};
| claunia/qemudb | xinha/plugins/TableOperations/lang/pl.js | JavaScript | gpl-2.0 | 3,246 |
define(["../../buildControl"], function(bc){
if(bc.stripConsole){
var consoleMethods = "assert|count|debug|dir|dirxml|group|groupEnd|info|profile|profileEnd|time|timeEnd|trace|log";
if(bc.stripConsole === "warn"){
consoleMethods += "|warn";
}else if(bc.stripConsole === "all"){
consoleMethods += "|warn|error";
}
// Match on "window.console" and plain "console" but not things like "myconsole" or "my.console"
var stripConsoleRe = new RegExp("([^\\w\\.]|^)((window.)?console\\.(" + consoleMethods + ")\\s*\\()", "g");
return function(text){
return text.replace(stripConsoleRe, "$1 0 && $2");
};
}else{
return function(text){
return text;
};
}
}); | avz-cmf/zaboy-middleware | www/js/util/build/transforms/optimizer/stripConsole.js | JavaScript | gpl-3.0 | 681 |
/**
* This file contains JS functionality required by mforms and is included automatically
* when required.
*/
// Namespace for the form bits and bobs
M.form = M.form || {};
/**
* Initialises the show advanced functionality and events.
* This should only ever happen ONCE per page.
*
* @param {YUI} Y
* @param {object} config
*/
M.form.initShowAdvanced = function(Y, config) {
if (M.form.showAdvanced) {
return M.form.showAdvanced;
}
var showAdvanced = function(config) {
showAdvanced.superclass.constructor.apply(this, arguments);
};
showAdvanced.prototype = {
_advButtons : [],
_advAreas : [],
_stateInput : null,
initializer : function() {
this._advAreas = Y.all('form .advanced');
this._advButtons = Y.all('.showadvancedbtn');
if (this._advButtons.size() > 0) {
this._stateInput = new Y.NodeList(document.getElementsByName('mform_showadvanced_last'));
this._advButtons.on('click', this.switchState, this);
}
},
/**
* Toggles between showing advanced items and hiding them.
* Should be fired by an event.
*/
switchState : function(e) {
e.preventDefault();
if (this._stateInput.get('value')=='1') {
this._stateInput.set('value', '0');
this._advButtons.setAttribute('value', M.str.form.showadvanced);
this._advAreas.addClass('hide');
} else {
this._stateInput.set('value', '1');
this._advButtons.setAttribute('value', M.str.form.hideadvanced);
this._advAreas.removeClass('hide');
}
}
};
// Extend it with the YUI widget fw.
Y.extend(showAdvanced, Y.Base, showAdvanced.prototype, {
NAME : 'mform-showAdvanced'
});
M.form.showAdvanced = new showAdvanced(config);
return M.form.showAdvanced;
};
/**
* Initialises a manager for a forms dependencies.
* This should happen once per form.
*/
M.form.initFormDependencies = function(Y, formid, dependencies) {
// If the dependencies isn't an array or object we don't want to
// know about it
if (!Y.Lang.isArray(dependencies) && !Y.Lang.isObject(dependencies)) {
return false;
}
/**
* Fixes an issue with YUI's processing method of form.elements property
* in Internet Explorer.
* http://yuilibrary.com/projects/yui3/ticket/2528030
*/
Y.Node.ATTRS.elements = {
getter: function() {
return Y.all(new Y.Array(this._node.elements, 0, true));
}
};
// Define the dependency manager if it hasn't already been defined.
M.form.dependencyManager = M.form.dependencyManager || (function(){
var dependencyManager = function(config) {
dependencyManager.superclass.constructor.apply(this, arguments);
};
dependencyManager.prototype = {
_form : null,
_depElements : [],
_nameCollections : [],
initializer : function(config) {
var i = 0, nodeName;
this._form = Y.one('#'+formid);
for (i in dependencies) {
this._depElements[i] = this.elementsByName(i);
if (this._depElements[i].size() == 0) {
continue;
}
this._depElements[i].each(function(node){
nodeName = node.get('nodeName').toUpperCase();
if (nodeName == 'INPUT') {
if (node.getAttribute('type').match(/^(button|submit|radio|checkbox)$/)) {
node.on('click', this.checkDependencies, this);
} else {
node.on('blur', this.checkDependencies, this);
}
node.on('change', this.checkDependencies, this);
} else if (nodeName == 'SELECT') {
node.on('change', this.checkDependencies, this);
} else {
node.on('click', this.checkDependencies, this);
node.on('blur', this.checkDependencies, this);
node.on('change', this.checkDependencies, this);
}
}, this);
}
this._form.get('elements').each(function(input){
if (input.getAttribute('type')=='reset') {
input.on('click', function(){
this._form.reset();
this.checkDependencies();
}, this);
}
}, this);
return this.checkDependencies(null);
},
/**
* Gets all elements in the form by thier name and returns
* a YUI NodeList
* @return Y.NodeList
*/
elementsByName : function(name) {
if (!this._nameCollections[name]) {
var elements = [];
this._form.get('elements').each(function(){
if (this.getAttribute('name') == name) {
elements.push(this);
}
});
this._nameCollections[name] = new Y.NodeList(elements);
}
return this._nameCollections[name];
},
/**
* Checks the dependencies the form has an makes any changes to the
* form that are required.
*
* Changes are made by functions title _dependency_{dependencytype}
* and more can easily be introduced by defining further functions.
*/
checkDependencies : function(e) {
var tolock = [],
tohide = [],
dependon, condition, value,
lock, hide, checkfunction, result;
for (dependon in dependencies) {
if (this._depElements[dependon].size() == 0) {
continue;
}
for (condition in dependencies[dependon]) {
for (value in dependencies[dependon][condition]) {
lock = false;
hide = false;
checkfunction = '_dependency_'+condition;
if (Y.Lang.isFunction(this[checkfunction])) {
result = this[checkfunction].apply(this, [this._depElements[dependon], value, e]);
} else {
result = this._dependency_default(this._depElements[dependon], value, e);
}
lock = result.lock || false;
hide = result.hide || false;
for (var ei in dependencies[dependon][condition][value]) {
var eltolock = dependencies[dependon][condition][value][ei];
if (hide) {
tohide[eltolock] = true;
}
if (tolock[eltolock] != null) {
tolock[eltolock] = lock || tolock[eltolock];
} else {
tolock[eltolock] = lock;
}
}
}
}
}
for (var el in tolock) {
this._disableElement(el, tolock[el]);
if (tohide.propertyIsEnumerable(el)) {
this._hideElement(el, tohide[el]);
}
}
return true;
},
/**
* Disabled all form elements with the given name
*/
_disableElement : function(name, disabled) {
var els = this.elementsByName(name);
els.each(function(){
if (disabled) {
this.setAttribute('disabled', 'disabled');
} else {
this.removeAttribute('disabled');
}
})
},
/**
* Hides all elements with the given name.
*/
_hideElement : function(name, hidden) {
var els = this.elementsByName(name);
els.each(function(){
var e = els.ancestor('.fitem');
if (e) {
e.setStyles({
display : (hidden)?'none':''
})
}
});
},
_dependency_notchecked : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && this.get('value') != value) {
return;
}
lock = lock || !Y.Node.getDOMNode(this).checked;
});
return {
lock : lock,
hide : false
}
},
_dependency_checked : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && this.get('value') != value) {
return;
}
lock = lock || Y.Node.getDOMNode(this).checked;
});
return {
lock : lock,
hide : false
}
},
_dependency_noitemselected : function(elements, value) {
var lock = false;
elements.each(function(){
lock = lock || this.get('selectedIndex') == -1;
});
return {
lock : lock,
hide : false
}
},
_dependency_eq : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && !Y.Node.getDOMNode(this).checked) {
return;
} else if (this.getAttribute('type').toLowerCase() == 'checkbox' && !Y.Node.getDOMNode(this).checked) {
return;
}
lock = lock || this.get('value') == value;
});
return {
lock : lock,
hide : false
}
},
_dependency_hide : function(elements, value) {
return {
lock : false,
hide : true
}
},
_dependency_default : function(elements, value, ev) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && !Y.Node.getDOMNode(this).checked) {
return;
} else if (this.getAttribute('type').toLowerCase() == 'checkbox' && !Y.Node.getDOMNode(this).checked) {
return;
}
lock = lock || this.get('value') != value;
});
return {
lock : lock,
hide : false
}
}
};
Y.extend(dependencyManager, Y.Base, dependencyManager.prototype, {
NAME : 'mform-dependency-manager'
});
return dependencyManager;
})();
return new M.form.dependencyManager();
}; | dhamma-dev/SEA | web/lib/form/form.js | JavaScript | gpl-3.0 | 12,220 |
/*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
*/
export default 'ALERT_SETTINGS';
| tomkralidis/geonode | geonode/monitoring/frontend/monitoring/src/pages/alerts-settings/constants.js | JavaScript | gpl-3.0 | 853 |
/**
* Model that represents our form template.
*
* @package Ninja Forms client
* @copyright (c) 2017 WP Ninjas
* @since 3.0
*/
define( [], function() {
var model = Backbone.Model.extend( {
defaults: {
objectType: 'template',
id: 'none',
title: 'unknown'
},
initialize: function() {
this.set( 'desc', this.get( 'template-desc' ) );
}
} );
return model;
} ); | dexxtr/osbb-web-manager | www/wp-content/plugins/ninja-forms/client/dashboard/models/formTemplateModel.js | JavaScript | gpl-3.0 | 441 |
/*
* Slimey - SLIdeshow Microformat Editor - http://slimey.sourceforge.net
* Copyright (C) 2007 - 2008 Ignacio de Soto
*
* Base Action definitions.
*/
/**
* abstract class SlimeyAction - Actions on the editor
* name: name of the action
*/
var SlimeyAction = function(name, slimey) {
this.name = name;
this.slimey = slimey;
}
/**
* returns the action's name.
*/
SlimeyAction.prototype.getName = function() {
return this.name;
}
/**
* base perform() implementation
*/
SlimeyAction.prototype.perform = function() {
}
/**
* base undo() implementation
*/
SlimeyAction.prototype.undo = function() {
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyInsertAction - Handles insertion of new elements
* tagname: HTML tagname of the element to be inserted
*/
var SlimeyInsertAction = function(slimey, tagname) {
SlimeyAction.call(this, 'insert', slimey);
var elem = this.slimey.editor.getContainer().ownerDocument.createElement(tagname);
/* set element attributes */
elem.slimey = this.slimey;
elem.className = 'slimeyElement';
elem.style.position = 'absolute';
elem.style.left = '40%';
elem.style.top = '30%';
elem.style.lineHeight = '1.';
elem.style.cursor = 'move';
elem.style.fontFamily = 'sans-serif';
elem.style.fontSize = '160%';
elem.style.margin = '0px';
elem.style.padding = '0px';
elem.style.border = '0px';
elem.style.zIndex = 10000;
if (elem.tagName == 'DIV') {
elem.style.left = '5%';
elem.style.top = '15%';
elem.style.width = '90%';
elem.style.height = '10%';
elem.innerHTML = lang("some text");
elem.style.textAlign = 'center';
elem.resizable = true;
elem.editable = true;
} else if (elem.tagName == 'IMG') {
elem.style.width = '20%';
elem.style.height = '20%';
elem.resizable = true;
elem.title = lang("drag the bottom right corner to resize");
} else {
if (elem.tagName == 'UL') {
elem.innerHTML = '<li>' + lang("some text") + '</li>';
} else if (elem.tagName == 'OL') {
elem.innerHTML = '<li>' + lang("some text") + '</li>';
} else {
elem.innerHTML = lang("some text");
}
elem.editable = true;
elem.title = lang("double click to edit content");
}
/* event handlers */
setEventHandler(elem, "mousedown", slimeyDrag);
setEventHandler(elem, "click", slimeyClick);
setEventHandler(elem, "dblclick", slimeyEdit);
setEventHandler(elem, "mouseover", slimeyHighlight);
setEventHandler(elem, "mouseout", slimeyLowshadow);
this.element = elem;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyInsertAction.prototype = new SlimeyAction();
/**
* returns the element created by this action
*/
SlimeyInsertAction.prototype.getElement = function() {
return this.element;
}
/**
* adds the created element to the editor
*/
SlimeyInsertAction.prototype.perform = function() {
this.slimey.editor.getContainer().appendChild(this.element);
}
/**
* removes the created element from the editor
*/
SlimeyInsertAction.prototype.undo = function() {
this.slimey.editor.getContainer().removeChild(this.element);
var selected = this.slimey.editor.getSelected();
if (selected == this.element) {
this.slimey.editor.deselect();
}
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyEditContentAction - edits the contents of the selected element in the editor
* content: HTML content to set to the element
*/
var SlimeyEditContentAction = function(slimey, content, element) {
SlimeyAction.call(this, 'editContent', slimey);
if (element) {
this.element = element;
} else {
this.element = this.slimey.editor.getSelected();
}
this.content = content;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyEditContentAction.prototype = new SlimeyAction();
/**
* edits the contents of the selected item in the editor
*/
SlimeyEditContentAction.prototype.perform = function() {
this.previousContent = this.element.innerHTML;
this.element.innerHTML = this.content;
}
/**
* restores the elements original content
*/
SlimeyEditContentAction.prototype.undo = function() {
this.element.innerHTML = this.previousContent;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyEditStyleAction - edits a style property of the selected element in the editor
* property: CSS property to be modified (i.e. fontFamily)
* value: Value to set to the property (i.e. sans-serif)
*/
var SlimeyEditStyleAction = function(slimey, property, value) {
SlimeyAction.call(this, 'editStyle', slimey);
this.element = this.slimey.editor.getSelected();
this.property = property;
this.value = value;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyEditStyleAction.prototype = new SlimeyAction();
/**
* edits the contents of the selected item in the editor
*/
SlimeyEditStyleAction.prototype.perform = function() {
this.previousValue = this.element.style[this.property];
this.element.style[this.property] = this.value;
}
/**
* restores the elements original content
*/
SlimeyEditStyleAction.prototype.undo = function() {
this.element.style[this.property] = this.previousValue;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyDeleteAction - Deletes the selected element
*/
var SlimeyDeleteAction = function(slimey) {
SlimeyAction.call(this, 'delete', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeyDeleteAction extends SlimeyAction
*/
SlimeyDeleteAction.prototype = new SlimeyAction();
/**
* removes the selected element from the editor
*/
SlimeyDeleteAction.prototype.perform = function() {
this.slimey.editor.getContainer().removeChild(this.element);
this.slimey.editor.deselect();
}
/**
* adds the previously deleted element to the editor
*/
SlimeyDeleteAction.prototype.undo = function() {
this.slimey.editor.getContainer().appendChild(this.element);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyMoveAction - Moves the selected element
* newx: new horizontal position
* newy: new vertical position
* oldx: (optional) previous horizontal position if different than current
* oldy: (optional) previous vertical position if different than current
*/
var SlimeyMoveAction = function(slimey, newx, newy, oldx, oldy) {
SlimeyAction.call(this, 'move', slimey);
var selected = this.slimey.editor.getSelected();
this.newx = newx;
this.newy = newy;
if (oldx) {
this.oldx = oldx;
} else {
this.oldx = selected.style.left;
}
if (oldy) {
this.oldy = oldy;
} else {
this.oldy = selected.style.top;
}
this.element = selected;
}
/**
* SlimeyMoveAction extends SlimeyAction
*/
SlimeyMoveAction.prototype = new SlimeyAction();
/**
* moves the selected element to the new position
*/
SlimeyMoveAction.prototype.perform = function() {
this.element.style.left = this.newx;
this.element.style.top = this.newy;
}
/**
* returns the moved element to its original position
*/
SlimeyMoveAction.prototype.undo = function() {
this.element.style.left = this.oldx;
this.element.style.top = this.oldy;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyResizeAction - Resizes the selected element
* neww: new width
* newh: new height
* oldw: (optional) previous width if different than current
* oldh: (optional) previous height if different than current
*/
var SlimeyResizeAction = function(slimey, neww, newh, oldw, oldh) {
SlimeyAction.call(this, 'resize', slimey);
var selected = this.slimey.editor.getSelected();
this.neww = neww;
this.newh = newh;
if (oldw) {
this.oldw = oldw;
} else {
this.oldw = selected.style.width;
}
if (oldh) {
this.oldh = oldh;
} else {
this.oldh = selected.style.height;
}
this.element = selected;
}
/**
* SlimeyResizeAction extends SlimeyAction
*/
SlimeyResizeAction.prototype = new SlimeyAction();
/**
* resizes the selected element
*/
SlimeyResizeAction.prototype.perform = function() {
this.element.style.width = this.neww;
this.element.style.height = this.newh;
}
/**
* returns the element to its original size
*/
SlimeyResizeAction.prototype.undo = function() {
this.element.style.width = this.oldw;
this.element.style.height = this.oldh;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeySendToBackAction - Sends the selected element to the back
*/
var SlimeySendToBackAction = function(slimey) {
SlimeyAction.call(this, 'sendToBack', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeySendToBackAction extends SlimeyAction
*/
SlimeySendToBackAction.prototype = new SlimeyAction();
/**
* sends the selected element to the back
*/
SlimeySendToBackAction.prototype.perform = function() {
var minZ = 100000000;
for (var elem = this.slimey.editor.getContainer().firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType == 1) {
thisZ = parseInt(elem.style.zIndex);
if (thisZ < minZ) {
minZ = thisZ;
}
}
}
this.oldZ = this.element.style.zIndex;
this.element.style.zIndex = minZ - 1;
}
/**
* sends the selected element back ot the previous z-index
*/
SlimeySendToBackAction.prototype.undo = function() {
this.element.style.zIndex = this.oldZ;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyBringToFrontAction - Brings the selected element to the front
*/
var SlimeyBringToFrontAction = function(slimey) {
SlimeyAction.call(this, 'bringToFront', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeyBringToFrontAction extends SlimeyAction
*/
SlimeyBringToFrontAction.prototype = new SlimeyAction();
/**
* brings the selected element to the front
*/
SlimeyBringToFrontAction.prototype.perform = function() {
var maxZ = 0;
for (var elem = this.slimey.editor.getContainer().firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType == 1) {
thisZ = parseInt(elem.style.zIndex);
if (thisZ > maxZ) {
maxZ = thisZ;
}
}
}
this.oldZ = this.element.style.zIndex;
this.element.style.zIndex = maxZ + 1;
}
/**
* returns the element to its original z-index
*/
SlimeyBringToFrontAction.prototype.undo = function() {
this.element.style.zIndex = this.oldZ;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyChangeSlideAction - Changes the current slide
* num: Slide number to change to
*/
var SlimeyChangeSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'changeSlide', slimey);
this.num = num;
}
/**
* SlimeyChangeSlideAction extends SlimeyAction
*/
SlimeyChangeSlideAction.prototype = new SlimeyAction();
/**
* changes the current slide
*/
SlimeyChangeSlideAction.prototype.perform = function() {
this.previousSlide = this.slimey.navigation.currentSlide;
this.slimey.navigation.getSlide(this.num);
}
/**
* returns to the previous slide
*/
SlimeyChangeSlideAction.prototype.undo = function() {
this.slimey.navigation.getSlide(this.previousSlide);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyInsertSlideAction - Inserts a new slide
* num: Position where to insert the new slide
*/
var SlimeyInsertSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'insertSlide', slimey);
this.num = num;
}
/**
* SlimeyInsertSlideAction extends SlimeyAction
*/
SlimeyInsertSlideAction.prototype = new SlimeyAction();
/**
* insert the new slide
*/
SlimeyInsertSlideAction.prototype.perform = function() {
this.slimey.navigation.insertNewSlide(this.num);
}
/**
* remove the inserted slide
*/
SlimeyInsertSlideAction.prototype.undo = function() {
this.slimey.navigation.deleteSlide(this.num);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyDeleteSlideAction - Deletes the current slide
* num: Number of the slide to be deleted
*/
var SlimeyDeleteSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'deleteSlide', slimey);
this.num = num;
}
/**
* SlimeyDeleteSlideAction extends SlimeyAction
*/
SlimeyDeleteSlideAction.prototype = new SlimeyAction();
/**
* delete the current slide
*/
SlimeyDeleteSlideAction.prototype.perform = function() {
this.html = this.slimey.editor.getHTML();
this.dom = document.createElement('div');
this.slimey.editor.getDOM(this.dom);
this.slimey.navigation.deleteSlide(this.num);
}
/**
* reinsert the deleted slide
*/
SlimeyDeleteSlideAction.prototype.undo = function() {
this.slimey.navigation.insertNewSlide(this.num, this.html, this.dom);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyMoveSlideAction - Moves the current slide to a new position
* from: Number of the slide to be moved
* to: The new position of the slide
*/
var SlimeyMoveSlideAction = function(slimey, from, to) {
SlimeyAction.call(this, 'moveSlide', slimey);
this.from = from;
this.to = to;
}
/**
* SlimeyMoveSlideAction extends SlimeyAction
*/
SlimeyMoveSlideAction.prototype = new SlimeyAction();
/**
* move the slide to the new position
*/
SlimeyMoveSlideAction.prototype.perform = function() {
this.slimey.navigation.moveSlide(this.from, this.to);
}
/**
* move the slide back to its original position
*/
SlimeyMoveSlideAction.prototype.undo = function() {
this.slimey.navigation.moveSlide(this.to, this.from);
}
/*---------------------------------------------------------------------------*/ | maestrano/fengoffice | public/assets/javascript/slimey/actions.js | JavaScript | agpl-3.0 | 14,292 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(249)
var __weex_template__ = __webpack_require__(250)
var __weex_style__ = __webpack_require__(251)
var __weex_script__ = __webpack_require__(252)
__weex_define__('@weex-component/81fdd9b8b8bce1b304791aba10e15462', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
__weex_bootstrap__('@weex-component/81fdd9b8b8bce1b304791aba10e15462',undefined,undefined)
/***/ },
/***/ 244:
/***/ function(module, exports) {
module.exports = {
"type": "image",
"style": {
"width": function () {return this.width},
"height": function () {return this.height}
},
"attr": {
"src": function () {return this.src},
"imageQuality": function () {return this.quality}
},
"events": {
"click": "_clickHandler"
}
}
/***/ },
/***/ 245:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
quality: 'normal',
width: 0,
height: 0,
src: '',
href: '',
spmc: 0,
spmd: 0
}},
methods: {
ready: function ready() {},
_clickHandler: function _clickHandler() {
this.$call('modal', 'toast', {
message: 'click',
duration: 1
});
}
}
};}
/* generated by weex-loader */
/***/ },
/***/ 246:
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(244)
var __weex_script__ = __webpack_require__(245)
__weex_define__('@weex-component/banner', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
})
/***/ },
/***/ 247:
/***/ function(module, exports) {
module.exports = {
"type": "container",
"children": [
{
"type": "container",
"shown": function () {return this.direction==='row'},
"style": {
"flexDirection": "row"
},
"children": [
{
"type": "container",
"repeat": function () {return this.ds},
"style": {
"width": function () {return this.width},
"height": function () {return this.height},
"marginLeft": function () {return this.space}
},
"children": [
{
"type": "banner",
"attr": {
"width": function () {return this.width},
"height": function () {return this.height},
"src": function () {return this.img},
"href": function () {return this.url}
}
}
]
}
]
},
{
"type": "container",
"shown": function () {return this.direction==='column'},
"children": [
{
"type": "container",
"repeat": function () {return this.ds},
"style": {
"width": function () {return this.width},
"height": function () {return this.height},
"marginTop": function () {return this.space}
},
"children": [
{
"type": "banner",
"attr": {
"width": function () {return this.width},
"height": function () {return this.height},
"src": function () {return this.img},
"href": function () {return this.url}
}
}
]
}
]
}
]
}
/***/ },
/***/ 248:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
space: 0,
width: 0,
height: 0,
spmc: 0,
spmdprefix: '',
ds: []
}},
methods: {
ready: function ready() {
var self = this;
var ds = self.ds;
var length = ds.length;
for (var i = 0; i < length; i++) {
var item = ds[i];
item.index = i;
item.space = i % length === 0 ? 0 : self.space;
}
}
}
};}
/* generated by weex-loader */
/***/ },
/***/ 249:
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(246)
var __weex_template__ = __webpack_require__(247)
var __weex_script__ = __webpack_require__(248)
__weex_define__('@weex-component/banners', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
})
/***/ },
/***/ 250:
/***/ function(module, exports) {
module.exports = {
"type": "container",
"classList": [
"container"
],
"children": [
{
"type": "image",
"shown": function () {return this.ds.floorTitle},
"classList": [
"title"
],
"attr": {
"src": function () {return this.ds.floorTitle}
}
},
{
"type": "container",
"style": {
"marginLeft": 4,
"marginRight": 4
},
"children": [
{
"type": "banners",
"attr": {
"ds": function () {return this.bannerItems},
"direction": "column",
"width": function () {return this.NUMBER_742},
"height": function () {return this.NUMBER_230},
"space": function () {return this.NUMBER_4}
}
}
]
}
]
}
/***/ },
/***/ 251:
/***/ function(module, exports) {
module.exports = {
"title": {
"width": 750,
"height": 100
},
"container": {
"marginBottom": 4,
"backgroundColor": "#C0BABC"
}
}
/***/ },
/***/ 252:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){"use strict";
module.exports = {
data: function () {return {
NUMBER_742: 742,
NUMBER_230: 230,
NUMBER_4: 4
}},
methods: {
ready: function ready() {
var self = this;
self._randomBrand();
},
_randomBrand: function _randomBrand() {
var self = this;
var bannerItems = self.ds.bannerItems;
bannerItems = bannerItems.sort(function () {
return Math.random() - 0.5;
});
self.bannerItems = bannerItems.slice(0, 8);
for (var i = 0; i < bannerItems.length; i++) {
var item = bannerItems[i];
if (i % 2 === 0) {
item.img = item.leftImg;
item.url = item.rightUrl;
} else {
item.img = item.rightImg;
item.url = item.rightUrl;
}
}
}
}
};}
/* generated by weex-loader */
/***/ }
/******/ }); | MrRaindrop/incubator-weex | android/playground/app/src/main/assets/showcase/new-fashion/brand.js | JavaScript | apache-2.0 | 8,757 |
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.az');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Şərh əlavə et";
Blockly.Msg.CHANGE_VALUE_TITLE = "Qiyməti dəyiş:";
Blockly.Msg.CHAT = "Chat with your collaborator by typing in this box!"; // untranslated
Blockly.Msg.COLLAPSE_ALL = "Blokları yığ";
Blockly.Msg.COLLAPSE_BLOCK = "Bloku yığ";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "rəng 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "rəng 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/";
Blockly.Msg.COLOUR_BLEND_RATIO = "nisbət";
Blockly.Msg.COLOUR_BLEND_TITLE = "qarışdır";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "İki rəngi verilmiş nisbətdə (0,0 - 1,0) qarışdırır.";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/Color"; // untranslated
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Palitradan bir rəng seçin.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "təsadüfi rəng";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Təsadüfi bir rəng seçin.";
Blockly.Msg.COLOUR_RGB_BLUE = "mavi";
Blockly.Msg.COLOUR_RGB_GREEN = "yaşıl";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "qırmızı";
Blockly.Msg.COLOUR_RGB_TITLE = "rəngin komponentləri:";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Qırmızı, yaşıl və mavinin göstərilən miqdarı ilə bir rəng düzəlt. Bütün qiymətlər 0 ilə 100 arasında olmalıdır.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#Loop_Termination_Blocks";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "dövrdən çıx";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "dövrün növbəti addımından davam et";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Cari dövrdən çıx.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Bu dövrün qalanını ötür və növbəti addımla davam et.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Xəbərdarlıq: Bu blok ancaq dövr daxilində istifadə oluna bilər.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#for_each";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "siyahıda";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "hər element üçün";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Siyahıdakı hər element üçün \"%1\" dəyişənini elementə mənimsət və bundan sonra bəzi əmrləri yerinə yetir.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#count_with";
Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO_BY = "%1 ilə başlayıb, %2 qiymətinə kimi %3 qədər dəyiş";
Blockly.Msg.CONTROLS_FOR_INPUT_WITH = "say:";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "%1 dəyişəni başlanğıc ədəddən son ədədə qədər göstərilən aralıqla qiymətlər aldıqca göstərilən blokları yerinə yetir.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "\"Əgər\" blokuna bir şərt əlavə et.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "\"Əgər\" blokuna qalan bütün halları əhatə edəb son bir şərt əlavə et.";
Blockly.Msg.CONTROLS_IF_HELPURL = "http://code.google.com/p/blockly/wiki/If_Then";
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Bu \"əgər\" blokunu dəyişdirmək üçün bölümlərin yenisini əlavə et, sil və ya yerini dəyiş.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "əks halda";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "əks halda əgər";
Blockly.Msg.CONTROLS_IF_MSG_IF = "əgər";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Əgər qiymət doğrudursa, onda bəzi əmrləri yerinə yetir.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Əgər qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda isə ikinci əmrlər blokunu yerinə yetir.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Əgər birinci qiymət doğrudursa, onda birinci əmrlər blokunu yerinə yetir. Əks halda əgər ikinci qiymət doğrudursa, onda ikinci əmrlər blokunu yerinə yetir. Əgər qiymətlərdən heç biri doğru deyilsə, onda axırıncı əmrlər blokunu yerinə yetir.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop"; // untranslated
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "icra et";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "%1 dəfə təkrar et";
Blockly.Msg.CONTROLS_REPEAT_TITLE_REPEAT = "təkrar et";
Blockly.Msg.CONTROLS_REPEAT_TITLE_TIMES = "dəfə";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Bəzi əmrləri bir neçə dəfə yerinə yetir.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "http://code.google.com/p/blockly/wiki/Repeat";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "təkrar et, ta ki";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "təkrar et, hələ ki";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Hələ ki, qiymət \"yalan\"dır, bəzi əmrləri yerinə yetir.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Hələ ki, qiymət \"doğru\"dur, bəzi əmrləri yerinə yetir.";
Blockly.Msg.DELETE_BLOCK = "Bloku sil";
Blockly.Msg.DELETE_X_BLOCKS = "%1 bloku sil";
Blockly.Msg.DISABLE_BLOCK = "Bloku söndür";
Blockly.Msg.DUPLICATE_BLOCK = "Dublikat";
Blockly.Msg.ENABLE_BLOCK = "Bloku aktivləşdir";
Blockly.Msg.EXPAND_ALL = "Blokları aç";
Blockly.Msg.EXPAND_BLOCK = "Bloku aç";
Blockly.Msg.EXTERNAL_INPUTS = "Xarici girişlər";
Blockly.Msg.HELP = "Kömək";
Blockly.Msg.INLINE_INPUTS = "Sətiriçi girişlər";
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "boş siyahı düzəlt";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Heç bir verilən qeyd olunmamış, uzunluğu 0 olan bir siyahı verir";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "siyahı";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Bu siyahı blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin.";
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "bunlardan siyahı düzəlt";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Siyahıya element əlavə edin.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "İstənilən ölçülü siyahı yaradın.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "birinci";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "axırdan # nömrəli";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#";
Blockly.Msg.LISTS_GET_INDEX_GET = "götür";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "götür və sil";
Blockly.Msg.LISTS_GET_INDEX_LAST = "axırıncı";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "təsadüfi";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "yığışdır";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Siyahının ilk elementini qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi qaytarır. #1 son elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi qaytarır. #1 ilk elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Siyahının son elementini qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Siyahıdan hər hansı təsadüfi elementi qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Siyahıdan ilk elementi silir və qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi silir və qaytarır. #1 son elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi silir və qaytarır. #1 ilk elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Siyahıdan son elementi silir və qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Siyahıdan təsadufi elementi silir və qaytarır.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Siyahıdan ilk elementi silir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Siyahıdan təyin olunmuş indeksli elementi silir. #1 son elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Siyahıdan təyin olunmuş indeksli elementi silir. #1 ilk elementdir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Siyahıdan son elementi silir.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Siyahıdan təsadüfi bir elementi silir.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "sondan # nömrəliyə";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "# nömrəliyə";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "Sonuncuya";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_a_sublist";
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "Birincidən alt-siyahını alın";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "# sonuncudan alt-siyahını alın";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "# - dən alt-siyahını alın";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Siyahının təyin olunmuş hissəsinin surətini yaradın.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "Element ilə ilk rastlaşma indeksini müəyyən edin";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_Items_from_a_List";
Blockly.Msg.LISTS_INDEX_OF_LAST = "Element ilə son rastlaşma indeksini müəyyən edin";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Siyahıda element ilə ilk/son rastlaşma indeksini qaytarır. Əgər tekst siyahıda tapılmazsa, 0 qaytarılır.";
Blockly.Msg.LISTS_INLIST = "siyahıda";
Blockly.Msg.LISTS_IS_EMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#is_empty";
Blockly.Msg.LISTS_IS_EMPTY_TITLE = "%1 boşdur";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#length_of";
Blockly.Msg.LISTS_LENGTH_TITLE = "%1 siyahısının uzunluğu";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Siyahının uzunluğunu verir.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#create_list_with";
Blockly.Msg.LISTS_REPEAT_TITLE = "%1 elementinin %2 dəfə təkrarlandığı siyahı düzəlt";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Təyin olunmuş elementin/qiymətin təyin olunmuş sayda təkrarlandığı siyahını yaradır.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#in_list_..._set";
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "Kimi";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "daxil et";
Blockly.Msg.LISTS_SET_INDEX_SET = "təyin et";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Elementi siyahının əvvəlinə daxil edir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Elementi siyahıda göstərilən yerə daxil edir. #1 axırıncı elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Elementi siyahıda göstərilən yerə daxil edir. #1 birinci elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Elementi siyahının sonuna artırır.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Elementi siyahıda təsadüfi seçilmiş bir yerə atır.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Siyahıda birinci elementi təyin edir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Siyahının göstərilən yerdəki elementini təyin edir. #1 axırıncı elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Siyahının göstərilən yerdəki elementini təyin edir. #1 birinci elementdir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Siyahının sonuncu elementini təyin edir.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Siyahının təsadüfi seçilmiş bir elementini təyin edir.";
Blockly.Msg.LISTS_TOOLTIP = "Siyahı boşdursa \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "yalan";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "http://code.google.com/p/blockly/wiki/True_False";
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "\"doğru\" və ya \"yalan\" cavanını qaytarır.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "doğru";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)"; // untranslated
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Girişlər bir birinə bərabərdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Birinci giriş ikincidən böyükdürsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Birinci giriş ikincidən böyük və ya bərarbərdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Birinci giriş ikincidən kiçikdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Birinci giriş ikincidən kiçik və ya bərarbərdirsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Girişlər bərabər deyillərsə \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "http://code.google.com/p/blockly/wiki/Not";
Blockly.Msg.LOGIC_NEGATE_TITLE = "%1 deyil";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Giriş \"yalan\"-dursa \"doğru\" cavabını qaytarır. Giriş \"doğru\"-dursa \"yalan\" cavabını qaytarır.";
Blockly.Msg.LOGIC_NULL = "boş";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Boş cavab qaytarır.";
Blockly.Msg.LOGIC_OPERATION_AND = "və";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "http://code.google.com/p/blockly/wiki/And_Or";
Blockly.Msg.LOGIC_OPERATION_OR = "və ya";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Hər iki giriş \"doğru\"-dursa \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Girişlərdən heç olmasa biri \"doğru\"-dursa \"doğru\" cavabını qaytarır.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "test";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "əgər yalandırsa";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "əgər doğrudursa";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "'Yoxla' əmrindəki şərtə nəzər yetirin. Əgər şərt \"doğru\"-dursa \"əgər doğru\", əks halda isə \"əgər yalan\" cavabını qaytarır.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+";
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://az.wikipedia.org/wiki/Hesab";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "İki ədədin cəmini qaytarır.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "İki ədədin nisbətini qaytarır.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "İki ədədin fərqini qaytarır.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "İki ədədin hasilini verir.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Birinci ədədin ikinci ədəd dərəcəsindən qüvvətini qaytarır.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; // untranslated
Blockly.Msg.MATH_CHANGE_INPUT_BY = "buna:";
Blockly.Msg.MATH_CHANGE_TITLE_CHANGE = "dəyiş:";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "'%1' dəyişəninin üzərinə bir ədəd artır.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant"; // untranslated
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Ümumi sabitlərdən birini qaytarır π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), və ya ∞ (sonsuzluq).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "%1 üçün ən aşağı %2, ən yuxarı %3 olmağı tələb et";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Bir ədədin verilmiş iki ədəd arasında olmasını tələb edir (sərhədlər də daxil olmaqla).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷";
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "bölünür";
Blockly.Msg.MATH_IS_EVEN = "cütdür";
Blockly.Msg.MATH_IS_NEGATIVE = "mənfidir";
Blockly.Msg.MATH_IS_ODD = "təkdir";
Blockly.Msg.MATH_IS_POSITIVE = "müsətdir";
Blockly.Msg.MATH_IS_PRIME = "sadədir";
Blockly.Msg.MATH_IS_TOOLTIP = "Bir ədədin cüt, tək, sadə, tam, müsbət, mənfi olmasını və ya müəyyən bir ədədə bölünməsini yoxlayır. \"Doğru\" və ya \"yalan\" qiymətini qaytarır.";
Blockly.Msg.MATH_IS_WHOLE = "tamdır";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; // untranslated
Blockly.Msg.MATH_MODULO_TITLE = "%1 ÷ %2 bölməsinin qalığı";
Blockly.Msg.MATH_MODULO_TOOLTIP = "İki ədədin nisbətindən alınan qalığı qaytarır.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×";
Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number"; // untranslated
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Ədəd.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "siyahının ədədi ortası";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "siyahının maksimumu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "siyahının medianı";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "siyahının minimumu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "Siyahı modları( Ən çox rastlaşılan elementləri)";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "siyahıdan təsadüfi seçilmiş bir element";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "Siyahının standart deviasiyası";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "Siyahının cəmi";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Siyahıdaki ədədlərin ədədi ortasını qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Siyahıdaki ən böyük elementi qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Siyahının median elementini qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Siyahıdaki ən kiçik ədədi qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Siyahıdaki ən çox rastlanan element(lər)dən ibarət siyahı qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Siyahıdan təsadüfi bir element qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Siyahının standart deviasiyasını qaytarır.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Siyahıdakı bütün ədədlərin cəmini qaytarır.";
Blockly.Msg.MATH_POWER_SYMBOL = "^";
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "təsadüfi kəsr";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "0.0 (daxil olmaqla) və 1.0 (daxil olmamaqla) ədədlərinin arasından təsadüfi bir kəsr ədəd qaytarır.";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg.MATH_RANDOM_INT_TITLE = "%1 ilə %2 arasından təsadüfi tam ədəd";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Verilmiş iki ədəd arasından (ədədrlər də daxil olmaqla) təsadüfi bir tam ədəd qaytarır.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; // untranslated
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "yuvarlaqlaşdır";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "aşağı yuvarlaqlaşdır";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "yuxarı yuvarlaqlaşdır";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Ədədi aşağı və ya yuxari yuvarlaqşdır.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root"; // untranslated
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "modul";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "kvadrat kök";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Ədədin modulunu qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "e sabitinin verilmiş ədədə qüvvətini qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Ədədin natural loqarifmini tapır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Ədədin 10-cu dərəcədən loqarifmini tapır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Ədədin əksini qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "10-un verilmiş ədədə qüvvətini qaytarır.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Ədədin kvadrat kökünü qaytarır.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-";
Blockly.Msg.MATH_TRIG_ACOS = "arccos";
Blockly.Msg.MATH_TRIG_ASIN = "arcsin";
Blockly.Msg.MATH_TRIG_ATAN = "arctan";
Blockly.Msg.MATH_TRIG_COS = "cos";
Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions"; // untranslated
Blockly.Msg.MATH_TRIG_SIN = "sin";
Blockly.Msg.MATH_TRIG_TAN = "tg";
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Ədədin arccosinusunu qaytarır.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Ədədin arcsinusunu qaytarır.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Ədədin arctanqensini qaytarır.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Dərəcənin kosinusunu qaytarır (radianın yox).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Dərəcənin sinusunu qaytar (radianın yox).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Dərəcənin tangensini qaytar (radianın yox).";
Blockly.Msg.NEW_VARIABLE = "Yeni dəyişən...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Yeni dəyişənin adı:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "ilə:";
Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Yaradılmış '%1' funksiyasını çalışdır və nəticəni istifadə et.";
Blockly.Msg.PROCEDURES_CREATE_DO = "'%1' yarat";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "hansısa əməliyyat";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "icra et:";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Nəticəsi olmayan funksiya yaradır.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "qaytar";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Nəticəsi olan funksiya yaradır.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Xəbərdarlıq: Bu funksiyanın təkrar olunmuş parametrləri var.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Funksiyanın təyinatını vurğula";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Əgər bir dəyər \"doğru\"-dursa onda ikinci dəyəri qaytar.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Xəbərdarlıq: Bu blok ancaq bir funksiyanın təyinatı daxilində işlədilə bilər.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "Giriş adı:";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "girişlər";
Blockly.Msg.REMOVE_COMMENT = "Şərhi sil";
Blockly.Msg.RENAME_VARIABLE = "Dəyişənin adını dəyiş...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Bütün '%1' dəyişənlərinin adını buna dəyiş:";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "bu mətni əlavə et:";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification";
Blockly.Msg.TEXT_APPEND_TO = "bu mətnin sonuna:";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "'%1' dəyişəninin sonuna nəsə əlavə et.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Adjusting_text_case";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "kiçik hərflərlə";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "Baş Hərflərlə";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "BÖYÜK HƏRFLƏRLƏ";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Mətndə hərflərin böyük-kiçikliyini dəyiş.";
Blockly.Msg.TEXT_CHARAT_FIRST = "birinci hərfi götür";
Blockly.Msg.TEXT_CHARAT_FROM_END = "axırdan bu nömrəli hərfi götür";
Blockly.Msg.TEXT_CHARAT_FROM_START = "bu nömrəli hərfi götür";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_text";
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "növbəti mətndə";
Blockly.Msg.TEXT_CHARAT_LAST = "axırıncı hərfi götür";
Blockly.Msg.TEXT_CHARAT_RANDOM = "təsadüfi hərf götür";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Göstərilən mövqedəki hərfi qaytarır.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Mətnə bir element əlavə et.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "birləşdir";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Bu mətn blokunu yenidən konfigurasiya etmək üçün bölmələri əlavə edin, silin və ya yerlərini dəyişin.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "axırdan bu nömrəli hərfə qədər";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "bu nömrəli hərfə qədər";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "son hərfə qədər";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "http://code.google.com/p/blockly/wiki/Text#Extracting_a_region_of_text";
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "mətndə";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "Mətnin surətini ilk hərfdən";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "Mətnin surətini sondan bu nömrəli # hərfdən";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "Mətnin surətini bu nömrəli hərfdən";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Mətnin təyin olunmuş hissəsini qaytarır.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Finding_text";
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "mətndə";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "Bu mətn ilə ilk rastlaşmanı tap:";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "Bu mətn ilə son rastlaşmanı tap:";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Birinci mətnin ikinci mətndə ilk/son rastlaşma indeksini qaytarır. Əgər rastlaşma baş verməzsə, 0 qaytarır.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Checking_for_empty_text";
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 boşdur";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Verilmiş mətn boşdursa, doğru qiymətini qaytarır.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_creation";
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "Verilmişlərlə mətn yarat";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "İxtiyari sayda elementlərinin birləşməsi ilə mətn parçası yarat.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification";
Blockly.Msg.TEXT_LENGTH_TITLE = "%1 - ın uzunluğu";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Verilmiş mətndəki hərflərin(sözlər arası boşluqlar sayılmaqla) sayını qaytarır.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Printing_text";
Blockly.Msg.TEXT_PRINT_TITLE = "%1 - i çap elə";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Təyin olunmuş mətn, ədəd və ya hər hansı bir başqa elementi çap elə.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Getting_input_from_the_user";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğu/tələb göndərin.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğu/tələb göndərin.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "İstifadəçiyə ədəd daxil etməsi üçün sorğunu/tələbi ismarıc kimi göndərin";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "İstifadəçiyə mətn daxil etməsi üçün sorğunu/tələbi ismarıc ilə göndərin";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; // untranslated
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Mətndəki hərf, söz və ya sətir.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Trimming_%28removing%29_spaces";
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "Boşluqları hər iki tərəfdən pozun";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "Boşluqlari yalnız sol tərəfdən pozun";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "Boşluqları yalnız sağ tərəfdən pozun";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Mətnin hər iki və ya yalnız bir tərəfdən olan boşluqları pozulmuş surətini qaytarın.";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "element";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "'%1 - i təyin et' - i yarat";
Blockly.Msg.VARIABLES_GET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Get";
Blockly.Msg.VARIABLES_GET_TAIL = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TITLE = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Bu dəyişənin qiymətini qaytarır.";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "'%1 - i götür' - ü yarat";
Blockly.Msg.VARIABLES_SET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Set";
Blockly.Msg.VARIABLES_SET_TAIL = "- i bu qiymət ilə təyin et:";
Blockly.Msg.VARIABLES_SET_TITLE = "set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Bu dəyişəni daxil edilmiş qiymətə bərabər edir.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; | drk123/buildafaq | third_party/msg/js/az.js | JavaScript | apache-2.0 | 31,031 |
"use strict";
var _Object$defineProperty = require("@babel/runtime-corejs3/core-js-stable/object/define-property");
_Object$defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var noteRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {},
relatedConcepts: [],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section']]
};
var _default = noteRole;
exports.default = _default; | GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/aria-query/lib/etc/roles/literal/noteRole.js | JavaScript | apache-2.0 | 627 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Variable = void 0;
const VariableBase_1 = require("./VariableBase");
/**
* A Variable represents a locally scoped identifier. These include arguments to functions.
*/
class Variable extends VariableBase_1.VariableBase {
/**
* `true` if the variable is valid in a type context, false otherwise
* @public
*/
get isTypeVariable() {
if (this.defs.length === 0) {
// we don't statically know whether this is a type or a value
return true;
}
return this.defs.some(def => def.isTypeDefinition);
}
/**
* `true` if the variable is valid in a value context, false otherwise
* @public
*/
get isValueVariable() {
if (this.defs.length === 0) {
// we don't statically know whether this is a type or a value
return true;
}
return this.defs.some(def => def.isVariableDefinition);
}
}
exports.Variable = Variable;
//# sourceMappingURL=Variable.js.map | ChromeDevTools/devtools-frontend | node_modules/@typescript-eslint/scope-manager/dist/variable/Variable.js | JavaScript | bsd-3-clause | 1,070 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Tests scripts panel file selectors.\n`);
await TestRunner.loadLegacyModule('sources'); await TestRunner.loadTestModule('sources_test_runner');
await TestRunner.loadTestModule('sdk_test_runner');
await TestRunner.showPanel('sources');
await TestRunner.addIframe(
'resources/post-message-listener.html', {name: 'childframe'});
Bindings.debuggerWorkspaceBinding.resetForTest(TestRunner.mainTarget);
Bindings.resourceMapping.resetForTest(TestRunner.mainTarget);
var subframe = TestRunner.mainFrame().childFrames[0];
var sourcesNavigatorView = new Sources.NetworkNavigatorView();
sourcesNavigatorView.show(UI.inspectorView.element);
var contentScriptsNavigatorView = new Sources.ContentScriptsNavigatorView();
contentScriptsNavigatorView.show(UI.inspectorView.element);
var uiSourceCodes = [];
async function addUISourceCode(url, isContentScript, frame) {
if (isContentScript) {
var uiSourceCode =
await SourcesTestRunner.addScriptUISourceCode(url, '', true, 42);
uiSourceCodes.push(uiSourceCode);
return;
}
TestRunner.addScriptForFrame(url, '', frame || TestRunner.mainFrame());
var uiSourceCode = await waitForUISourceCodeAdded(url);
uiSourceCodes.push(uiSourceCode);
}
async function addUISourceCode2(url) {
TestRunner.evaluateInPageAnonymously(`
window.workers = window.workers || [];
window.workers.push(new Worker('${url}'));
`);
var uiSourceCode = await waitForUISourceCodeAdded(url);
uiSourceCodes.push(uiSourceCode);
}
function waitForUISourceCodeAdded(url) {
var fulfill;
var promise = new Promise(x => fulfill = x);
Workspace.workspace.addEventListener(
Workspace.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded);
return promise;
function uiSourceCodeAdded(event) {
if (event.data.url() !== url)
return;
Workspace.workspace.removeEventListener(
Workspace.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded);
fulfill(event.data);
}
}
function revealUISourceCode(uiSourceCode) {
sourcesNavigatorView.revealUISourceCode(uiSourceCode);
contentScriptsNavigatorView.revealUISourceCode(uiSourceCode);
}
var rootURL = 'http://localhost:8080/LayoutTests/inspector/debugger/';
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding first resource:');
await addUISourceCode(rootURL + 'foo/bar/script.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding second resource:');
await addUISourceCode(rootURL + 'foo/bar/script.js?a=2', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding resources into another frame:');
await addUISourceCode(rootURL + 'foo/bar/script.js?a=1', false, subframe);
await addUISourceCode(rootURL + 'foo/baz/script.js', false, subframe);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding resources into another target:');
await addUISourceCode2(TestRunner.url('resources/script1.js?a=3'));
await addUISourceCode2(TestRunner.url('resources/script2.js'));
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Adding content scripts and some random resources:');
await addUISourceCode(rootURL + 'foo/bar/contentScript2.js?a=1', true);
await addUISourceCode(rootURL + 'foo/bar/contentScript.js?a=2', true);
await addUISourceCode(rootURL + 'foo/bar/contentScript.js?a=1', true);
await addUISourceCode('http://example.com/', false);
await addUISourceCode('http://example.com/?a=b', false);
await addUISourceCode(
'http://example.com/the%2fdir/foo?bar=100&baz=a%20%2fb', false);
// Verify that adding invalid URL does not throw exception.
await addUISourceCode(
'http://example.com/the%2fdir/foo?bar=100%&baz=a%20%2fb', false);
await addUISourceCode(
'http://example.com/path%20with%20spaces/white%20space.html', false);
await addUISourceCode('?a=b', false);
await addUISourceCode(
'very_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_url',
false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
SourcesTestRunner.dumpNavigatorViewInAllModes(contentScriptsNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Revealing first resource:');
revealUISourceCode(uiSourceCodes[0]);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
// Here we keep http://localhost:8080/LayoutTests/inspector/debugger2/ folder
// collapsed while adding resources into it.
TestRunner.addResult('\n\n================================================');
TestRunner.addResult(
'Adding some resources to change the way debugger folder looks like, first:');
var rootURL2 = 'http://localhost:8080/LayoutTests/inspector/debugger2/';
await addUISourceCode(rootURL2 + 'foo/bar/script.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Second:');
await addUISourceCode(rootURL2 + 'foo/bar/script.js?a=2', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Others:');
await addUISourceCode(rootURL2 + 'foo/bar/script.js?a=1', false);
await addUISourceCode(rootURL2 + 'foo/baz/script.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
var rootURL3 = 'http://localhost:8080/LayoutTests/inspector/debugger3/';
await addUISourceCode(
rootURL3 + 'hasOwnProperty/__proto__/constructor/foo.js', false);
await addUISourceCode(rootURL3 + 'hasOwnProperty/__proto__/foo.js', false);
await addUISourceCode(rootURL3 + 'hasOwnProperty/foo.js', false);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Revealing all resources:');
for (var i = 0; i < uiSourceCodes.length; ++i)
revealUISourceCode(uiSourceCodes[i]);
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
SourcesTestRunner.dumpNavigatorViewInAllModes(contentScriptsNavigatorView);
TestRunner.addResult('\n\n================================================');
TestRunner.addResult('Removing all resources:');
for (const target of SDK.targetManager.targets()) {
if (target !== TestRunner.mainTarget)
Bindings.debuggerWorkspaceBinding.resetForTest(target);
}
SourcesTestRunner.dumpNavigatorViewInAllModes(sourcesNavigatorView);
SourcesTestRunner.dumpNavigatorViewInAllModes(contentScriptsNavigatorView);
TestRunner.completeTest();
})();
| chromium/chromium | third_party/blink/web_tests/http/tests/devtools/sources/debugger/navigator-view.js | JavaScript | bsd-3-clause | 7,615 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
function waitUntilIdle() {
return new Promise(resolve=>{
window.requestIdleCallback(()=>resolve());
});
}
(async function() {
TestRunner.addResult(`Tests V8 code cache for javascript resources\n`);
await TestRunner.loadLegacyModule('timeline'); await TestRunner.loadTestModule('performance_test_runner');
await TestRunner.showPanel('timeline');
// Clear browser cache to avoid any existing entries for the fetched
// scripts in the cache.
SDK.multitargetNetworkManager.clearBrowserCache();
// There are two scripts:
// [A] http://127.0.0.1:8000/devtools/resources/v8-cache-script.cgi
// [B] http://localhost:8000/devtools/resources/v8-cache-script.cgi
// An iframe that loads [A].
// The script is executed as a parser-inserted script,
// to keep the ScriptResource on the MemoryCache.
// ScriptResources for dynamically-inserted <script>s can be
// garbage-collected and thus removed from MemoryCache after its execution.
const scope = 'resources/same-origin-script.html';
// An iframe that loads [B].
const scopeCrossOrigin = 'resources/cross-origin-script.html';
TestRunner.addResult('--- Trace events related to code caches ------');
await PerformanceTestRunner.startTimeline();
async function stopAndPrintTimeline() {
await PerformanceTestRunner.stopTimeline();
await PerformanceTestRunner.printTimelineRecordsWithDetails(
TimelineModel.TimelineModel.RecordType.CompileScript,
TimelineModel.TimelineModel.RecordType.CacheScript);
}
async function expectationComment(msg) {
await stopAndPrintTimeline();
TestRunner.addResult(msg);
await PerformanceTestRunner.startTimeline();
}
// Load [A] thrice. With the current V8 heuristics (defined in
// third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc) we produce
// cache on second fetch and consume it in the third fetch. This tests these
// heuristics.
// Note that addIframe() waits for iframe's load event, which waits for the
// <script> loading.
await expectationComment('Load [A] 1st time. Produce timestamp. -->');
await TestRunner.addIframe(scope);
await expectationComment('Load [A] 2nd time. Produce code cache. -->');
await TestRunner.addIframe(scope);
await waitUntilIdle();
await expectationComment('Load [A] 3rd time. Consume code cache. -->');
await TestRunner.addIframe(scope);
await expectationComment('Load [B]. Should not use the cached code. -->');
await TestRunner.addIframe(scopeCrossOrigin);
await expectationComment('Load [A] again from MemoryCache. ' +
'Should use the cached code. -->');
await TestRunner.addIframe(scope);
await expectationComment('Clear [A] from MemoryCache. -->');
// Blink evicts previous Resource when a new request to the same URL but with
// different resource type is started. We fetch() to the URL of [A], and thus
// evicts the previous ScriptResource of [A].
await TestRunner.evaluateInPageAsync(
`fetch('/devtools/resources/v8-cache-script.cgi')`);
await expectationComment('Load [A] from Disk Cache. -->');
// As we cleared [A] from MemoryCache, this doesn't hit MemoryCache, but still
// hits Disk Cache.
await TestRunner.addIframe(scope);
await stopAndPrintTimeline();
TestRunner.addResult('-----------------------------------------------');
TestRunner.completeTest();
})();
| chromium/chromium | third_party/blink/web_tests/http/tests/devtools/isolated-code-cache/same-origin-test.js | JavaScript | bsd-3-clause | 3,533 |
// This is not the set of all possible signals.
//
// It IS, however, the set of all signals that trigger
// an exit on either Linux or BSD systems. Linux is a
// superset of the signal names supported on BSD, and
// the unknown signals just fail to register, so we can
// catch that easily enough.
//
// Don't bother with SIGKILL. It's uncatchable, which
// means that we can't fire any callbacks anyway.
//
// If a user does happen to register a handler on a non-
// fatal signal like SIGWINCH or something, and then
// exit, it'll end up firing `process.emit('exit')`, so
// the handler will be fired anyway.
//
// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
// artificially, inherently leave the process in a
// state from which it is not safe to try and enter JS
// listeners.
module.exports = [
'SIGABRT',
'SIGALRM',
'SIGHUP',
'SIGINT',
'SIGTERM'
]
if (process.platform !== 'win32') {
module.exports.push(
'SIGVTALRM',
'SIGXCPU',
'SIGXFSZ',
'SIGUSR2',
'SIGTRAP',
'SIGSYS',
'SIGQUIT',
'SIGIOT'
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
)
}
if (process.platform === 'linux') {
module.exports.push(
'SIGIO',
'SIGPOLL',
'SIGPWR',
'SIGSTKFLT',
'SIGUNUSED'
)
}
| Moccine/global-service-plus.com | web/libariries/bootstrap/node_modules/signal-exit/signals.js | JavaScript | mit | 1,348 |
import { css, StyleSheet } from 'aphrodite/no-important';
import React, { PropTypes } from 'react';
import octicons from './octicons';
import colors from './colors';
import sizes from './sizes';
import styles from './styles';
const classes = StyleSheet.create(styles);
// FIXME static octicon classes leaning on Elemental to avoid duplicate
// font and CSS; inflating the project size
function Glyph ({
aphroditeStyles,
className,
color,
component: Component,
name,
size,
style,
...props
}) {
const colorIsValidType = Object.keys(colors).includes(color);
props.className = css(
classes.glyph,
colorIsValidType && classes['color__' + color],
classes['size__' + size],
aphroditeStyles
) + ` ${octicons[name]}`;
if (className) {
props.className += (' ' + className);
}
// support random color strings
props.style = {
color: !colorIsValidType ? color : null,
...style,
};
return <Component {...props} />;
};
Glyph.propTypes = {
aphroditeStyles: PropTypes.shape({
_definition: PropTypes.object,
_name: PropTypes.string,
}),
color: PropTypes.oneOfType([
PropTypes.oneOf(Object.keys(colors)),
PropTypes.string, // support random color strings
]),
name: PropTypes.oneOf(Object.keys(octicons)).isRequired,
size: PropTypes.oneOf(Object.keys(sizes)),
};
Glyph.defaultProps = {
component: 'i',
color: 'inherit',
size: 'small',
};
module.exports = Glyph;
| linhanyang/keystone | admin/client/App/elemental/Glyph/index.js | JavaScript | mit | 1,398 |
"function"==typeof jQuery&&jQuery(document).ready(function(e){function n(){!1!==s?o():t()}function o(){r=new google.maps.LatLng(s[0],s[1]),a()}function t(){var e=new google.maps.Geocoder;e.geocode({address:d},function(e,n){n==google.maps.GeocoderStatus.OK&&(r=e[0].geometry.location,a())})}function a(){var n={zoom:parseInt(tribeEventsSingleMap.zoom),center:r,mapTypeId:google.maps.MapTypeId.ROADMAP};p.map=new google.maps.Map(i,n);var o={map:p.map,title:g,position:r};e("body").trigger("map-created.tribe",[p.map,i,n]),"undefined"!==tribeEventsSingleMap.pin_url&&tribeEventsSingleMap.pin_url&&(o.icon=tribeEventsSingleMap.pin_url),new google.maps.Marker(o)}var i,r,p,d,s,g;"undefined"!=typeof tribeEventsSingleMap&&e.each(tribeEventsSingleMap.addresses,function(e,o){i=document.getElementById("tribe-events-gmap-"+e),null!==i&&(p="undefined"!=typeof o?o:{},d="undefined"!=typeof o.address&&o.address,s="undefined"!=typeof o.coords&&o.coords,g=o.title,n())})}); | smpetrey/acredistilling.com | web/app/plugins/the-events-calendar/src/resources/js/embedded-map.min.js | JavaScript | mit | 961 |
angular.module('merchello.plugins.braintree').controller('Merchello.Plugins.GatewayProviders.Dialogs.PaymentMethodAddEditController',
['$scope', 'braintreeProviderSettingsBuilder',
function($scope, braintreeProviderSettingsBuilder) {
$scope.providerSettings = {};
function init() {
var json = JSON.parse($scope.dialogData.provider.extendedData.getValue('braintreeProviderSettings'));
$scope.providerSettings = braintreeProviderSettingsBuilder.transform(json);
$scope.$watch(function () {
return $scope.providerSettings;
}, function (newValue, oldValue) {
$scope.dialogData.provider.extendedData.setValue('braintreeProviderSettings', angular.toJson(newValue));
}, true);
}
// initialize the controller
init();
}]); | bjarnef/Merchello | src/Merchello.Web.UI/App_Plugins/Merchello.Braintree/payment.braintree.providersettings.controller.js | JavaScript | mit | 922 |
(function () {
'use strict';
function ContentEditController($rootScope, $scope, $routeParams, $q, $timeout, $window, $location, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, treeService, fileManager, formHelper, umbRequestHelper, keyboardService, umbModelMapper, editorState, $http, eventsService, relationResource) {
var evts = [];
//setup scope vars
$scope.defaultButton = null;
$scope.subButtons = [];
$scope.page = {};
$scope.page.loading = false;
$scope.page.menu = {};
$scope.page.menu.currentNode = null;
$scope.page.menu.currentSection = appState.getSectionState("currentSection");
$scope.page.listViewPath = null;
$scope.page.isNew = $scope.isNew ? true : false;
$scope.page.buttonGroupState = "init";
$scope.allowOpen = true;
function init(content) {
createButtons(content);
editorState.set($scope.content);
//We fetch all ancestors of the node to generate the footer breadcrumb navigation
if (!$scope.page.isNew) {
if (content.parentId && content.parentId !== -1) {
entityResource.getAncestors(content.id, "document")
.then(function (anc) {
$scope.ancestors = anc;
});
}
}
evts.push(eventsService.on("editors.content.changePublishDate", function (event, args) {
createButtons(args.node);
}));
evts.push(eventsService.on("editors.content.changeUnpublishDate", function (event, args) {
createButtons(args.node);
}));
// We don't get the info tab from the server from version 7.8 so we need to manually add it
contentEditingHelper.addInfoTab($scope.content.tabs);
}
function getNode() {
$scope.page.loading = true;
//we are editing so get the content item from the server
$scope.getMethod()($scope.contentId)
.then(function (data) {
$scope.content = data;
if (data.isChildOfListView && data.trashed === false) {
$scope.page.listViewPath = ($routeParams.page) ?
"/content/content/edit/" + data.parentId + "?page=" + $routeParams.page :
"/content/content/edit/" + data.parentId;
}
init($scope.content);
//in one particular special case, after we've created a new item we redirect back to the edit
// route but there might be server validation errors in the collection which we need to display
// after the redirect, so we will bind all subscriptions which will show the server validation errors
// if there are any and then clear them so the collection no longer persists them.
serverValidationManager.executeAndClearAllSubscriptions();
syncTreeNode($scope.content, data.path, true);
resetLastListPageNumber($scope.content);
eventsService.emit("content.loaded", { content: $scope.content });
$scope.page.loading = false;
});
}
function createButtons(content) {
$scope.page.buttonGroupState = "init";
var buttons = contentEditingHelper.configureContentEditorButtons({
create: $scope.page.isNew,
content: content,
methods: {
saveAndPublish: $scope.saveAndPublish,
sendToPublish: $scope.sendToPublish,
save: $scope.save,
unPublish: $scope.unPublish
}
});
$scope.defaultButton = buttons.defaultButton;
$scope.subButtons = buttons.subButtons;
}
/** Syncs the content item to it's tree node - this occurs on first load and after saving */
function syncTreeNode(content, path, initialLoad) {
if (!$scope.content.isChildOfListView) {
navigationService.syncTree({ tree: $scope.treeAlias, path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) {
$scope.page.menu.currentNode = syncArgs.node;
});
}
else if (initialLoad === true) {
//it's a child item, just sync the ui node to the parent
navigationService.syncTree({ tree: $scope.treeAlias, path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true });
//if this is a child of a list view and it's the initial load of the editor, we need to get the tree node
// from the server so that we can load in the actions menu.
umbRequestHelper.resourcePromise(
$http.get(content.treeNodeUrl),
'Failed to retrieve data for child node ' + content.id).then(function (node) {
$scope.page.menu.currentNode = node;
});
}
}
// This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish
function performSave(args) {
var deferred = $q.defer();
$scope.page.buttonGroupState = "busy";
eventsService.emit("content.saving", { content: $scope.content, action: args.action });
contentEditingHelper.contentEditorPerformSave({
statusMessage: args.statusMessage,
saveMethod: args.saveMethod,
scope: $scope,
content: $scope.content,
action: args.action
}).then(function (data) {
//success
init($scope.content);
syncTreeNode($scope.content, data.path);
$scope.page.buttonGroupState = "success";
deferred.resolve(data);
eventsService.emit("content.saved", { content: $scope.content, action: args.action });
}, function (err) {
//error
if (err) {
editorState.set($scope.content);
}
$scope.page.buttonGroupState = "error";
deferred.reject(err);
});
return deferred.promise;
}
function resetLastListPageNumber(content) {
// We're using rootScope to store the page number for list views, so if returning to the list
// we can restore the page. If we've moved on to edit a piece of content that's not the list or it's children
// we should remove this so as not to confuse if navigating to a different list
if (!content.isChildOfListView && !content.isContainer) {
$rootScope.lastListViewPageViewed = null;
}
}
if ($scope.page.isNew) {
$scope.page.loading = true;
//we are creating so get an empty content item
$scope.getScaffoldMethod()()
.then(function (data) {
$scope.content = data;
init($scope.content);
resetLastListPageNumber($scope.content);
$scope.page.loading = false;
eventsService.emit("content.newReady", { content: $scope.content });
});
}
else {
getNode();
}
$scope.unPublish = function () {
// raising the event triggers the confirmation dialog
if (!notificationsService.hasView()) {
notificationsService.add({ view: "confirmunpublish" });
}
$scope.page.buttonGroupState = "busy";
// actioning the dialog raises the confirmUnpublish event, act on it here
var actioned = $rootScope.$on("content.confirmUnpublish", function(event, confirmed) {
if (confirmed && formHelper.submitForm({ scope: $scope, statusMessage: "Unpublishing...", skipValidation: true })) {
eventsService.emit("content.unpublishing", { content: $scope.content });
contentResource.unPublish($scope.content.id)
.then(function (data) {
formHelper.resetForm({ scope: $scope, notifications: data.notifications });
contentEditingHelper.handleSuccessfulSave({
scope: $scope,
savedContent: data,
rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data)
});
init($scope.content);
syncTreeNode($scope.content, data.path);
$scope.page.buttonGroupState = "success";
eventsService.emit("content.unpublished", { content: $scope.content });
}, function(err) {
formHelper.showNotifications(err.data);
$scope.page.buttonGroupState = 'error';
});
} else {
$scope.page.buttonGroupState = "init";
}
// unsubscribe to avoid queueing notifications
// listener is re-bound when the unpublish button is clicked so it is created just-in-time
actioned();
});
};
$scope.sendToPublish = function () {
return performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending...", action: "sendToPublish" });
};
$scope.saveAndPublish = function () {
return performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing...", action: "publish" });
};
$scope.save = function () {
return performSave({ saveMethod: $scope.saveMethod(), statusMessage: "Saving...", action: "save" });
};
$scope.preview = function (content) {
if (!$scope.busy) {
// Chromes popup blocker will kick in if a window is opened
// without the initial scoped request. This trick will fix that.
//
var previewWindow = $window.open('preview/?init=true&id=' + content.id, 'umbpreview');
// Build the correct path so both /#/ and #/ work.
var redirect = Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath + '/preview/?id=' + content.id;
//The user cannot save if they don't have access to do that, in which case we just want to preview
//and that's it otherwise they'll get an unauthorized access message
if (!_.contains(content.allowedActions, "A")) {
previewWindow.location.href = redirect;
}
else {
$scope.save().then(function (data) {
previewWindow.location.href = redirect;
});
}
}
};
$scope.restore = function (content) {
$scope.page.buttonRestore = "busy";
relationResource.getByChildId(content.id, "relateParentDocumentOnDelete").then(function (data) {
var relation = null;
var target = null;
var error = { headline: "Cannot automatically restore this item", content: "Use the Move menu item to move it manually"};
if (data.length == 0) {
notificationsService.error(error.headline, "There is no 'restore' relation found for this node. Use the Move menu item to move it manually.");
$scope.page.buttonRestore = "error";
return;
}
relation = data[0];
if (relation.parentId == -1) {
target = { id: -1, name: "Root" };
moveNode(content, target);
} else {
contentResource.getById(relation.parentId).then(function (data) {
target = data;
// make sure the target item isn't in the recycle bin
if(target.path.indexOf("-20") !== -1) {
notificationsService.error(error.headline, "The item you want to restore it under (" + target.name + ") is in the recycle bin. Use the Move menu item to move the item manually.");
$scope.page.buttonRestore = "error";
return;
}
moveNode(content, target);
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.error(error.headline, error.content);
});
}
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.error(error.headline, error.content);
});
};
function moveNode(node, target) {
contentResource.move({ "parentId": target.id, "id": node.id })
.then(function (path) {
// remove the node that we're working on
if($scope.page.menu.currentNode) {
treeService.removeNode($scope.page.menu.currentNode);
}
// sync the destination node
navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false });
$scope.page.buttonRestore = "success";
notificationsService.success("Successfully restored " + node.name + " to " + target.name);
// reload the node
getNode();
}, function (err) {
$scope.page.buttonRestore = "error";
notificationsService.error("Cannot automatically restore this item", err);
});
}
//ensure to unregister from all events!
$scope.$on('$destroy', function () {
for (var e in evts) {
eventsService.unsubscribe(evts[e]);
}
});
}
function createDirective() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/content/edit.html',
controller: 'Umbraco.Editors.Content.EditorDirectiveController',
scope: {
contentId: "=",
isNew: "=?",
treeAlias: "@",
page: "=?",
saveMethod: "&",
getMethod: "&",
getScaffoldMethod: "&?"
}
};
return directive;
}
angular.module('umbraco.directives').controller('Umbraco.Editors.Content.EditorDirectiveController', ContentEditController);
angular.module('umbraco.directives').directive('contentEditor', createDirective);
})();
| abryukhov/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js | JavaScript | mit | 13,245 |
var tns = (function (){
// keys
if (!Object.keys) {
Object.keys = function (object) {
var keys = [];
for (var name in object) {
if (Object.prototype.hasOwnProperty.call(object, name)) {
keys.push(name);
}
}
return keys;
};
}
// ChildNode.remove
(function () {
"use strict";
if(!("remove" in Element.prototype)){
Element.prototype.remove = function(){
if(this.parentNode) {
this.parentNode.removeChild(this);
}
};
}
})();
var win = window;
var raf = win.requestAnimationFrame
|| win.webkitRequestAnimationFrame
|| win.mozRequestAnimationFrame
|| win.msRequestAnimationFrame
|| function(cb) { return setTimeout(cb, 16); };
var win$1 = window;
var caf = win$1.cancelAnimationFrame
|| win$1.mozCancelAnimationFrame
|| function(id){ clearTimeout(id); };
function extend() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) !== null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
}
function checkStorageValue (value) {
return ['true', 'false'].indexOf(value) >= 0 ? JSON.parse(value) : value;
}
function setLocalStorage(key, value) {
localStorage.setItem(key, value);
return value;
}
function getSlideId() {
var id = window.tnsId;
window.tnsId = !id ? 1 : id + 1;
return 'tns' + window.tnsId;
}
function getBody () {
var doc = document,
body = doc.body;
if (!body) {
body = doc.createElement('body');
body.fake = true;
}
return body;
}
var docElement = document.documentElement;
function setFakeBody (body) {
var docOverflow = '';
if (body.fake) {
docOverflow = docElement.style.overflow;
//avoid crashing IE8, if background image is used
body.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
body.style.overflow = docElement.style.overflow = 'hidden';
docElement.appendChild(body);
}
return docOverflow;
}
function resetFakeBody (body, docOverflow) {
if (body.fake) {
body.remove();
docElement.style.overflow = docOverflow;
// Trigger layout so kinetic scrolling isn't disabled in iOS6+
// eslint-disable-next-line
docElement.offsetHeight;
}
}
// get css-calc
function calc() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
result = false;
body.appendChild(div);
try {
var vals = ['calc(10px)', '-moz-calc(10px)', '-webkit-calc(10px)'], val;
for (var i = 0; i < 3; i++) {
val = vals[i];
div.style.width = val;
if (div.offsetWidth === 10) {
result = val.replace('(10px)', '');
break;
}
}
} catch (e) {}
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return result;
}
// get subpixel support value
function subpixelLayout() {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
parent = doc.createElement('div'),
child1 = doc.createElement('div'),
child2,
supported;
parent.style.cssText = 'width: 10px';
child1.style.cssText = 'float: left; width: 5.5px; height: 10px;';
child2 = child1.cloneNode(true);
parent.appendChild(child1);
parent.appendChild(child2);
body.appendChild(parent);
supported = child1.offsetTop !== child2.offsetTop;
body.fake ? resetFakeBody(body, docOverflow) : parent.remove();
return supported;
}
function mediaquerySupport () {
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
div = doc.createElement('div'),
style = doc.createElement('style'),
rule = '@media all and (min-width:1px){.tns-mq-test{position:absolute}}',
position;
style.type = 'text/css';
div.className = 'tns-mq-test';
body.appendChild(style);
body.appendChild(div);
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.appendChild(doc.createTextNode(rule));
}
position = window.getComputedStyle ? window.getComputedStyle(div).position : div.currentStyle['position'];
body.fake ? resetFakeBody(body, docOverflow) : div.remove();
return position === "absolute";
}
// create and append style sheet
function createStyleSheet (media) {
// Create the <style> tag
var style = document.createElement("style");
// style.setAttribute("type", "text/css");
// Add a media (and/or media query) here if you'd like!
// style.setAttribute("media", "screen")
// style.setAttribute("media", "only screen and (max-width : 1024px)")
if (media) { style.setAttribute("media", media); }
// WebKit hack :(
// style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.querySelector('head').appendChild(style);
return style.sheet ? style.sheet : style.styleSheet;
}
// cross browsers addRule method
function addCSSRule(sheet, selector, rules, index) {
// return raf(function() {
'insertRule' in sheet ?
sheet.insertRule(selector + '{' + rules + '}', index) :
sheet.addRule(selector, rules, index);
// });
}
function getCssRulesLength(sheet) {
var rule = ('insertRule' in sheet) ? sheet.cssRules : sheet.rules;
return rule.length;
}
function toDegree (y, x) {
return Math.atan2(y, x) * (180 / Math.PI);
}
function getTouchDirection(angle, range) {
var direction = false,
gap = Math.abs(90 - Math.abs(angle));
if (gap >= 90 - range) {
direction = 'horizontal';
} else if (gap <= range) {
direction = 'vertical';
}
return direction;
}
// https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/
function forEachNodeList (arr, callback, scope) {
for (var i = 0, l = arr.length; i < l; i++) {
callback.call(scope, arr[i], i);
}
}
var classListSupport = 'classList' in document.createElement('_');
var hasClass = classListSupport ?
function (el, str) { return el.classList.contains(str); } :
function (el, str) { return el.className.indexOf(str) >= 0; };
var addClass = classListSupport ?
function (el, str) {
if (!hasClass(el, str)) { el.classList.add(str); }
} :
function (el, str) {
if (!hasClass(el, str)) { el.className += ' ' + str; }
};
var removeClass = classListSupport ?
function (el, str) {
if (hasClass(el, str)) { el.classList.remove(str); }
} :
function (el, str) {
if (hasClass(el, str)) { el.className = el.className.replace(str, ''); }
};
function hasAttr(el, attr) {
return el.hasAttribute(attr);
}
function getAttr(el, attr) {
return el.getAttribute(attr);
}
function isNodeList(el) {
// Only NodeList has the "item()" function
return typeof el.item !== "undefined";
}
function setAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
if (Object.prototype.toString.call(attrs) !== '[object Object]') { return; }
for (var i = els.length; i--;) {
for(var key in attrs) {
els[i].setAttribute(key, attrs[key]);
}
}
}
function removeAttrs(els, attrs) {
els = (isNodeList(els) || els instanceof Array) ? els : [els];
attrs = (attrs instanceof Array) ? attrs : [attrs];
var attrLength = attrs.length;
for (var i = els.length; i--;) {
for (var j = attrLength; j--;) {
els[i].removeAttribute(attrs[j]);
}
}
}
function removeElementStyles(el) {
el.style.cssText = '';
}
function arrayFromNodeList (nl) {
var arr = [];
for (var i = 0, l = nl.length; i < l; i++) {
arr.push(nl[i]);
}
return arr;
}
function hideElement(el) {
if (!hasAttr(el, 'hidden')) {
setAttrs(el, {'hidden': ''});
}
}
function showElement(el) {
if (hasAttr(el, 'hidden')) {
removeAttrs(el, 'hidden');
}
}
function isVisible(el) {
return el.offsetWidth > 0 && el.offsetHeight > 0;
}
function whichProperty(props){
if (typeof props === 'string') {
var arr = [props],
Props = props.charAt(0).toUpperCase() + props.substr(1),
prefixes = ['Webkit', 'Moz', 'ms', 'O'];
prefixes.forEach(function(prefix) {
if (prefix !== 'ms' || props === 'transform') {
arr.push(prefix + Props);
}
});
props = arr;
}
var el = document.createElement('fakeelement'),
len = props.length;
for(var i = 0; i < props.length; i++){
var prop = props[i];
if( el.style[prop] !== undefined ){ return prop; }
}
return false; // explicit for ie9-
}
function has3D(tf){
if (!window.getComputedStyle) { return false; }
var doc = document,
body = getBody(),
docOverflow = setFakeBody(body),
el = doc.createElement('p'),
has3d,
cssTF = tf.length > 9 ? '-' + tf.slice(0, -9).toLowerCase() + '-' : '';
cssTF += 'transform';
// Add it to the body to get the computed style
body.insertBefore(el, null);
el.style[tf] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(cssTF);
body.fake ? resetFakeBody(body, docOverflow) : el.remove();
return (has3d !== undefined && has3d.length > 0 && has3d !== "none");
}
// get transitionend, animationend based on transitionDuration
// @propin: string
// @propOut: string, first-letter uppercase
// Usage: getEndProperty('WebkitTransitionDuration', 'Transition') => webkitTransitionEnd
function getEndProperty(propIn, propOut) {
var endProp = false;
if (/^Webkit/.test(propIn)) {
endProp = 'webkit' + propOut + 'End';
} else if (/^O/.test(propIn)) {
endProp = 'o' + propOut + 'End';
} else if (propIn) {
endProp = propOut.toLowerCase() + 'end';
}
return endProp;
}
// Test via a getter in the options object to see if the passive property is accessed
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("test", null, opts);
} catch (e) {}
var passiveOption = supportsPassive ? { passive: true } : false;
function addEvents(el, obj) {
for (var prop in obj) {
var option = (prop === 'touchstart' || prop === 'touchmove') ? passiveOption : false;
el.addEventListener(prop, obj[prop], option);
}
}
function removeEvents(el, obj) {
for (var prop in obj) {
var option = ['touchstart', 'touchmove'].indexOf(prop) >= 0 ? passiveOption : false;
el.removeEventListener(prop, obj[prop], option);
}
}
function Events() {
return {
topics: {},
on: function (eventName, fn) {
this.topics[eventName] = this.topics[eventName] || [];
this.topics[eventName].push(fn);
},
off: function(eventName, fn) {
if (this.topics[eventName]) {
for (var i = 0; i < this.topics[eventName].length; i++) {
if (this.topics[eventName][i] === fn) {
this.topics[eventName].splice(i, 1);
break;
}
}
}
},
emit: function (eventName, data) {
if (this.topics[eventName]) {
this.topics[eventName].forEach(function(fn) {
fn(data);
});
}
}
};
}
function jsTransform(element, attr, prefix, postfix, to, duration, callback) {
var tick = Math.min(duration, 10),
unit = (to.indexOf('%') >= 0) ? '%' : 'px',
to = to.replace(unit, ''),
from = Number(element.style[attr].replace(prefix, '').replace(postfix, '').replace(unit, '')),
positionTick = (to - from) / duration * tick,
running;
setTimeout(moveElement, tick);
function moveElement() {
duration -= tick;
from += positionTick;
element.style[attr] = prefix + from + unit + postfix;
if (duration > 0) {
setTimeout(moveElement, tick);
} else {
callback();
}
}
}
// Format: IIFE
var tns = function(options) {
options = extend({
container: '.slider',
mode: 'carousel',
axis: 'horizontal',
items: 1,
gutter: 0,
edgePadding: 0,
fixedWidth: false,
fixedWidthViewportWidth: false,
slideBy: 1,
controls: true,
controlsText: ['prev', 'next'],
controlsContainer: false,
prevButton: false,
nextButton: false,
nav: true,
navContainer: false,
navAsThumbnails: false,
arrowKeys: false,
speed: 300,
autoplay: false,
autoplayTimeout: 5000,
autoplayDirection: 'forward',
autoplayText: ['start', 'stop'],
autoplayHoverPause: false,
autoplayButton: false,
autoplayButtonOutput: true,
autoplayResetOnVisibility: true,
// animateIn: 'tns-fadeIn',
// animateOut: 'tns-fadeOut',
// animateNormal: 'tns-normal',
// animateDelay: false,
loop: true,
rewind: false,
autoHeight: false,
responsive: false,
lazyload: false,
touch: true,
mouseDrag: false,
swipeAngle: 15,
nested: false,
freezable: true,
// startIndex: 0,
onInit: false,
useLocalStorage: true
}, options || {});
var doc = document,
win = window,
KEYS = {
ENTER: 13,
SPACE: 32,
PAGEUP: 33,
PAGEDOWN: 34,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40
},
CALC,
SUBPIXEL,
CSSMQ,
TRANSFORM,
HAS3D,
TRANSITIONDURATION,
TRANSITIONDELAY,
ANIMATIONDURATION,
ANIMATIONDELAY,
TRANSITIONEND,
ANIMATIONEND,
localStorageAccess = true;
if (options.useLocalStorage) {
// check browser version and local storage
// if browser upgraded,
// 1. delete browser ralated data from local storage and
// 2. recheck these options and save them to local storage
var browserInfo = navigator.userAgent,
tnsStorage = {};
// tC => calc
// tSP => subpixel
// tMQ => mediaquery
// tTf => transform
// tTDu => transitionDuration
// tTDe => transitionDelay
// tADu => animationDuration
// tADe => animationDelay
// tTE => transitionEnd
// tAE => animationEnd
try {
tnsStorage = localStorage;
// remove storage when browser version changes
if (tnsStorage['tnsApp'] && tnsStorage['tnsApp'] !== browserInfo) {
['tC', 'tSP', 'tMQ', 'tTf', 't3D', 'tTDu', 'tTDe', 'tADu', 'tADe', 'tTE', 'tAE'].forEach(function(item) { tnsStorage.removeItem(item); });
}
// update browserInfo
tnsStorage['tnsApp'] = browserInfo;
} catch(e) {
localStorageAccess = false;
}
// reset tnsStorage when localStorage is null (on some versions of Chrome Mobile #134)
// https://stackoverflow.com/questions/8701015/html-localstorage-is-null-on-android-when-using-webview
if (!localStorage) {
tnsStorage = {};
localStorageAccess = false;
}
// get browser related data from local storage if they exist
// otherwise, run the functions again and save these data to local storage
// checkStorageValue() convert non-string value to its original value: 'true' > true
if (localStorageAccess) {
if (tnsStorage['tC']) {
CALC = checkStorageValue(tnsStorage['tC']);
SUBPIXEL = checkStorageValue(tnsStorage['tSP']);
CSSMQ = checkStorageValue(tnsStorage['tMQ']);
TRANSFORM = checkStorageValue(tnsStorage['tTf']);
HAS3D = checkStorageValue(tnsStorage['t3D']);
TRANSITIONDURATION = checkStorageValue(tnsStorage['tTDu']);
TRANSITIONDELAY = checkStorageValue(tnsStorage['tTDe']);
ANIMATIONDURATION = checkStorageValue(tnsStorage['tADu']);
ANIMATIONDELAY = checkStorageValue(tnsStorage['tADe']);
TRANSITIONEND = checkStorageValue(tnsStorage['tTE']);
ANIMATIONEND = checkStorageValue(tnsStorage['tAE']);
} else {
CALC = setLocalStorage('tC', calc());
SUBPIXEL = setLocalStorage('tSP', subpixelLayout());
CSSMQ = setLocalStorage('tMQ', mediaquerySupport());
TRANSFORM = setLocalStorage('tTf', whichProperty('transform'));
HAS3D = setLocalStorage('t3D', has3D(TRANSFORM));
TRANSITIONDURATION = setLocalStorage('tTDu', whichProperty('transitionDuration'));
TRANSITIONDELAY = setLocalStorage('tTDe', whichProperty('transitionDelay'));
ANIMATIONDURATION = setLocalStorage('tADu', whichProperty('animationDuration'));
ANIMATIONDELAY = setLocalStorage('tADe', whichProperty('animationDelay'));
TRANSITIONEND = setLocalStorage('tTE', getEndProperty(TRANSITIONDURATION, 'Transition'));
ANIMATIONEND = setLocalStorage('tAE', getEndProperty(ANIMATIONDURATION, 'Animation'));
}
}
} else {
localStorageAccess = false;
}
if (!localStorageAccess) {
CALC = calc();
SUBPIXEL = subpixelLayout();
CSSMQ = mediaquerySupport();
TRANSFORM = whichProperty('transform');
HAS3D = has3D(TRANSFORM);
TRANSITIONDURATION = whichProperty('transitionDuration');
TRANSITIONDELAY = whichProperty('transitionDelay');
ANIMATIONDURATION = whichProperty('animationDuration');
ANIMATIONDELAY = whichProperty('animationDelay');
TRANSITIONEND = getEndProperty(TRANSITIONDURATION, 'Transition');
ANIMATIONEND = getEndProperty(ANIMATIONDURATION, 'Animation');
}
// reset SUBPIXEL for IE8
if (!CSSMQ) { SUBPIXEL = false; }
// get element nodes from selectors
var supportConsoleWarn = win.console && typeof win.console.warn === "function";
var list = ['container', 'controlsContainer', 'prevButton', 'nextButton', 'navContainer', 'autoplayButton'];
for (var i = list.length; i--;) {
var item = list[i];
if (typeof options[item] === 'string') {
var el = doc.querySelector(options[item]);
if (el && el.nodeName) {
options[item] = el;
} else {
if (supportConsoleWarn) { console.warn('Can\'t find', options[item]); }
return;
}
}
}
// make sure at least 1 slide
if (options.container.children && options.container.children.length < 1) {
if (supportConsoleWarn) { console.warn('No slides found in', options.container); }
return;
}
// update responsive
// from: {
// 300: 2,
// 800: {
// loop: false
// }
// }
// to: {
// 300: {
// items: 2
// },
// 800: {
// loop: false
// }
// }
if (options.responsive) {
var resTem = {}, res = options.responsive;
for(var key in res) {
var val = res[key];
resTem[key] = typeof val === 'number' ? {items: val} : val;
}
options.responsive = resTem;
resTem = null;
// apply responsive[0] to options and remove it
if (0 in options.responsive) {
options = extend(options, options.responsive[0]);
delete options.responsive[0];
}
}
// === define and set variables ===
var carousel = options.mode === 'carousel' ? true : false;
if (!carousel) {
options.axis = 'horizontal';
// options.rewind = false;
// options.loop = true;
options.edgePadding = false;
var animateIn = 'tns-fadeIn',
animateOut = 'tns-fadeOut',
animateDelay = false,
animateNormal = options.animateNormal || 'tns-normal';
if (TRANSITIONEND && ANIMATIONEND) {
animateIn = options.animateIn || animateIn;
animateOut = options.animateOut || animateOut;
animateDelay = options.animateDelay || animateDelay;
}
}
var horizontal = options.axis === 'horizontal' ? true : false,
outerWrapper = doc.createElement('div'),
innerWrapper = doc.createElement('div'),
container = options.container,
containerParent = container.parentNode,
slideItems = container.children,
slideCount = slideItems.length,
vpInner,
responsive = options.responsive,
responsiveItems = [],
breakpoints = false,
breakpointZone = 0,
windowWidth = getWindowWidth(),
isOn;
if (options.fixedWidth) { var vpOuter = getViewportWidth(containerParent); }
if (responsive) {
breakpoints = Object.keys(responsive)
.map(function (x) { return parseInt(x); })
.sort(function (a, b) { return a - b; });
// get all responsive items
breakpoints.forEach(function(bp) {
responsiveItems = responsiveItems.concat(Object.keys(responsive[bp]));
});
// remove duplicated items
var arr = [];
responsiveItems.forEach(function (item) { if (arr.indexOf(item) < 0) { arr.push(item); } });
responsiveItems = arr;
setBreakpointZone();
}
var items = getOption('items'),
slideBy = getOption('slideBy') === 'page' ? items : getOption('slideBy'),
nested = options.nested,
gutter = getOption('gutter'),
edgePadding = getOption('edgePadding'),
fixedWidth = getOption('fixedWidth'),
fixedWidthViewportWidth = options.fixedWidthViewportWidth,
arrowKeys = getOption('arrowKeys'),
speed = getOption('speed'),
rewind = options.rewind,
loop = rewind ? false : options.loop,
autoHeight = getOption('autoHeight'),
sheet = createStyleSheet(),
lazyload = options.lazyload,
slideOffsetTops, // collection of slide offset tops
slideItemsOut = [],
hasEdgePadding = checkOption('edgePadding'),
cloneCount = loop ? getCloneCountForLoop() : 0,
slideCountNew = !carousel ? slideCount + cloneCount : slideCount + cloneCount * 2,
hasRightDeadZone = fixedWidth && !loop && !edgePadding ? true : false,
updateIndexBeforeTransform = (!carousel || !loop) ? true : false,
// transform
transformAttr = horizontal ? 'left' : 'top',
transformPrefix = '',
transformPostfix = '',
// index
startIndex = getOption('startIndex'),
index = startIndex ? updateStartIndex(startIndex) : !carousel ? 0 : cloneCount,
indexCached = index,
indexMin = 0,
indexMax = getIndexMax(),
// resize
resizeTimer,
swipeAngle = options.swipeAngle,
moveDirectionExpected = swipeAngle ? '?' : true,
running = false,
onInit = options.onInit,
events = new Events(),
// id, class
containerIdCached = container.id,
classContainer = ' tns-slider tns-' + options.mode,
slideId = container.id || getSlideId(),
disable = getOption('disable'),
freezable = options.freezable,
freeze = disable ? true : freezable ? slideCount <= items : false,
frozen,
importantStr = nested === 'inner' ? ' !important' : '',
controlsEvents = {
'click': onControlsClick,
'keydown': onControlsKeydown
},
navEvents = {
'click': onNavClick,
'keydown': onNavKeydown
},
hoverEvents = {
'mouseover': mouseoverPause,
'mouseout': mouseoutRestart
},
visibilityEvent = {'visibilitychange': onVisibilityChange},
docmentKeydownEvent = {'keydown': onDocumentKeydown},
touchEvents = {
'touchstart': onPanStart,
'touchmove': onPanMove,
'touchend': onPanEnd,
'touchcancel': onPanEnd
}, dragEvents = {
'mousedown': onPanStart,
'mousemove': onPanMove,
'mouseup': onPanEnd,
'mouseleave': onPanEnd
},
hasControls = checkOption('controls'),
hasNav = checkOption('nav'),
navAsThumbnails = options.navAsThumbnails,
hasAutoplay = checkOption('autoplay'),
hasTouch = checkOption('touch'),
hasMouseDrag = checkOption('mouseDrag'),
slideActiveClass = 'tns-slide-active',
imgCompleteClass = 'tns-complete',
imgEvents = {
'load': imgLoadedOrError,
'error': imgLoadedOrError
},
imgsComplete;
// controls
if (hasControls) {
var controls = getOption('controls'),
controlsText = getOption('controlsText'),
controlsContainer = options.controlsContainer,
prevButton = options.prevButton,
nextButton = options.nextButton,
prevIsButton,
nextIsButton;
}
// nav
if (hasNav) {
var nav = getOption('nav'),
navContainer = options.navContainer,
navItems,
visibleNavIndexes = [],
visibleNavIndexesCached = visibleNavIndexes,
navClicked = -1,
navCurrentIndex = getAbsIndex(),
navCurrentIndexCached = navCurrentIndex,
navActiveClass = 'tns-nav-active';
}
// autoplay
if (hasAutoplay) {
var autoplay = getOption('autoplay'),
autoplayTimeout = getOption('autoplayTimeout'),
autoplayDirection = options.autoplayDirection === 'forward' ? 1 : -1,
autoplayText = getOption('autoplayText'),
autoplayHoverPause = getOption('autoplayHoverPause'),
autoplayButton = options.autoplayButton,
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility'),
autoplayHtmlStrings = ['<span class=\'tns-visually-hidden\'>', ' animation</span>'],
autoplayTimer,
animating,
autoplayHoverPaused,
autoplayUserPaused,
autoplayVisibilityPaused;
}
if (hasTouch || hasMouseDrag) {
var initPosition = {},
lastPosition = {},
translateInit,
disX,
disY,
panStart = false,
rafIndex = 0,
getDist = horizontal ?
function(a, b) { return a.x - b.x; } :
function(a, b) { return a.y - b.y; };
}
// touch
if (hasTouch) {
var touch = getOption('touch');
}
// mouse drag
if (hasMouseDrag) {
var mouseDrag = getOption('mouseDrag');
}
// disable slider when slidecount <= items
if (freeze) {
controls = nav = touch = mouseDrag = arrowKeys = autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
}
if (TRANSFORM) {
transformAttr = TRANSFORM;
transformPrefix = 'translate';
if (HAS3D) {
transformPrefix += horizontal ? '3d(' : '3d(0px, ';
transformPostfix = horizontal ? ', 0px, 0px)' : ', 0px)';
} else {
transformPrefix += horizontal ? 'X(' : 'Y(';
transformPostfix = ')';
}
}
// === COMMON FUNCTIONS === //
function getIndexMax () {
return carousel || loop ? Math.max(0, slideCountNew - items) : slideCountNew - 1;
}
function updateStartIndex (indexTem) {
indexTem = indexTem%slideCount;
if (indexTem < 0) { indexTem += slideCount; }
indexTem = Math.min(indexTem, slideCountNew - items);
return indexTem;
}
function getAbsIndex (i) {
if (i === undefined) { i = index; }
if (carousel) {
while (i < cloneCount) { i += slideCount; }
i -= cloneCount;
}
return i ? i%slideCount : i;
}
function getItemsMax () {
if (fixedWidth && !fixedWidthViewportWidth) {
return slideCount - 1;
} else {
var str = fixedWidth ? 'fixedWidth' : 'items',
arr = [];
if (fixedWidth || options[str] < slideCount) { arr.push(options[str]); }
if (breakpoints && responsiveItems.indexOf(str) >= 0) {
breakpoints.forEach(function(bp) {
var tem = responsive[bp][str];
if (tem && (fixedWidth || tem < slideCount)) { arr.push(tem); }
});
}
if (!arr.length) { arr.push(0); }
return fixedWidth ? Math.ceil(fixedWidthViewportWidth / Math.min.apply(null, arr)) :
Math.max.apply(null, arr);
}
}
function getCloneCountForLoop () {
var itemsMax = getItemsMax(),
result = carousel ? Math.ceil((itemsMax * 5 - slideCount)/2) : (itemsMax * 4 - slideCount);
result = Math.max(itemsMax, result);
return hasEdgePadding ? result + 1 : result;
}
function getWindowWidth () {
return win.innerWidth || doc.documentElement.clientWidth || doc.body.clientWidth;
}
function getViewportWidth (el) {
return el.clientWidth || getViewportWidth(el.parentNode);
}
function checkOption (item) {
var result = options[item];
if (!result && breakpoints && responsiveItems.indexOf(item) >= 0) {
breakpoints.forEach(function (bp) {
if (responsive[bp][item]) { result = true; }
});
}
return result;
}
function getOption (item, viewport) {
viewport = viewport ? viewport : windowWidth;
var obj = {
slideBy: 'page',
edgePadding: false
},
result;
if (!carousel && item in obj) {
result = obj[item];
} else {
if (item === 'items' && getOption('fixedWidth')) {
result = Math.floor(vpOuter / (getOption('fixedWidth') + getOption('gutter')));
} else if (item === 'autoHeight' && nested === 'outer') {
result = true;
} else {
result = options[item];
if (breakpoints && responsiveItems.indexOf(item) >= 0) {
for (var i = 0, len = breakpoints.length; i < len; i++) {
var bp = breakpoints[i];
if (viewport >= bp) {
if (item in responsive[bp]) { result = responsive[bp][item]; }
} else { break; }
}
}
}
}
if (item === 'slideBy' && result === 'page') { result = getOption('items'); }
return result;
}
function getSlideMarginLeft (i) {
var str = CALC ?
CALC + '(' + i * 100 + '% / ' + slideCountNew + ')' :
i * 100 / slideCountNew + '%';
return str;
}
function getInnerWrapperStyles (edgePaddingTem, gutterTem, fixedWidthTem, speedTem) {
var str = '';
if (edgePaddingTem) {
var gap = edgePaddingTem;
if (gutterTem) { gap += gutterTem; }
if (fixedWidthTem) {
str = 'margin: 0px ' + (vpOuter%(fixedWidthTem + gutterTem) + gutterTem) / 2 + 'px;';
} else {
str = horizontal ?
'margin: 0 ' + edgePaddingTem + 'px 0 ' + gap + 'px;' :
'padding: ' + gap + 'px 0 ' + edgePaddingTem + 'px 0;';
}
} else if (gutterTem && !fixedWidthTem) {
var gutterTemUnit = '-' + gutterTem + 'px',
dir = horizontal ? gutterTemUnit + ' 0 0' : '0 ' + gutterTemUnit + ' 0';
str = 'margin: 0 ' + dir + ';';
}
if (TRANSITIONDURATION && speedTem) { str += getTrsnsitionDurationStyle(speedTem); }
return str;
}
function getContainerWidth (fixedWidthTem, gutterTem, itemsTem) {
var str;
if (fixedWidthTem) {
str = (fixedWidthTem + gutterTem) * slideCountNew + 'px';
} else {
str = CALC ?
CALC + '(' + slideCountNew * 100 + '% / ' + itemsTem + ')' :
slideCountNew * 100 / itemsTem + '%';
}
return str;
}
function getSlideWidthStyle (fixedWidthTem, gutterTem, itemsTem) {
var str = '';
if (horizontal) {
str = 'width:';
if (fixedWidthTem) {
str += (fixedWidthTem + gutterTem) + 'px';
} else {
var dividend = carousel ? slideCountNew : itemsTem;
str += CALC ?
CALC + '(100% / ' + dividend + ')' :
100 / dividend + '%';
}
str += importantStr + ';';
}
return str;
}
function getSlideGutterStyle (gutterTem) {
var str = '';
// gutter maybe interger || 0
// so can't use 'if (gutter)'
if (gutterTem !== false) {
var prop = horizontal ? 'padding-' : 'margin-',
dir = horizontal ? 'right' : 'bottom';
str = prop + dir + ': ' + gutterTem + 'px;';
}
return str;
}
function getCSSPrefix (name, num) {
var prefix = name.substring(0, name.length - num).toLowerCase();
if (prefix) { prefix = '-' + prefix + '-'; }
return prefix;
}
function getTrsnsitionDurationStyle (speed) {
return getCSSPrefix(TRANSITIONDURATION, 18) + 'transition-duration:' + speed / 1000 + 's;';
}
function getAnimationDurationStyle (speed) {
return getCSSPrefix(ANIMATIONDURATION, 17) + 'animation-duration:' + speed / 1000 + 's;';
}
(function sliderInit () {
// First thing first, wrap container with 'outerWrapper > innerWrapper',
// to get the correct view width
outerWrapper.appendChild(innerWrapper);
containerParent.insertBefore(outerWrapper, container);
innerWrapper.appendChild(container);
vpInner = getViewportWidth(innerWrapper);
var classOuter = 'tns-outer',
classInner = 'tns-inner',
hasGutter = checkOption('gutter');
if (carousel) {
if (horizontal) {
if (checkOption('edgePadding') || hasGutter && !options.fixedWidth) {
classOuter += ' tns-ovh';
} else {
classInner += ' tns-ovh';
}
} else {
classInner += ' tns-ovh';
}
} else if (hasGutter) {
classOuter += ' tns-ovh';
}
outerWrapper.className = classOuter;
innerWrapper.className = classInner;
innerWrapper.id = slideId + '-iw';
if (autoHeight) { innerWrapper.className += ' tns-ah'; }
// set container properties
if (container.id === '') { container.id = slideId; }
classContainer += SUBPIXEL ? ' tns-subpixel' : ' tns-no-subpixel';
classContainer += CALC ? ' tns-calc' : ' tns-no-calc';
if (carousel) { classContainer += ' tns-' + options.axis; }
container.className += classContainer;
// add event
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
addEvents(container, eve);
}
// delete datas after init
classOuter = classInner = null;
// add id, class, aria attributes
// before clone slides
for (var x = 0; x < slideCount; x++) {
var item = slideItems[x];
if (!item.id) { item.id = slideId + '-item' + x; }
addClass(item, 'tns-item');
if (!carousel && animateNormal) { addClass(item, animateNormal); }
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
// clone slides
if (loop || edgePadding) {
var fragmentBefore = doc.createDocumentFragment(),
fragmentAfter = doc.createDocumentFragment();
for (var j = cloneCount; j--;) {
var num = j%slideCount,
cloneFirst = slideItems[num].cloneNode(true);
removeAttrs(cloneFirst, 'id');
fragmentAfter.insertBefore(cloneFirst, fragmentAfter.firstChild);
if (carousel) {
var cloneLast = slideItems[slideCount - 1 - num].cloneNode(true);
removeAttrs(cloneLast, 'id');
fragmentBefore.appendChild(cloneLast);
}
}
container.insertBefore(fragmentBefore, container.firstChild);
container.appendChild(fragmentAfter);
slideItems = container.children;
}
// add image events
if (checkOption('autoHeight') || !carousel) {
var imgs = container.querySelectorAll('img');
// check all image complete status
// add complete class if true
forEachNodeList(imgs, function(img) {
addEvents(img, imgEvents);
var src = img.src;
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
});
// set imgsComplete to true
// when all images are compulete (loaded or error)
raf(function(){ checkImagesLoaded(arrayFromNodeList(imgs), function() {
imgsComplete = true;
}); });
}
// activate visible slides
// add aria attrs
// set animation classes and left value for gallery slider
// use slide count when slides are fewer than items
for (var i = index, l = index + Math.min(slideCount, items); i < l; i++) {
var item = slideItems[i];
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
if (!carousel) {
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
}
}
if (carousel && horizontal) {
// set font-size rules
// for modern browsers
if (SUBPIXEL) {
// set slides font-size first
addCSSRule(sheet, '#' + slideId + ' > .tns-item', 'font-size:' + win.getComputedStyle(slideItems[0]).fontSize + ';', getCssRulesLength(sheet));
addCSSRule(sheet, '#' + slideId, 'font-size:0;', getCssRulesLength(sheet));
// slide left margin
// for IE8 & webkit browsers (no subpixel)
} else {
forEachNodeList(slideItems, function (slide, i) {
slide.style.marginLeft = getSlideMarginLeft(i);
});
}
}
// all browsers which support CSS transitions support CSS media queries
if (CSSMQ) {
// inner wrapper styles
var str = getInnerWrapperStyles(options.edgePadding, options.gutter, options.fixedWidth, options.speed);
addCSSRule(sheet, '#' + slideId + '-iw', str, getCssRulesLength(sheet));
// container styles
if (carousel) {
str = horizontal ? 'width:' + getContainerWidth(options.fixedWidth, options.gutter, options.items) + ';' : '';
if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); }
addCSSRule(sheet, '#' + slideId, str, getCssRulesLength(sheet));
}
// slide styles
if (horizontal || options.gutter) {
str = getSlideWidthStyle(options.fixedWidth, options.gutter, options.items) +
getSlideGutterStyle(options.gutter);
// set gallery items transition-duration
if (!carousel) {
if (TRANSITIONDURATION) { str += getTrsnsitionDurationStyle(speed); }
if (ANIMATIONDURATION) { str += getAnimationDurationStyle(speed); }
}
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
// non CSS mediaqueries: IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
} else {
// inner wrapper styles
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
// container styles
if (carousel && horizontal) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal || gutter) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// append to the last line
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
}
if (!horizontal && !disable) {
getSlideOffsetTops();
updateContentWrapperHeight();
}
// media queries
if (responsive && CSSMQ) {
breakpoints.forEach(function(bp) {
var opts = responsive[bp],
str = '',
innerWrapperStr = '',
containerStr = '',
slideStr = '',
itemsBP = getOption('items', bp),
fixedWidthBP = getOption('fixedWidth', bp),
speedBP = getOption('speed', bp),
edgePaddingBP = getOption('edgePadding', bp),
gutterBP = getOption('gutter', bp);
// inner wrapper string
if ('edgePadding' in opts || 'gutter' in opts) {
innerWrapperStr = '#' + slideId + '-iw{' + getInnerWrapperStyles(edgePaddingBP, gutterBP, fixedWidthBP, speedBP) + '}';
}
// container string
if (carousel && horizontal && ('fixedWidth' in opts || 'gutter' in opts || 'items' in opts)) {
containerStr = 'width:' + getContainerWidth(fixedWidthBP, gutterBP, itemsBP) + ';';
}
if (TRANSITIONDURATION && 'speed' in opts) {
containerStr += getTrsnsitionDurationStyle(speedBP);
}
if (containerStr) {
containerStr = '#' + slideId + '{' + containerStr + '}';
}
// slide string
if ('fixedWidth' in opts || checkOption('fixedWidth') && 'gutter' in opts || !carousel && 'items' in opts) {
slideStr += getSlideWidthStyle(fixedWidthBP, gutterBP, itemsBP);
}
if ('gutter' in opts) {
slideStr += getSlideGutterStyle(gutterBP);
}
// set gallery items transition-duration
if (!carousel && 'speed' in opts) {
if (TRANSITIONDURATION) { slideStr += getTrsnsitionDurationStyle(speedBP); }
if (ANIMATIONDURATION) { slideStr += getAnimationDurationStyle(speedBP); }
}
if (slideStr) { slideStr = '#' + slideId + ' > .tns-item{' + slideStr + '}'; }
// add up
str = innerWrapperStr + containerStr + slideStr;
if (str) {
sheet.insertRule('@media (min-width: ' + bp / 16 + 'em) {' + str + '}', sheet.cssRules.length);
}
});
}
// set container transform property
if (carousel && !disable) {
doContainerTransformSilent();
}
// == msInit ==
// for IE10
if (navigator.msMaxTouchPoints) {
addClass(container, 'ms-touch');
addEvents(container, {'scroll': ie10Scroll});
setSnapInterval();
}
// == navInit ==
if (hasNav) {
var initIndex = !carousel ? 0 : cloneCount;
// customized nav
// will not hide the navs in case they're thumbnails
if (navContainer) {
setAttrs(navContainer, {'aria-label': 'Carousel Pagination'});
navItems = navContainer.children;
forEachNodeList(navItems, function (item, i) {
setAttrs(item, {
'data-nav': i,
'tabindex': '-1',
'aria-selected': 'false',
'aria-controls': slideItems[initIndex + i].id,
});
});
// generated nav
} else {
var navHtml = '',
hiddenStr = navAsThumbnails ? '' : 'hidden';
for (var i = 0; i < slideCount; i++) {
// hide nav items by default
navHtml += '<button data-nav="' + i +'" tabindex="-1" aria-selected="false" aria-controls="' + slideItems[initIndex + i].id + '" ' + hiddenStr + ' type="button"></button>';
}
navHtml = '<div class="tns-nav" aria-label="Carousel Pagination">' + navHtml + '</div>';
outerWrapper.insertAdjacentHTML('afterbegin', navHtml);
navContainer = outerWrapper.querySelector('.tns-nav');
navItems = navContainer.children;
}
updateNavVisibility();
// add transition
if (TRANSITIONDURATION) {
var prefix = TRANSITIONDURATION.substring(0, TRANSITIONDURATION.length - 18).toLowerCase(),
str = 'transition: all ' + speed / 1000 + 's';
if (prefix) {
str = '-' + prefix + '-' + str;
}
addCSSRule(sheet, '[aria-controls^=' + slideId + '-item]', str, getCssRulesLength(sheet));
}
setAttrs(navItems[navCurrentIndex], {'tabindex': '0', 'aria-selected': 'true'});
addClass(navItems[navCurrentIndex], navActiveClass);
// add events
addEvents(navContainer, navEvents);
if (!nav) { hideElement(navContainer); }
}
// == autoplayInit ==
if (hasAutoplay) {
var txt = autoplay ? 'stop' : 'start';
if (autoplayButton) {
setAttrs(autoplayButton, {'data-action': txt});
} else if (options.autoplayButtonOutput) {
innerWrapper.insertAdjacentHTML('beforebegin', '<button data-action="' + txt + '" type="button">' + autoplayHtmlStrings[0] + txt + autoplayHtmlStrings[1] + autoplayText[0] + '</button>');
autoplayButton = outerWrapper.querySelector('[data-action]');
}
// add event
if (autoplayButton) {
addEvents(autoplayButton, {'click': toggleAutoplay});
}
if (!autoplay) {
if (autoplayButton) {
hideElement(autoplayButton);
}
} else {
startAutoplay();
if (autoplayHoverPause) { addEvents(container, hoverEvents); }
if (autoplayResetOnVisibility) { addEvents(container, visibilityEvent); }
}
}
// == controlsInit ==
if (hasControls) {
if (controlsContainer || (prevButton && nextButton)) {
if (controlsContainer) {
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
setAttrs(controlsContainer, {
'aria-label': 'Carousel Navigation',
'tabindex': '0'
});
setAttrs(controlsContainer.children, {
'aria-controls': slideId,
'tabindex': '-1',
});
}
setAttrs(prevButton, {'data-controls' : 'prev'});
setAttrs(nextButton, {'data-controls' : 'next'});
} else {
outerWrapper.insertAdjacentHTML('afterbegin', '<div class="tns-controls" aria-label="Carousel Navigation" tabindex="0"><button data-controls="prev" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[0] + '</button><button data-controls="next" tabindex="-1" aria-controls="' + slideId +'" type="button">' + controlsText[1] + '</button></div>');
controlsContainer = outerWrapper.querySelector('.tns-controls');
prevButton = controlsContainer.children[0];
nextButton = controlsContainer.children[1];
}
prevIsButton = isButton(prevButton);
nextIsButton = isButton(nextButton);
updateControlsStatus();
// add events
if (controlsContainer) {
addEvents(controlsContainer, controlsEvents);
} else {
addEvents(prevButton, controlsEvents);
addEvents(nextButton, controlsEvents);
}
if (!controls) { hideElement(controlsContainer); }
}
// if (!navigator.msMaxTouchPoints) {
if (carousel) {
if (touch) { addEvents(container, touchEvents); }
if (mouseDrag) { addEvents(container, dragEvents); }
}
// }
if (arrowKeys) { addEvents(doc, docmentKeydownEvent); }
if (nested === 'inner') {
events.on('outerResized', function () {
resizeTasks();
events.emit('innerLoaded', info());
});
} else {
addEvents(win, {'resize': onResize});
}
if (nested === 'outer') {
events.on('innerLoaded', runAutoHeight);
} else if ((autoHeight || !carousel) && !disable) {
runAutoHeight();
}
lazyLoad();
toggleSlideDisplayAndEdgePadding();
updateFixedWidthInnerWrapperStyle();
events.on('indexChanged', additionalUpdates);
if (typeof onInit === 'function') { onInit(info()); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
if (disable) { disableSlider(true); }
isOn = true;
})();
// === ON RESIZE ===
function onResize (e) {
raf(function(){ resizeTasks(getEvent(e)); });
}
function resizeTasks (e) {
if (!isOn) { return; }
windowWidth = getWindowWidth();
if (nested === 'outer') { events.emit('outerResized', info(e)); }
var breakpointZoneTem = breakpointZone,
indexTem = index,
itemsTem = items,
freezeTem = freeze,
needContainerTransform = false;
if (fixedWidth) { vpOuter = getViewportWidth(outerWrapper); }
vpInner = getViewportWidth(innerWrapper);
if (breakpoints) { setBreakpointZone(); }
// things do when breakpoint zone change
if (breakpointZoneTem !== breakpointZone || fixedWidth) {
var slideByTem = slideBy,
arrowKeysTem = arrowKeys,
autoHeightTem = autoHeight,
fixedWidthTem = fixedWidth,
edgePaddingTem = edgePadding,
gutterTem = gutter,
disableTem = disable;
// update variables
items = getOption('items');
slideBy = getOption('slideBy');
disable = getOption('disable');
freeze = disable ? true : freezable ? slideCount <= items : false;
if (items !== itemsTem) {
indexMax = getIndexMax();
// check index before transform in case
// slider reach the right edge then items become bigger
updateIndex();
}
if (disable !== disableTem) {
disableSlider(disable);
}
if (freeze !== freezeTem) {
// reset index to initial status
if (freeze) { index = !carousel ? 0 : cloneCount; }
toggleSlideDisplayAndEdgePadding();
}
if (breakpointZoneTem !== breakpointZone) {
speed = getOption('speed');
edgePadding = getOption('edgePadding');
gutter = getOption('gutter');
fixedWidth = getOption('fixedWidth');
if (!disable && fixedWidth !== fixedWidthTem) {
needContainerTransform = true;
}
autoHeight = getOption('autoHeight');
if (autoHeight !== autoHeightTem) {
if (!autoHeight) { innerWrapper.style.height = ''; }
}
}
arrowKeys = freeze ? false : getOption('arrowKeys');
if (arrowKeys !== arrowKeysTem) {
arrowKeys ?
addEvents(doc, docmentKeydownEvent) :
removeEvents(doc, docmentKeydownEvent);
}
if (hasControls) {
var controlsTem = controls,
controlsTextTem = controlsText;
controls = freeze ? false : getOption('controls');
controlsText = getOption('controlsText');
if (controls !== controlsTem) {
controls ?
showElement(controlsContainer) :
hideElement(controlsContainer);
}
if (controlsText !== controlsTextTem) {
prevButton.innerHTML = controlsText[0];
nextButton.innerHTML = controlsText[1];
}
}
if (hasNav) {
var navTem = nav;
nav = freeze ? false : getOption('nav');
if (nav !== navTem) {
if (nav) {
showElement(navContainer);
updateNavVisibility();
} else {
hideElement(navContainer);
}
}
}
if (hasTouch) {
var touchTem = touch;
touch = freeze ? false : getOption('touch');
if (touch !== touchTem && carousel) {
touch ?
addEvents(container, touchEvents) :
removeEvents(container, touchEvents);
}
}
if (hasMouseDrag) {
var mouseDragTem = mouseDrag;
mouseDrag = freeze ? false : getOption('mouseDrag');
if (mouseDrag !== mouseDragTem && carousel) {
mouseDrag ?
addEvents(container, dragEvents) :
removeEvents(container, dragEvents);
}
}
if (hasAutoplay) {
var autoplayTem = autoplay,
autoplayHoverPauseTem = autoplayHoverPause,
autoplayResetOnVisibilityTem = autoplayResetOnVisibility,
autoplayTextTem = autoplayText;
if (freeze) {
autoplay = autoplayHoverPause = autoplayResetOnVisibility = false;
} else {
autoplay = getOption('autoplay');
if (autoplay) {
autoplayHoverPause = getOption('autoplayHoverPause');
autoplayResetOnVisibility = getOption('autoplayResetOnVisibility');
} else {
autoplayHoverPause = autoplayResetOnVisibility = false;
}
}
autoplayText = getOption('autoplayText');
autoplayTimeout = getOption('autoplayTimeout');
if (autoplay !== autoplayTem) {
if (autoplay) {
if (autoplayButton) { showElement(autoplayButton); }
if (!animating && !autoplayUserPaused) { startAutoplay(); }
} else {
if (autoplayButton) { hideElement(autoplayButton); }
if (animating) { stopAutoplay(); }
}
}
if (autoplayHoverPause !== autoplayHoverPauseTem) {
autoplayHoverPause ?
addEvents(container, hoverEvents) :
removeEvents(container, hoverEvents);
}
if (autoplayResetOnVisibility !== autoplayResetOnVisibilityTem) {
autoplayResetOnVisibility ?
addEvents(doc, visibilityEvent) :
removeEvents(doc, visibilityEvent);
}
if (autoplayButton && autoplayText !== autoplayTextTem) {
var i = autoplay ? 1 : 0,
html = autoplayButton.innerHTML,
len = html.length - autoplayTextTem[i].length;
if (html.substring(len) === autoplayTextTem[i]) {
autoplayButton.innerHTML = html.substring(0, len) + autoplayText[i];
}
}
}
// IE8
// ## update inner wrapper, container, slides if needed
// set inline styles for inner wrapper & container
// insert stylesheet (one line) for slides only (since slides are many)
if (!CSSMQ) {
// inner wrapper styles
if (!freeze && (edgePadding !== edgePaddingTem || gutter !== gutterTem)) {
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
}
// container styles
if (carousel && horizontal && (fixedWidth !== fixedWidthTem || gutter !== gutterTem || items !== itemsTem)) {
container.style.width = getContainerWidth(fixedWidth, gutter, items);
}
// slide styles
if (horizontal && (items !== itemsTem || gutter !== gutterTem || fixedWidth != fixedWidthTem)) {
var str = getSlideWidthStyle(fixedWidth, gutter, items) +
getSlideGutterStyle(gutter);
// remove the last line and
// add new styles
sheet.removeRule(getCssRulesLength(sheet) - 1);
addCSSRule(sheet, '#' + slideId + ' > .tns-item', str, getCssRulesLength(sheet));
}
if (!fixedWidth) { needContainerTransform = true; }
}
if (index !== indexTem) {
events.emit('indexChanged', info());
needContainerTransform = true;
}
if (items !== itemsTem) {
additionalUpdates();
updateSlidePosition();
if (navigator.msMaxTouchPoints) { setSnapInterval(); }
}
}
// things always do regardless of breakpoint zone changing
if (!horizontal && !disable) {
getSlideOffsetTops();
updateContentWrapperHeight();
needContainerTransform = true;
}
if (needContainerTransform) {
doContainerTransformSilent();
indexCached = index;
}
updateFixedWidthInnerWrapperStyle(true);
// auto height
if ((autoHeight || !carousel) && !disable) { runAutoHeight(); }
}
// === INITIALIZATION FUNCTIONS === //
function setBreakpointZone () {
breakpointZone = 0;
breakpoints.forEach(function(bp, i) {
if (windowWidth >= bp) { breakpointZone = i + 1; }
});
}
function loopNumber (num, min, max) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? index - slideCount : index + slideCount;
}
function cutindexber (index, min, indexMax) {
return index >= indexMin && index <= indexMax ? index : index > indexMax ? indexMax : indexMin;
}
// (slideBy, indexMin, indexMax) => index
var updateIndex = (function () {
return loop ?
carousel ?
// loop + carousel
function () {
var leftEdge = indexMin,
rightEdge = indexMax;
leftEdge += slideBy;
rightEdge -= slideBy;
// adjust edges when edge padding is true
// or fixed-width slider with extra space on the right side
if (edgePadding) {
leftEdge += 1;
rightEdge -= 1;
} else if (fixedWidth) {
var gt = gutter ? gutter : 0;
if (vpOuter%(fixedWidth + gt) > gt) { rightEdge -= 1; }
}
if (cloneCount) {
if (index > rightEdge) {
index -= slideCount;
} else if (index < leftEdge) {
index += slideCount;
}
}
} :
// loop + gallery
function() {
if (index > indexMax) {
while (index >= indexMin + slideCount) { index -= slideCount; }
} else if (index < indexMin) {
while (index <= indexMax - slideCount) { index += slideCount; }
}
} :
// non-loop
function() {
index = (index >= indexMin && index <= indexMax) ? index :
index > indexMax ? indexMax : indexMin;
};
})();
function toggleSlideDisplayAndEdgePadding () {
// if (cloneCount) {
// if (fixedWidth && cloneCount) {
var str = 'tns-transparent';
if (freeze) {
if (!frozen) {
// remove edge padding from inner wrapper
if (edgePadding) { innerWrapper.style.margin = '0px'; }
// add class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i--;) {
if (carousel) { addClass(slideItems[i], str); }
addClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = true;
}
} else if (frozen) {
// restore edge padding for inner wrapper
// for mordern browsers
if (edgePadding && !fixedWidth && CSSMQ) { innerWrapper.style.margin = ''; }
// remove class tns-transparent to cloned slides
if (cloneCount) {
for (var i = cloneCount; i--;) {
if (carousel) { removeClass(slideItems[i], str); }
removeClass(slideItems[slideCountNew - i - 1], str);
}
}
frozen = false;
}
// }
}
function updateFixedWidthInnerWrapperStyle (resize) {
if (fixedWidth && edgePadding) {
// remove edge padding when freeze or viewport narrower than one slide
if (freeze || vpOuter <= (fixedWidth + gutter)) {
if (innerWrapper.style.margin !== '0px') { innerWrapper.style.margin = '0px'; }
// update edge padding on resize
} else if (resize) {
innerWrapper.style.cssText = getInnerWrapperStyles(edgePadding, gutter, fixedWidth);
}
}
}
function disableSlider (disable) {
var len = slideItems.length;
if (disable) {
sheet.disabled = true;
container.className = container.className.replace(classContainer.substring(1), '');
removeElementStyles(container);
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { hideElement(slideItems[j]); }
hideElement(slideItems[len - j - 1]);
}
}
// vertical slider
if (!horizontal || !carousel) { removeElementStyles(innerWrapper); }
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i];
removeElementStyles(item);
removeClass(item, animateIn);
removeClass(item, animateNormal);
}
}
} else {
sheet.disabled = false;
container.className += classContainer;
// vertical slider: get offsetTops before container transform
if (!horizontal) { getSlideOffsetTops(); }
doContainerTransformSilent();
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { showElement(slideItems[j]); }
showElement(slideItems[len - j - 1]);
}
}
// gallery
if (!carousel) {
for (var i = index, l = index + slideCount; i < l; i++) {
var item = slideItems[i],
classN = i < index + items ? animateIn : animateNormal;
item.style.left = (i - index) * 100 / items + '%';
addClass(item, classN);
}
}
}
}
// lazyload
function lazyLoad () {
if (lazyload && !disable) {
var i = index,
len = index + items;
if (edgePadding) {
i -=1;
len +=1;
}
i = Math.max(i, 0);
len = Math.min(len, slideCountNew);
for(; i < len; i++) {
forEachNodeList(slideItems[i].querySelectorAll('.tns-lazy-img'), function (img) {
// stop propagationl transitionend event to container
var eve = {};
eve[TRANSITIONEND] = function (e) { e.stopPropagation(); };
addEvents(img, eve);
if (!hasClass(img, 'loaded')) {
img.src = getAttr(img, 'data-src');
addClass(img, 'loaded');
}
});
}
}
}
function imgLoadedOrError (e) {
var img = getTarget(e);
addClass(img, imgCompleteClass);
removeEvents(img, imgEvents);
}
function getImageArray (slideStart, slideRange) {
var imgs = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
forEachNodeList(slideItems[i].querySelectorAll('img'), function (img) {
imgs.push(img);
});
}
return imgs;
}
// check if all visible images are loaded
// and update container height if it's done
function runAutoHeight () {
var imgs = autoHeight ?
getImageArray(index, items) :
getImageArray(cloneCount, slideCount);
raf(function(){ checkImagesLoaded(imgs, updateInnerWrapperHeight); });
}
function checkImagesLoaded (imgs, cb) {
// directly execute callback function if all images are complete
if (imgsComplete) { return cb(); }
// check selected image classes otherwise
imgs.forEach(function (img, index) {
if (hasClass(img, imgCompleteClass)) { imgs.splice(index, 1); }
});
// execute callback function if selected images are all complete
if (!imgs.length) { return cb(); }
// otherwise execute this functiona again
raf(function(){ checkImagesLoaded(imgs, cb); });
}
function additionalUpdates () {
lazyLoad();
updateSlideStatus();
updateControlsStatus();
updateNavVisibility();
updateNavStatus();
}
function getMaxSlideHeight (slideStart, slideRange) {
var heights = [];
for (var i = slideStart, l = slideStart + slideRange; i < l; i++) {
heights.push(slideItems[i].offsetHeight);
}
return Math.max.apply(null, heights);
}
// update inner wrapper height
// 1. get the max-height of the visible slides
// 2. set transitionDuration to speed
// 3. update inner wrapper height to max-height
// 4. set transitionDuration to 0s after transition done
function updateInnerWrapperHeight () {
var maxHeight = autoHeight ?
getMaxSlideHeight(index, items) :
getMaxSlideHeight(cloneCount, slideCount);
if (innerWrapper.style.height !== maxHeight) { innerWrapper.style.height = maxHeight + 'px'; }
}
// get the distance from the top edge of the first slide to each slide
// (init) => slideOffsetTops
function getSlideOffsetTops () {
slideOffsetTops = [0];
var topFirst = slideItems[0].getBoundingClientRect().top, attr;
for (var i = 1; i < slideCountNew; i++) {
attr = slideItems[i].getBoundingClientRect().top;
slideOffsetTops.push(attr - topFirst);
}
}
// set snapInterval (for IE10)
function setSnapInterval () {
outerWrapper.style.msScrollSnapPointsX = 'snapInterval(0%, ' + (100 / items) + '%)';
}
// update slide
function updateSlideStatus () {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i--;) {
var item = slideItems[i];
// visible slides
if (i >= index && i < l) {
if (hasAttr(item, 'tabindex')) {
setAttrs(item, {'aria-hidden': 'false'});
removeAttrs(item, ['tabindex']);
addClass(item, slideActiveClass);
}
// hidden slides
} else {
if (!hasAttr(item, 'tabindex')) {
setAttrs(item, {
'aria-hidden': 'true',
'tabindex': '-1'
});
}
if (hasClass(item, slideActiveClass)) {
removeClass(item, slideActiveClass);
}
}
}
}
// gallery: update slide position
function updateSlidePosition () {
if (!carousel) {
var l = index + Math.min(slideCount, items);
for (var i = slideCountNew; i--;) {
var item = slideItems[i];
if (i >= index && i < l) {
// add transitions to visible slides when adjusting their positions
addClass(item, 'tns-moving');
item.style.left = (i - index) * 100 / items + '%';
addClass(item, animateIn);
removeClass(item, animateNormal);
} else if (item.style.left) {
item.style.left = '';
addClass(item, animateNormal);
removeClass(item, animateIn);
}
// remove outlet animation
removeClass(item, animateOut);
}
// removing '.tns-moving'
setTimeout(function() {
forEachNodeList(slideItems, function(el) {
removeClass(el, 'tns-moving');
});
}, 300);
}
}
// set tabindex & aria-selected on Nav
function updateNavStatus () {
// get current nav
if (nav) {
navCurrentIndex = navClicked !== -1 ? navClicked : getAbsIndex();
navClicked = -1;
if (navCurrentIndex !== navCurrentIndexCached) {
var navPrev = navItems[navCurrentIndexCached],
navCurrent = navItems[navCurrentIndex];
setAttrs(navPrev, {
'tabindex': '-1',
'aria-selected': 'false'
});
setAttrs(navCurrent, {
'tabindex': '0',
'aria-selected': 'true'
});
removeClass(navPrev, navActiveClass);
addClass(navCurrent, navActiveClass);
}
}
}
function getLowerCaseNodeName (el) {
return el.nodeName.toLowerCase();
}
function isButton (el) {
return getLowerCaseNodeName(el) === 'button';
}
function isAriaDisabled (el) {
return el.getAttribute('aria-disabled') === 'true';
}
function disEnableElement (isButton, el, val) {
if (isButton) {
el.disabled = val;
} else {
el.setAttribute('aria-disabled', val.toString());
}
}
// set 'disabled' to true on controls when reach the edges
function updateControlsStatus () {
if (!controls || rewind || loop) { return; }
var prevDisabled = (prevIsButton) ? prevButton.disabled : isAriaDisabled(prevButton),
nextDisabled = (nextIsButton) ? nextButton.disabled : isAriaDisabled(nextButton),
disablePrev = (index === indexMin) ? true : false,
disableNext = (!rewind && index === indexMax) ? true : false;
if (disablePrev && !prevDisabled) {
disEnableElement(prevIsButton, prevButton, true);
}
if (!disablePrev && prevDisabled) {
disEnableElement(prevIsButton, prevButton, false);
}
if (disableNext && !nextDisabled) {
disEnableElement(nextIsButton, nextButton, true);
}
if (!disableNext && nextDisabled) {
disEnableElement(nextIsButton, nextButton, false);
}
}
// set duration
function resetDuration (el, str) {
if (TRANSITIONDURATION) { el.style[TRANSITIONDURATION] = str; }
}
function getContainerTransformValue () {
var val;
if (horizontal) {
if (fixedWidth) {
val = - (fixedWidth + gutter) * index + 'px';
} else {
var denominator = TRANSFORM ? slideCountNew : items;
val = - index * 100 / denominator + '%';
}
} else {
val = - slideOffsetTops[index] + 'px';
}
return val;
}
function doContainerTransformSilent (val) {
resetDuration(container, '0s');
doContainerTransform(val);
setTimeout(function() { resetDuration(container, ''); }, 0);
}
function doContainerTransform (val, test) {
if (!val) { val = getContainerTransformValue(); }
container.style[transformAttr] = transformPrefix + val + transformPostfix;
}
function animateSlide (number, classOut, classIn, isOut) {
var l = number + items;
if (!loop) { l = Math.min(l, slideCountNew); }
for (var i = number; i < l; i++) {
var item = slideItems[i];
// set item positions
if (!isOut) { item.style.left = (i - index) * 100 / items + '%'; }
if (animateDelay && TRANSITIONDELAY) {
item.style[TRANSITIONDELAY] = item.style[ANIMATIONDELAY] = animateDelay * (i - number) / 1000 + 's';
}
removeClass(item, classOut);
addClass(item, classIn);
if (isOut) { slideItemsOut.push(item); }
}
}
// make transfer after click/drag:
// 1. change 'transform' property for mordern browsers
// 2. change 'left' property for legacy browsers
var transformCore = (function () {
return carousel ?
function (duration, distance) {
if (!distance) { distance = getContainerTransformValue(); }
// constrain the distance when non-loop no-edgePadding fixedWidth reaches the right edge
if (hasRightDeadZone && index === indexMax) {
distance = - ((fixedWidth + gutter) * slideCountNew - vpInner) + 'px';
}
if (TRANSITIONDURATION || !duration) {
// for morden browsers with non-zero duration or
// zero duration for all browsers
doContainerTransform(distance);
// run fallback function manually
// when duration is 0 / container is hidden
if (!duration || !isVisible(container)) { onTransitionEnd(); }
} else {
// for old browser with non-zero duration
jsTransform(container, transformAttr, transformPrefix, transformPostfix, distance, speed, onTransitionEnd);
}
if (!horizontal) { updateContentWrapperHeight(); }
} :
function (duration) {
slideItemsOut = [];
var eve = {};
eve[TRANSITIONEND] = eve[ANIMATIONEND] = onTransitionEnd;
removeEvents(slideItems[indexCached], eve);
addEvents(slideItems[index], eve);
animateSlide(indexCached, animateIn, animateOut, true);
animateSlide(index, animateNormal, animateIn);
// run fallback function manually
// when transition or animation not supported / duration is 0
if (!TRANSITIONEND || !ANIMATIONEND || !duration) { onTransitionEnd(); }
};
})();
function doTransform (duration, distance) {
// check duration is defined and is a number
if (isNaN(duration)) { duration = speed; }
// if container is hidden, set duration to 0
// to fix an issue where browser doesn't fire ontransitionend on hidden element
if (animating && !isVisible(container)) { duration = 0; }
transformCore(duration, distance);
}
function render (e, sliderMoved) {
if (updateIndexBeforeTransform) { updateIndex(); }
// render when slider was moved (touch or drag) even though index may not change
if (index !== indexCached || sliderMoved) {
// events
events.emit('indexChanged', info());
events.emit('transitionStart', info());
// pause autoplay when click or keydown from user
if (animating && e && ['click', 'keydown'].indexOf(e.type) >= 0) { stopAutoplay(); }
running = true;
doTransform();
}
}
/*
* Transfer prefixed properties to the same format
* CSS: -Webkit-Transform => webkittransform
* JS: WebkitTransform => webkittransform
* @param {string} str - property
*
*/
function strTrans (str) {
return str.toLowerCase().replace(/-/g, '');
}
// AFTER TRANSFORM
// Things need to be done after a transfer:
// 1. check index
// 2. add classes to visible slide
// 3. disable controls buttons when reach the first/last slide in non-loop slider
// 4. update nav status
// 5. lazyload images
// 6. update container height
function onTransitionEnd (event) {
// check running on gallery mode
// make sure trantionend/animationend events run only once
if (carousel || running) {
events.emit('transitionEnd', info(event));
if (!carousel && slideItemsOut.length > 0) {
for (var i = 0; i < slideItemsOut.length; i++) {
var item = slideItemsOut[i];
// set item positions
item.style.left = '';
if (ANIMATIONDELAY && TRANSITIONDELAY) {
item.style[ANIMATIONDELAY] = '';
item.style[TRANSITIONDELAY] = '';
}
removeClass(item, animateOut);
addClass(item, animateNormal);
}
}
/* update slides, nav, controls after checking ...
* => legacy browsers who don't support 'event'
* have to check event first, otherwise event.target will cause an error
* => or 'gallery' mode:
* + event target is slide item
* => or 'carousel' mode:
* + event target is container,
* + event.property is the same with transform attribute
*/
if (!event ||
!carousel && event.target.parentNode === container ||
event.target === container && strTrans(event.propertyName) === strTrans(transformAttr)) {
if (!updateIndexBeforeTransform) {
var indexTem = index;
updateIndex();
if (index !== indexTem) {
events.emit('indexChanged', info());
doContainerTransformSilent();
}
}
if (autoHeight) { runAutoHeight(); }
if (nested === 'inner') { events.emit('innerLoaded', info()); }
running = false;
navCurrentIndexCached = navCurrentIndex;
indexCached = index;
}
}
}
// # ACTIONS
function goTo (targetIndex, e) {
if (freeze) { return; }
// prev slideBy
if (targetIndex === 'prev') {
onControlsClick(e, -1);
// next slideBy
} else if (targetIndex === 'next') {
onControlsClick(e, 1);
// go to exact slide
} else {
if (running) { onTransitionEnd(); }
// } else if (!running) {
var absIndex = getAbsIndex(),
indexGap = 0;
if (absIndex < 0) { absIndex += slideCount; }
if (targetIndex === 'first') {
indexGap = - absIndex;
} else if (targetIndex === 'last') {
indexGap = carousel ? slideCount - items - absIndex : slideCount - 1 - absIndex;
} else {
if (typeof targetIndex !== 'number') { targetIndex = parseInt(targetIndex); }
if (!isNaN(targetIndex)) {
var absTargetIndex = getAbsIndex(targetIndex);
if (absTargetIndex < 0) { absTargetIndex += slideCount; }
indexGap = absTargetIndex - absIndex;
}
}
index += indexGap;
// if index is changed, start rendering
if (getAbsIndex(index) !== getAbsIndex(indexCached)) {
render(e);
}
}
}
// on controls click
function onControlsClick (e, dir) {
// if (!running) {
if (running) { onTransitionEnd(); }
var passEventObject;
if (!dir) {
e = getEvent(e);
var target = e.target || e.srcElement;
while (target !== controlsContainer && [prevButton, nextButton].indexOf(target) < 0) { target = target.parentNode; }
var targetIn = [prevButton, nextButton].indexOf(target);
if (targetIn >= 0) {
passEventObject = true;
dir = targetIn === 0 ? -1 : 1;
}
}
if (rewind) {
if (index === indexMin && dir === -1) {
goTo('last', e);
return;
} else if (index === indexMax && dir === 1) {
goTo(0, e);
return;
}
}
if (dir) {
index += slideBy * dir;
// pass e when click control buttons or keydown
render((passEventObject || (e && e.type === 'keydown')) ? e : null);
}
// }
}
// on nav click
function onNavClick (e) {
// if (!running) {
if (running) { onTransitionEnd(); }
e = getEvent(e);
var target = e.target || e.srcElement,
navIndex;
// find the clicked nav item
while (target !== navContainer && !hasAttr(target, 'data-nav')) { target = target.parentNode; }
if (hasAttr(target, 'data-nav')) {
navIndex = navClicked = [].indexOf.call(navItems, target);
goTo(navIndex + cloneCount, e);
}
// }
}
// autoplay functions
function setAutoplayTimer () {
autoplayTimer = setInterval(function () {
onControlsClick(null, autoplayDirection);
}, autoplayTimeout);
animating = true;
}
function stopAutoplayTimer () {
clearInterval(autoplayTimer);
animating = false;
}
function updateAutoplayButton (action, txt) {
setAttrs(autoplayButton, {'data-action': action});
autoplayButton.innerHTML = autoplayHtmlStrings[0] + action + autoplayHtmlStrings[1] + txt;
}
function startAutoplay () {
setAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('stop', autoplayText[1]); }
}
function stopAutoplay () {
stopAutoplayTimer();
if (autoplayButton) { updateAutoplayButton('start', autoplayText[0]); }
}
// programaitcally play/pause the slider
function play () {
if (autoplay && !animating) {
startAutoplay();
autoplayUserPaused = false;
}
}
function pause () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
}
}
function toggleAutoplay () {
if (animating) {
stopAutoplay();
autoplayUserPaused = true;
} else {
startAutoplay();
autoplayUserPaused = false;
}
}
function onVisibilityChange () {
if (doc.hidden) {
if (animating) {
stopAutoplayTimer();
autoplayVisibilityPaused = true;
}
} else if (autoplayVisibilityPaused) {
setAutoplayTimer();
autoplayVisibilityPaused = false;
}
}
function mouseoverPause () {
if (animating) {
stopAutoplayTimer();
autoplayHoverPaused = true;
}
}
function mouseoutRestart () {
if (autoplayHoverPaused) {
setAutoplayTimer();
autoplayHoverPaused = false;
}
}
// keydown events on document
function onDocumentKeydown (e) {
e = getEvent(e);
switch(e.keyCode) {
case KEYS.LEFT:
onControlsClick(e, -1);
break;
case KEYS.RIGHT:
onControlsClick(e, 1);
}
}
// on key control
function onControlsKeydown (e) {
e = getEvent(e);
var code = e.keyCode;
switch (code) {
case KEYS.LEFT:
case KEYS.UP:
case KEYS.PAGEUP:
if (!prevButton.disabled) {
onControlsClick(e, -1);
}
break;
case KEYS.RIGHT:
case KEYS.DOWN:
case KEYS.PAGEDOWN:
if (!nextButton.disabled) {
onControlsClick(e, 1);
}
break;
case KEYS.HOME:
goTo(0, e);
break;
case KEYS.END:
goTo(slideCount - 1, e);
break;
}
}
// set focus
function setFocus (focus) {
focus.focus();
}
// on key nav
function onNavKeydown (e) {
var curElement = doc.activeElement;
if (!hasAttr(curElement, 'data-nav')) { return; }
e = getEvent(e);
var code = e.keyCode,
navIndex = [].indexOf.call(navItems, curElement),
len = visibleNavIndexes.length,
current = visibleNavIndexes.indexOf(navIndex);
if (options.navContainer) {
len = slideCount;
current = navIndex;
}
function getNavIndex (num) {
return options.navContainer ? num : visibleNavIndexes[num];
}
switch(code) {
case KEYS.LEFT:
case KEYS.PAGEUP:
if (current > 0) { setFocus(navItems[getNavIndex(current - 1)]); }
break;
case KEYS.UP:
case KEYS.HOME:
if (current > 0) { setFocus(navItems[getNavIndex(0)]); }
break;
case KEYS.RIGHT:
case KEYS.PAGEDOWN:
if (current < len - 1) { setFocus(navItems[getNavIndex(current + 1)]); }
break;
case KEYS.DOWN:
case KEYS.END:
if (current < len - 1) { setFocus(navItems[getNavIndex(len - 1)]); }
break;
// Can't use onNavClick here,
// Because onNavClick require event.target as nav items
case KEYS.ENTER:
case KEYS.SPACE:
navClicked = navIndex;
goTo(navIndex + cloneCount, e);
break;
}
}
// IE10 scroll function
function ie10Scroll () {
transformCore(0, container.scrollLeft);
indexCached = index;
}
function getEvent (e) {
e = e || win.event;
return isTouchEvent(e) ? e.changedTouches[0] : e;
}
function getTarget (e) {
return e.target || win.event.srcElement;
}
function isTouchEvent (e) {
return e.type.indexOf('touch') >= 0;
}
function preventDefaultBehavior (e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
}
function onPanStart (e) {
if (running) { onTransitionEnd(); }
panStart = true;
caf(rafIndex);
rafIndex = raf(function(){ panUpdate(e); });
var $ = getEvent(e);
events.emit(isTouchEvent(e) ? 'touchStart' : 'dragStart', info(e));
if (!isTouchEvent(e) && ['img', 'a'].indexOf(getLowerCaseNodeName(getTarget(e))) >= 0) {
preventDefaultBehavior(e);
}
lastPosition.x = initPosition.x = parseInt($.clientX);
lastPosition.y = initPosition.y = parseInt($.clientY);
translateInit = parseFloat(container.style[transformAttr].replace(transformPrefix, '').replace(transformPostfix, ''));
resetDuration(container, '0s');
}
function onPanMove (e) {
if (panStart) {
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
}
}
function panUpdate (e) {
if (!moveDirectionExpected) {
panStart = false;
return;
}
caf(rafIndex);
if (panStart) { rafIndex = raf(function(){ panUpdate(e); }); }
if (
moveDirectionExpected === '?' &&
lastPosition.x !== initPosition.x &&
lastPosition.y !== initPosition.y) {
moveDirectionExpected = getTouchDirection(toDegree(lastPosition.y - initPosition.y, lastPosition.x - initPosition.x), swipeAngle) === options.axis;
}
if (moveDirectionExpected) {
events.emit(isTouchEvent(e) ? 'touchMove' : 'dragMove', info(e));
var x = translateInit,
dist = getDist(lastPosition, initPosition);
if (!horizontal || fixedWidth) {
x += dist;
x += 'px';
} else {
var percentageX = TRANSFORM ? dist * items * 100 / (vpInner * slideCountNew): dist * 100 / vpInner;
x += percentageX;
x += '%';
}
container.style[transformAttr] = transformPrefix + x + transformPostfix;
}
}
function onPanEnd (e) {
if (swipeAngle) { moveDirectionExpected = '?'; } // reset
if (panStart) {
caf(rafIndex);
resetDuration(container, '');
panStart = false;
var $ = getEvent(e);
lastPosition.x = parseInt($.clientX);
lastPosition.y = parseInt($.clientY);
var dist = getDist(lastPosition, initPosition);
// initPosition = {x:0, y:0}; // reset positions
// lastPosition = {x:0, y:0}; // reset positions
if (Math.abs(dist) >= 5) {
// drag vs click
if (!isTouchEvent(e)) {
// prevent "click"
var target = getTarget(e);
addEvents(target, {'click': function preventClick (e) {
preventDefaultBehavior(e);
removeEvents(target, {'click': preventClick});
}});
}
rafIndex = raf(function() {
events.emit(isTouchEvent(e) ? 'touchEnd' : 'dragEnd', info(e));
if (horizontal) {
var indexMoved = - dist * items / vpInner;
indexMoved = dist > 0 ? Math.floor(indexMoved) : Math.ceil(indexMoved);
index += indexMoved;
} else {
var moved = - (translateInit + dist);
if (moved <= 0) {
index = indexMin;
} else if (moved >= slideOffsetTops[slideOffsetTops.length - 1]) {
index = indexMax;
} else {
var i = 0;
do {
i++;
index = dist < 0 ? i + 1 : i;
} while (i < slideCountNew && moved >= slideOffsetTops[i + 1]);
}
}
render(e, dist);
});
}
}
}
// === RESIZE FUNCTIONS === //
// (slideOffsetTops, index, items) => vertical_conentWrapper.height
function updateContentWrapperHeight () {
innerWrapper.style.height = slideOffsetTops[index + items] - slideOffsetTops[index] + 'px';
}
/*
* get nav item indexes per items
* add 1 more if the nav items cann't cover all slides
* [0, 1, 2, 3, 4] / 3 => [0, 3]
*/
function getVisibleNavIndex () {
// reset visibleNavIndexes
visibleNavIndexes = [];
var absIndexMin = getAbsIndex()%items;
while (absIndexMin < slideCount) {
if (carousel && !loop && absIndexMin + items > slideCount) { absIndexMin = slideCount - items; }
visibleNavIndexes.push(absIndexMin);
absIndexMin += items;
}
// nav count * items < slide count means
// some slides can not be displayed only by nav clicking
if (loop && visibleNavIndexes.length * items < slideCount ||
!loop && visibleNavIndexes[0] > 0) {
visibleNavIndexes.unshift(0);
}
}
/*
* 1. update visible nav items list
* 2. add "hidden" attributes to previous visible nav items
* 3. remove "hidden" attrubutes to new visible nav items
*/
function updateNavVisibility () {
if (!nav || navAsThumbnails) { return; }
getVisibleNavIndex();
if (visibleNavIndexes !== visibleNavIndexesCached) {
forEachNodeList(navItems, function(el, i) {
if (visibleNavIndexes.indexOf(i) < 0) {
hideElement(el);
} else {
showElement(el);
}
});
// cache visible nav indexes
visibleNavIndexesCached = visibleNavIndexes;
}
}
function info (e) {
return {
container: container,
slideItems: slideItems,
navContainer: navContainer,
navItems: navItems,
controlsContainer: controlsContainer,
hasControls: hasControls,
prevButton: prevButton,
nextButton: nextButton,
items: items,
slideBy: slideBy,
cloneCount: cloneCount,
slideCount: slideCount,
slideCountNew: slideCountNew,
index: index,
indexCached: indexCached,
navCurrentIndex: navCurrentIndex,
navCurrentIndexCached: navCurrentIndexCached,
visibleNavIndexes: visibleNavIndexes,
visibleNavIndexesCached: visibleNavIndexesCached,
sheet: sheet,
event: e || {},
};
}
return {
getInfo: info,
events: events,
goTo: goTo,
play: play,
pause: pause,
isOn: isOn,
updateSliderHeight: updateInnerWrapperHeight,
rebuild: function() {
return tns(options);
},
destroy: function () {
// remove win event listeners
removeEvents(win, {'resize': onResize});
// remove arrowKeys eventlistener
removeEvents(doc, docmentKeydownEvent);
// sheet
sheet.disabled = true;
// cloned items
if (loop) {
for (var j = cloneCount; j--;) {
if (carousel) { slideItems[0].remove(); }
slideItems[slideItems.length - 1].remove();
}
}
// Slide Items
var slideClasses = ['tns-item', slideActiveClass];
if (!carousel) { slideClasses = slideClasses.concat('tns-normal', animateIn); }
for (var i = slideCount; i--;) {
var slide = slideItems[i];
if (slide.id.indexOf(slideId + '-item') >= 0) { slide.id = ''; }
slideClasses.forEach(function(cl) { removeClass(slide, cl); });
}
removeAttrs(slideItems, ['style', 'aria-hidden', 'tabindex']);
slideItems = slideId = slideCount = slideCountNew = cloneCount = null;
// controls
if (controls) {
removeEvents(controlsContainer, controlsEvents);
if (options.controlsContainer) {
removeAttrs(controlsContainer, ['aria-label', 'tabindex']);
removeAttrs(controlsContainer.children, ['aria-controls', 'aria-disabled', 'tabindex']);
}
controlsContainer = prevButton = nextButton = null;
}
// nav
if (nav) {
removeEvents(navContainer, navEvents);
if (options.navContainer) {
removeAttrs(navContainer, ['aria-label']);
removeAttrs(navItems, ['aria-selected', 'aria-controls', 'tabindex']);
}
navContainer = navItems = null;
}
// auto
if (autoplay) {
clearInterval(autoplayTimer);
if (autoplayButton) {
removeEvents(autoplayButton, {'click': toggleAutoplay});
}
removeEvents(container, hoverEvents);
removeEvents(container, visibilityEvent);
if (options.autoplayButton) {
removeAttrs(autoplayButton, ['data-action']);
}
}
// container
container.id = containerIdCached || '';
container.className = container.className.replace(classContainer, '');
removeElementStyles(container);
if (carousel && TRANSITIONEND) {
var eve = {};
eve[TRANSITIONEND] = onTransitionEnd;
removeEvents(container, eve);
}
removeEvents(container, touchEvents);
removeEvents(container, dragEvents);
// outerWrapper
containerParent.insertBefore(container, outerWrapper);
outerWrapper.remove();
outerWrapper = innerWrapper = container =
index = indexCached = items = slideBy = navCurrentIndex = navCurrentIndexCached = hasControls = visibleNavIndexes = visibleNavIndexesCached =
this.getInfo = this.events = this.goTo = this.play = this.pause = this.destroy = null;
this.isOn = isOn = false;
}
};
};
return tns;
})(); | jonobr1/cdnjs | ajax/libs/tiny-slider/2.7.3/tiny-slider.js | JavaScript | mit | 89,288 |
function dec(target, name, descriptor) {
assert(target);
assert.equal(typeof name, "string");
assert.equal(typeof descriptor, "object");
target.decoratedProps = (target.decoratedProps || []).concat([name]);
let value = descriptor.value;
Object.assign(descriptor, {
enumerable: name.indexOf("enum") !== -1,
configurable: name.indexOf("conf") !== -1,
writable: name.indexOf("write") !== -1,
value: function(...args) {
return "__" + value.apply(this, args) + "__";
},
});
}
const inst = {
@dec
enumconfwrite(){
return 1;
},
@dec
enumconf(){
return 2;
},
@dec
enumwrite(){
return 3;
},
@dec
enum(){
return 4;
},
@dec
confwrite(){
return 5;
},
@dec
conf(){
return 6;
},
@dec
write(){
return 7;
},
@dec
_(){
return 8;
},
}
assert(inst.hasOwnProperty('decoratedProps'));
assert.deepEqual(inst.decoratedProps, [
"enumconfwrite",
"enumconf",
"enumwrite",
"enum",
"confwrite",
"conf",
"write",
"_",
]);
const descs = Object.getOwnPropertyDescriptors(inst);
assert(descs.enumconfwrite.enumerable);
assert(descs.enumconfwrite.writable);
assert(descs.enumconfwrite.configurable);
assert.equal(inst.enumconfwrite(), "__1__");
assert(descs.enumconf.enumerable);
assert.equal(descs.enumconf.writable, false);
assert(descs.enumconf.configurable);
assert.equal(inst.enumconf(), "__2__");
assert(descs.enumwrite.enumerable);
assert(descs.enumwrite.writable);
assert.equal(descs.enumwrite.configurable, false);
assert.equal(inst.enumwrite(), "__3__");
assert(descs.enum.enumerable);
assert.equal(descs.enum.writable, false);
assert.equal(descs.enum.configurable, false);
assert.equal(inst.enum(), "__4__");
assert.equal(descs.confwrite.enumerable, false);
assert(descs.confwrite.writable);
assert(descs.confwrite.configurable);
assert.equal(inst.confwrite(), "__5__");
assert.equal(descs.conf.enumerable, false);
assert.equal(descs.conf.writable, false);
assert(descs.conf.configurable);
assert.equal(inst.conf(), "__6__");
assert.equal(descs.write.enumerable, false);
assert(descs.write.writable);
assert.equal(descs.write.configurable, false);
assert.equal(inst.write(), "__7__");
assert.equal(descs._.enumerable, false);
assert.equal(descs._.writable, false);
assert.equal(descs._.configurable, false);
assert.equal(inst._(), "__8__");
| ccschneidr/babel | packages/babel-plugin-transform-decorators/test/fixtures/object-methods/mutate-descriptor/exec.js | JavaScript | mit | 2,375 |
/*
Language: Lisp
Description: Generic lisp syntax
Author: Vasily Polovnyov <[email protected]>
Category: lisp
*/
function lisp(hljs) {
var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*';
var MEC_RE = '\\|[^]*?\\|';
var LISP_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?';
var LITERAL = {
className: 'literal',
begin: '\\b(t{1}|nil)\\b'
};
var NUMBER = {
className: 'number',
variants: [
{begin: LISP_SIMPLE_NUMBER_RE, relevance: 0},
{begin: '#(b|B)[0-1]+(/[0-1]+)?'},
{begin: '#(o|O)[0-7]+(/[0-7]+)?'},
{begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'},
{begin: '#(c|C)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, end: '\\)'}
]
};
var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null});
var COMMENT = hljs.COMMENT(
';', '$',
{
relevance: 0
}
);
var VARIABLE = {
begin: '\\*', end: '\\*'
};
var KEYWORD = {
className: 'symbol',
begin: '[:&]' + LISP_IDENT_RE
};
var IDENT = {
begin: LISP_IDENT_RE,
relevance: 0
};
var MEC = {
begin: MEC_RE
};
var QUOTED_LIST = {
begin: '\\(', end: '\\)',
contains: ['self', LITERAL, STRING, NUMBER, IDENT]
};
var QUOTED = {
contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT],
variants: [
{
begin: '[\'`]\\(', end: '\\)'
},
{
begin: '\\(quote ', end: '\\)',
keywords: {name: 'quote'}
},
{
begin: '\'' + MEC_RE
}
]
};
var QUOTED_ATOM = {
variants: [
{begin: '\'' + LISP_IDENT_RE},
{begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'}
]
};
var LIST = {
begin: '\\(\\s*', end: '\\)'
};
var BODY = {
endsWithParent: true,
relevance: 0
};
LIST.contains = [
{
className: 'name',
variants: [
{
begin: LISP_IDENT_RE,
relevance: 0,
},
{begin: MEC_RE}
]
},
BODY
];
BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT];
return {
name: 'Lisp',
illegal: /\S/,
contains: [
NUMBER,
hljs.SHEBANG(),
LITERAL,
STRING,
COMMENT,
QUOTED,
QUOTED_ATOM,
LIST,
IDENT
]
};
}
module.exports = lisp;
| ealbertos/dotfiles | vscode.symlink/extensions/bierner.markdown-preview-github-styles-0.2.0/node_modules/highlight.js/lib/languages/lisp.js | JavaScript | mit | 2,398 |
define(
//begin v1.x content
{
"field-quarter-short-relative+0": "detta kv.",
"field-quarter-short-relative+1": "nästa kv.",
"field-tue-relative+-1": "tisdag förra veckan",
"field-year": "år",
"field-wed-relative+0": "onsdag denna vecka",
"field-wed-relative+1": "onsdag nästa vecka",
"field-minute": "minut",
"field-month-narrow-relative+-1": "förra mån.",
"field-tue-narrow-relative+0": "denna tis.",
"field-tue-narrow-relative+1": "nästa tis.",
"field-thu-short-relative+0": "tors. denna vecka",
"field-day-short-relative+-1": "i går",
"field-thu-short-relative+1": "tors. nästa vecka",
"field-day-relative+0": "i dag",
"field-day-short-relative+-2": "i förrgår",
"field-day-relative+1": "i morgon",
"field-week-narrow-relative+0": "denna v.",
"field-day-relative+2": "i övermorgon",
"field-week-narrow-relative+1": "nästa v.",
"field-wed-narrow-relative+-1": "förra ons.",
"field-year-narrow": "år",
"field-era-short": "era",
"field-year-narrow-relative+0": "i år",
"field-tue-relative+0": "tisdag denna vecka",
"field-year-narrow-relative+1": "nästa år",
"field-tue-relative+1": "tisdag nästa vecka",
"field-weekdayOfMonth": "veckodag i månad",
"field-second-short": "sek",
"field-weekdayOfMonth-narrow": "veckodag i mån.",
"field-week-relative+0": "denna vecka",
"field-month-relative+0": "denna månad",
"field-week-relative+1": "nästa vecka",
"field-month-relative+1": "nästa månad",
"field-sun-narrow-relative+0": "denna sön.",
"field-mon-short-relative+0": "mån. denna vecka",
"field-sun-narrow-relative+1": "nästa sön.",
"field-mon-short-relative+1": "mån. nästa vecka",
"field-second-relative+0": "nu",
"field-weekOfMonth": "vecka i månaden",
"field-month-short": "m",
"field-day": "dag",
"field-dayOfYear-short": "dag under året",
"field-year-relative+-1": "i fjol",
"field-sat-short-relative+-1": "lör. förra veckan",
"field-hour-relative+0": "denna timme",
"field-second-short-relative+0": "nu",
"field-wed-relative+-1": "onsdag förra veckan",
"field-sat-narrow-relative+-1": "förra lör.",
"field-second": "sekund",
"field-hour-short-relative+0": "denna timme",
"field-quarter": "kvartal",
"field-week-short": "v",
"field-day-narrow-relative+0": "idag",
"field-day-narrow-relative+1": "imorgon",
"field-day-narrow-relative+2": "i övermorgon",
"field-tue-short-relative+0": "tis. denna vecka",
"field-tue-short-relative+1": "tis. nästa vecka",
"field-month-short-relative+-1": "förra mån.",
"field-mon-relative+-1": "måndag förra veckan",
"field-month": "månad",
"field-day-narrow": "dag",
"field-minute-short": "min",
"field-dayperiod": "fm/em",
"field-sat-short-relative+0": "lör. denna vecka",
"field-sat-short-relative+1": "lör. nästa vecka",
"field-second-narrow": "s",
"field-mon-relative+0": "måndag denna vecka",
"field-mon-relative+1": "måndag nästa vecka",
"field-day-narrow-relative+-1": "igår",
"field-year-short": "år",
"field-day-narrow-relative+-2": "i förrgår",
"field-quarter-relative+-1": "förra kvartalet",
"field-dayperiod-narrow": "fm/em",
"field-week-narrow-relative+-1": "förra v.",
"field-dayOfYear": "dag under året",
"field-sat-relative+-1": "lördag förra veckan",
"field-hour": "timme",
"field-minute-narrow-relative+0": "denna minut",
"field-month-relative+-1": "förra månaden",
"field-quarter-short": "kv.",
"field-sat-narrow-relative+0": "denna lör.",
"field-fri-relative+0": "fredag denna vecka",
"field-sat-narrow-relative+1": "nästa lör.",
"field-fri-relative+1": "fredag nästa vecka",
"field-month-narrow-relative+0": "denna mån.",
"field-month-narrow-relative+1": "nästa mån.",
"field-sun-short-relative+0": "sön. denna vecka",
"field-sun-short-relative+1": "sön. nästa vecka",
"field-week-relative+-1": "förra veckan",
"field-quarter-short-relative+-1": "förra kv.",
"field-minute-short-relative+0": "denna minut",
"field-quarter-relative+0": "detta kvartal",
"field-minute-relative+0": "denna minut",
"field-quarter-relative+1": "nästa kvartal",
"field-wed-short-relative+-1": "ons. förra veckan",
"field-thu-short-relative+-1": "tors. förra veckan",
"field-year-narrow-relative+-1": "i fjol",
"field-thu-narrow-relative+-1": "förra tors.",
"field-tue-narrow-relative+-1": "förra tis.",
"field-weekOfMonth-short": "vk. i mån.",
"field-wed-short-relative+0": "ons. denna vecka",
"field-wed-short-relative+1": "ons. nästa vecka",
"field-sun-relative+-1": "söndag förra veckan",
"field-second-narrow-relative+0": "nu",
"field-weekday": "veckodag",
"field-day-short-relative+0": "i dag",
"field-quarter-narrow-relative+0": "detta kv.",
"field-sat-relative+0": "lördag denna vecka",
"field-day-short-relative+1": "i morgon",
"field-quarter-narrow-relative+1": "nästa kv.",
"field-sat-relative+1": "lördag nästa vecka",
"field-day-short-relative+2": "i övermorgon",
"field-week-short-relative+0": "denna v.",
"field-week-short-relative+1": "nästa v.",
"field-dayOfYear-narrow": "dag under året",
"field-month-short-relative+0": "denna mån.",
"field-month-short-relative+1": "nästa mån.",
"field-weekdayOfMonth-short": "veckodag i mån.",
"field-zone-narrow": "tidszon",
"field-thu-narrow-relative+0": "denna tors.",
"field-thu-narrow-relative+1": "nästa tors.",
"field-sun-narrow-relative+-1": "förra sön.",
"field-mon-short-relative+-1": "mån. förra veckan",
"field-thu-relative+0": "torsdag denna vecka",
"field-thu-relative+1": "torsdag nästa vecka",
"field-fri-short-relative+-1": "fre. förra veckan",
"field-thu-relative+-1": "torsdag förra veckan",
"field-week": "vecka",
"field-wed-narrow-relative+0": "denna ons.",
"field-wed-narrow-relative+1": "nästa ons.",
"field-quarter-narrow-relative+-1": "förra kv.",
"field-year-short-relative+0": "i år",
"field-dayperiod-short": "fm/em",
"field-year-short-relative+1": "nästa år",
"field-fri-short-relative+0": "fre. denna vecka",
"field-fri-short-relative+1": "fre. nästa vecka",
"field-week-short-relative+-1": "förra v.",
"field-hour-narrow-relative+0": "denna timme",
"field-hour-short": "tim",
"field-zone-short": "tidszon",
"field-month-narrow": "mån",
"field-hour-narrow": "h",
"field-fri-narrow-relative+-1": "förra fre.",
"field-year-relative+0": "i år",
"field-year-relative+1": "nästa år",
"field-era-narrow": "era",
"field-fri-relative+-1": "fredag förra veckan",
"field-tue-short-relative+-1": "tis. förra veckan",
"field-minute-narrow": "m",
"field-year-short-relative+-1": "i fjol",
"field-zone": "tidszon",
"field-weekOfMonth-narrow": "vk.i mån.",
"field-weekday-narrow": "veckodag",
"field-quarter-narrow": "kv.",
"field-sun-short-relative+-1": "sön. förra veckan",
"field-day-relative+-1": "i går",
"field-day-relative+-2": "i förrgår",
"field-weekday-short": "veckodag",
"field-sun-relative+0": "söndag denna vecka",
"field-sun-relative+1": "söndag nästa vecka",
"field-day-short": "dag",
"field-week-narrow": "v",
"field-era": "era",
"field-fri-narrow-relative+0": "denna fre.",
"field-fri-narrow-relative+1": "nästa fre."
}
//end v1.x content
); | cdnjs/cdnjs | ajax/libs/dojo/1.17.1/cldr/nls/sv/dangi.js | JavaScript | mit | 7,152 |
jQuery.fn.nextInArray = function(element) {
var nextId = 0;
for(var i = 0; i < this.length; i++) {
if(this[i] == element) {
nextId = i + 1;
break;
}
}
if(nextId > this.length-1)
nextId = 0;
return this[nextId];
};
jQuery.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return jQuery(':input', this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
jQuery.fn.tagName = function() {
return this.get(0).tagName;
};
jQuery.fn.exists = function(){
return (jQuery(this).size() > 0 ? true : false);
};
function isNumber(val) {
return /^\d+/.test(val);
}
jQuery.fn.serializeAnything = function(addData) {
var toReturn = [];
var els = jQuery(this).find(':input').get();
jQuery.each(els, function() {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
var val = jQuery(this).val();
toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
}
});
if(typeof(addData) != 'undefined') {
for(var key in addData)
toReturn.push(key + "=" + addData[key]);
}
return toReturn.join("&").replace(/%20/g, "+");
};
jQuery.fn.hasScrollBarH = function() {
return this.get(0).scrollHeight > this.height();
};
jQuery.fn.hasScrollBarV = function() {
console.log(this.get(0).scrollWidth, this.width(), this.get(0).scrollHeight, this.height());
return this.get(0).scrollWidth > this.width();
};
function str_replace(haystack, needle, replacement) {
var temp = haystack.split(needle);
return temp.join(replacement);
}
/**
* @see php html::nameToClassId($name) method
**/
function nameToClassId(name) {
return str_replace(
str_replace(name, ']', ''),
'[', ''
);
}
function strpos( haystack, needle, offset){
var i = haystack.indexOf( needle, offset ); // returns -1
return i >= 0 ? i : false;
}
function extend(Child, Parent) {
var F = function() { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype;
}
function toeRedirect(url) {
document.location.href = url;
}
function toeReload() {
document.location.reload();
}
jQuery.fn.toeRebuildSelect = function(data, useIdAsValue, val) {
if(jQuery(this).tagName() == 'SELECT' && typeof(data) == 'object') {
if(jQuery(data).size() > 0) {
if(typeof(val) == 'undefined')
val = false;
if(jQuery(this).children('option').length) {
jQuery(this).children('option').remove();
}
if(typeof(useIdAsValue) == 'undefined')
useIdAsValue = false;
var selected = '';
for(var id in data) {
selected = '';
if(val && ((useIdAsValue && id == val) || (data[id] == val)))
selected = 'selected';
jQuery(this).append('<option value="'+ (useIdAsValue ? id : data[id])+ '" '+ selected+ '>'+ data[id]+ '</option>');
}
}
}
}
/**
* We will not use just jQUery.inArray because it is work incorrect for objects
* @return mixed - key that was found element or -1 if not
*/
function toeInArray(needle, haystack) {
if(typeof(haystack) == 'object') {
for(var k in haystack) {
if(haystack[ k ] == needle)
return k;
}
} else if(typeof(haystack) == 'array') {
return jQuery.inArray(needle, haystack);
}
return -1;
}
jQuery.fn.setReadonly = function() {
jQuery(this).addClass('toeReadonly').attr('readonly', 'readonly');
}
jQuery.fn.unsetReadonly = function() {
jQuery(this).removeClass('toeReadonly').removeAttr('readonly', 'readonly');
}
jQuery.fn.getClassId = function(pref, test) {
var classId = jQuery(this).attr('class');
classId = classId.substr( strpos(classId, pref+ '_') );
if(strpos(classId, ' '))
classId = classId.substr( 0, strpos(classId, ' ') );
classId = classId.split('_');
classId = classId[1];
return classId;
}
function toeTextIncDec(textFieldId, inc) {
var value = parseInt(jQuery('#'+ textFieldId).val());
if(isNaN(value))
value = 0;
if(!(inc < 0 && value < 1)) {
value += inc;
}
jQuery('#'+ textFieldId).val(value);
}
/**
* Make first letter of string in upper case
* @param str string - string to convert
* @return string converted string - first letter in upper case
*/
function toeStrFirstUp(str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
function parseStr (str, array) {
// http://kevin.vanzonneveld.net
// + original by: Cagri Ekin
// + improved by: Michael White (http://getsprink.com)
// + tweaked by: Jack
// + bugfixed by: Onno Marsman
// + reimplemented by: stag019
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: stag019
// + input by: Dreamer
// + bugfixed by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
// + input by: Zaide (http://zaidesthings.com/)
// + input by: David Pesta (http://davidpesta.com/)
// + input by: jeicquest
// + improved by: Brett Zamir (http://brett-zamir.me)
// % note 1: When no argument is specified, will put variables in global scope.
// % note 1: When a particular argument has been passed, and the returned value is different parse_str of PHP. For example, a=b=c&d====c
// * example 1: var arr = {};
// * example 1: parse_str('first=foo&second=bar', arr);
// * results 1: arr == { first: 'foo', second: 'bar' }
// * example 2: var arr = {};
// * example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.', arr);
// * results 2: arr == { str_a: "Jack and Jill didn't see the well." }
// * example 3: var abc = {3:'a'};
// * example 3: parse_str('abc[a][b]["c"]=def&abc[q]=t+5');
// * results 3: JSON.stringify(abc) === '{"3":"a","a":{"b":{"c":"def"}},"q":"t 5"}';
var strArr = String(str).replace(/^&/, '').replace(/&$/, '').split('&'),
sal = strArr.length,
i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
postLeftBracketPos, keys, keysLen,
fixStr = function (str) {
return decodeURIComponent(str.replace(/\+/g, '%20'));
};
// Comented by Alexey Bolotov
/*
if (!array) {
array = this.window;
}*/
if (!array) {
array = {};
}
for (i = 0; i < sal; i++) {
tmp = strArr[i].split('=');
key = fixStr(tmp[0]);
value = (tmp.length < 2) ? '' : fixStr(tmp[1]);
while (key.charAt(0) === ' ') {
key = key.slice(1);
}
if (key.indexOf('\x00') > -1) {
key = key.slice(0, key.indexOf('\x00'));
}
if (key && key.charAt(0) !== '[') {
keys = [];
postLeftBracketPos = 0;
for (j = 0; j < key.length; j++) {
if (key.charAt(j) === '[' && !postLeftBracketPos) {
postLeftBracketPos = j + 1;
} else if (key.charAt(j) === ']') {
if (postLeftBracketPos) {
if (!keys.length) {
keys.push(key.slice(0, postLeftBracketPos - 1));
}
keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
postLeftBracketPos = 0;
if (key.charAt(j + 1) !== '[') {
break;
}
}
}
}
if (!keys.length) {
keys = [key];
}
for (j = 0; j < keys[0].length; j++) {
chr = keys[0].charAt(j);
if (chr === ' ' || chr === '.' || chr === '[') {
keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
}
if (chr === '[') {
break;
}
}
obj = array;
for (j = 0, keysLen = keys.length; j < keysLen; j++) {
key = keys[j].replace(/^['"]/, '').replace(/['"]$/, '');
lastIter = j !== keys.length - 1;
lastObj = obj;
if ((key !== '' && key !== ' ') || j === 0) {
if (obj[key] === undef) {
obj[key] = {};
}
obj = obj[key];
} else { // To insert new dimension
ct = -1;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
if (+p > ct && p.match(/^\d+$/g)) {
ct = +p;
}
}
}
key = ct + 1;
}
}
lastObj[key] = value;
}
}
return array;
}
function toeListable(params) {
this.params = jQuery.extend({}, params);
this.table = jQuery(this.params.table);
this.paging = jQuery(this.params.paging);
this.perPage = this.params.perPage;
this.list = this.params.list;
this.count = this.params.count;
this.page = this.params.page;
this.pagingCallback = this.params.pagingCallback;
var self = this;
this.draw = function(list, count) {
this.table.find('tr').not('.gmpExample, .gmpTblHeader').remove();
var exampleRow = this.table.find('.gmpExample');
for(var i in list) {
var newRow = exampleRow.clone();
for(var key in list[i]) {
var element = newRow.find('.'+ key);
if(element.size()) {
var valueTo = element.attr('valueTo');
if(valueTo) {
var newValue = list[i][key];
var prevValue = element.attr(valueTo);
if(prevValue)
newValue = prevValue+ ' '+ newValue;
element.attr(valueTo, newValue);
} else
element.html(list[i][key]);
}
}
newRow.removeClass('gmpExample').show();
this.table.append(newRow);
}
if(this.paging) {
this.paging.html('');
if(count && count > list.length && this.perPage) {
for(var i = 1; i <= Math.ceil(count/this.perPage); i++) {
var newPageId = i-1
, newElement = (newPageId == this.page) ? jQuery('<b/>') : jQuery('<a/>');
if(newPageId != this.page) {
newElement.attr('href', '#'+ newPageId)
.click(function(){
if(self.pagingCallback && typeof(self.pagingCallback) == 'function') {
self.pagingCallback(parseInt(jQuery(this).attr('href').replace('#', '')));
return false;
}
});
}
newElement.addClass('toePagingElement').html(i);
this.paging.append(newElement);
}
}
}
}
if(this.list)
this.draw(this.list, this.count);
}
function setCookieGmp(c_name, value, exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookieGmp(name) {
var parts = document.cookie.split(name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
return null;
}
function getImgSize(url, callback) {
jQuery('<img/>').attr('src', url).load(function(){
callback({w: this.width, h: this.height});
});
}
function callUserFuncArray(cb, parameters) {
// http://kevin.vanzonneveld.net
// + original by: Thiago Mata (http://thiagomata.blog.com)
// + revised by: Jon Hohle
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Diplom@t (http://difane.com/)
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: call_user_func_array('isNaN', ['a']);
// * returns 1: true
// * example 2: call_user_func_array('isNaN', [1]);
// * returns 2: false
var func;
if (typeof cb === 'string') {
func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))();
}
else if (Object.prototype.toString.call(cb) === '[object Array]') {
func = (typeof cb[0] == 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]];
}
else if (typeof cb === 'function') {
func = cb;
}
if (typeof func !== 'function') {
throw new Error(func + ' is not a valid function');
}
return (typeof cb[0] === 'string') ? func.apply(eval(cb[0]), parameters) : (typeof cb[0] !== 'object') ? func.apply(null, parameters) : func.apply(cb[0], parameters);
}
| nikakoss/arsenal-media.net | wp-content/plugins/google-maps-ready/js/common.js | JavaScript | gpl-2.0 | 12,013 |
var Deferred = require('./')
var assert = require('assert')
var d = new Deferred()
var t = require('tap')
t.match(d, {
resolve: Function,
reject: Function,
promise: Object
})
| gerrytucker78/emse_capstone_project | services/node_modules/nodeunit/node_modules/tap/node_modules/trivial-deferred/test.js | JavaScript | gpl-3.0 | 181 |
/* TL.Point
Inspired by Leaflet
TL.Point represents a point with x and y coordinates.
================================================== */
TL.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
this.x = (round ? Math.round(x) : x);
this.y = (round ? Math.round(y) : y);
};
TL.Point.prototype = {
add: function (point) {
return this.clone()._add(point);
},
_add: function (point) {
this.x += point.x;
this.y += point.y;
return this;
},
subtract: function (point) {
return this.clone()._subtract(point);
},
// destructive subtract (faster)
_subtract: function (point) {
this.x -= point.x;
this.y -= point.y;
return this;
},
divideBy: function (num, round) {
return new TL.Point(this.x / num, this.y / num, round);
},
multiplyBy: function (num) {
return new TL.Point(this.x * num, this.y * num);
},
distanceTo: function (point) {
var x = point.x - this.x,
y = point.y - this.y;
return Math.sqrt(x * x + y * y);
},
round: function () {
return this.clone()._round();
},
// destructive round
_round: function () {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
},
clone: function () {
return new TL.Point(this.x, this.y);
},
toString: function () {
return 'Point(' +
TL.Util.formatNum(this.x) + ', ' +
TL.Util.formatNum(this.y) + ')';
}
}; | tkandala/TimelineJS3 | source/js/dom/TL.Point.js | JavaScript | mpl-2.0 | 1,360 |
var classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser =
[
[ "Deserialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a5e8aa7ae1372033da215d02b79947b20.html#a5e8aa7ae1372033da215d02b79947b20", null ],
[ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a4aec60f5df74f482b576f4e0dad0d5f6.html#a4aec60f5df74f482b576f4e0dad0d5f6", null ],
[ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a2362ae784859054bf5b9281dafeb37cd.html#a2362ae784859054bf5b9281dafeb37cd", null ],
[ "ValueType", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_af5d06e2fe995f816c840a8ceefd22991.html#af5d06e2fe995f816c840a8ceefd22991", null ]
]; | Chinchilla-Software-Com/CQRS | wiki/docs/2.4/html/classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser.js | JavaScript | lgpl-2.1 | 693 |
//// [privateIdentifierChain.1.ts]
class A {
a?: A
#b?: A;
getA(): A {
return new A();
}
constructor() {
this?.#b; // Error
this?.a.#b; // Error
this?.getA().#b; // Error
}
}
//// [privateIdentifierChain.1.js]
"use strict";
class A {
constructor() {
this?.#b; // Error
this?.a.#b; // Error
this?.getA().#b; // Error
}
#b;
getA() {
return new A();
}
}
| Microsoft/TypeScript | tests/baselines/reference/privateIdentifierChain.1.js | JavaScript | apache-2.0 | 498 |
/* Uncaught exception
* Output: EH_UNCAUGHT_EXCEPTION */
function throwsException() {
throw new Error();
}
function doSomething() {
try {
throwsException();
}
catch (e) { }
}
function doSomethingElse() {
throwsException();
}
doSomething();
doSomethingElse();
| qhanam/Pangor | js/test/input/error_handling/eh_methods_old.js | JavaScript | apache-2.0 | 272 |
/**
* Copyright 2013-2014 Facebook, Inc.
*
* 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.
*
* @providesModule ReactBrowserEventEmitter
* @typechecks static-only
*/
"use strict";
var EventConstants = require("./EventConstants");
var EventPluginHub = require("./EventPluginHub");
var EventPluginRegistry = require("./EventPluginRegistry");
var ReactEventEmitterMixin = require("./ReactEventEmitterMixin");
var ViewportMetrics = require("./ViewportMetrics");
var isEventSupported = require("./isEventSupported");
var merge = require("./merge");
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topBlur: 'blur',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topScroll: 'scroll',
topSelectionChange: 'selectionchange',
topTextInput: 'textInput',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = merge(ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function(ReactEventListener) {
ReactEventListener.setHandleTopLevel(
ReactBrowserEventEmitter.handleTopLevel
);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function(enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function() {
return !!(
ReactBrowserEventEmitter.ReactEventListener &&
ReactBrowserEventEmitter.ReactEventListener.isEnabled()
);
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function(registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.
registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0, l = dependencies.length; i < l; i++) {
var dependency = dependencies[i];
if (!(
isListening.hasOwnProperty(dependency) &&
isListening[dependency]
)) {
if (dependency === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topWheel,
'wheel',
mountAt
);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topWheel,
'mousewheel',
mountAt
);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topWheel,
'DOMMouseScroll',
mountAt
);
}
} else if (dependency === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelTypes.topScroll,
'scroll',
mountAt
);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topScroll,
'scroll',
ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE
);
}
} else if (dependency === topLevelTypes.topFocus ||
dependency === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelTypes.topFocus,
'focus',
mountAt
);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelTypes.topBlur,
'blur',
mountAt
);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topFocus,
'focusin',
mountAt
);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelTypes.topBlur,
'focusout',
mountAt
);
}
// to make sure blur and focus event listeners are only attached once
isListening[topLevelTypes.topBlur] = true;
isListening[topLevelTypes.topFocus] = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
dependency,
topEventMapping[dependency],
mountAt
);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function(topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(
topLevelType,
handlerBaseName,
handle
);
},
trapCapturedEvent: function(topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(
topLevelType,
handlerBaseName,
handle
);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function(){
if (!isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
},
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
registrationNameModules: EventPluginHub.registrationNameModules,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners
});
module.exports = ReactBrowserEventEmitter;
| KnisterPeter/jreact | src/test/resources/react-0.11/node_modules/react/lib/ReactBrowserEventEmitter.js | JavaScript | bsd-2-clause | 12,568 |
/**
* 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.
*
* @flow strict
* @format
*/
'use strict';
const {polyfillObjectProperty} = require('../Utilities/PolyfillFunctions');
let navigator = global.navigator;
if (navigator === undefined) {
global.navigator = navigator = {};
}
// see https://github.com/facebook/react-native/issues/10881
polyfillObjectProperty(navigator, 'product', () => 'ReactNative');
| pandiaraj44/react-native | Libraries/Core/setUpNavigator.js | JavaScript | bsd-3-clause | 545 |
version https://git-lfs.github.com/spec/v1
oid sha256:ff6a5c1204e476c89870c6f14e75db666fa26de9359f9d8c372ef779b55c8875
size 2736
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.8.9/cldr/nls/cs/buddhist.js.uncompressed.js | JavaScript | mit | 129 |
function example(name, deps) {
console.log('This is where fpscounter plugin code would execute in the node process.');
}
module.exports = example; | BenjaminTsai/openrov-cockpit | src/plugins/fpscounter/index.js | JavaScript | mit | 148 |
// Node
if (typeof module !== 'undefined' && module.exports) {
var numeral = require('../../numeral');
var expect = require('chai').expect;
var language = require('../../languages/th');
}
describe('Language: th', function() {
before(function() {
numeral.language('th', language);
numeral.language('th');
});
after(function() {
numeral.reset();
});
describe('Number', function() {
it('should format a number', function() {
var tests = [
[10000,'0,0.0000','10,000.0000'],
[10000.23,'0,0','10,000'],
[-10000,'0,0.0','-10,000.0'],
[10000.1234,'0.000','10000.123'],
[-10000,'(0,0.0000)','(10,000.0000)'],
[-0.23,'.00','-.23'],
[-0.23,'(.00)','(.23)'],
[0.23,'0.00000','0.23000'],
[1230974,'0.0a','1.2ล้าน'],
[1460,'0a','1พัน'],
[-104000,'0a','-104พัน'],
[1,'0o','1.'],
[52,'0o','52.'],
[23,'0o','23.'],
[100,'0o','100.'],
[1,'0[.]0','1']
];
for (var i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
}
});
});
describe('Currency', function() {
it('should format a currency', function() {
var tests = [
[1000.234,'$0,0.00','฿1,000.23'],
[-1000.234,'($0,0)','(฿1,000)'],
[-1000.234,'$0.00','-฿1000.23'],
[1230974,'($0.00a)','฿1.23ล้าน']
];
for (var i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
}
});
});
describe('Percentages', function() {
it('should format a percentages', function() {
var tests = [
[1,'0%','100%'],
[0.974878234,'0.000%','97.488%'],
[-0.43,'0%','-43%'],
[0.43,'(0.000%)','43.000%']
];
for (var i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
}
});
});
describe('Unformat', function() {
it('should unformat', function() {
var tests = [
['10,000.123',10000.123],
['(0.12345)',-0.12345],
['(฿1.23ล้าน)',-1230000],
['10พัน',10000],
['-10พัน',-10000],
['23.',23],
['฿10,000.00',10000],
['-76%',-0.76],
['2:23:57',8637]
];
for (var i = 0; i < tests.length; i++) {
expect(numeral().unformat(tests[i][0])).to.equal(tests[i][1]);
}
});
});
});
| Nrupesh29/Web-Traffic-Visualizer | vizceral/node_modules/numeral/tests/languages/th.js | JavaScript | mit | 3,021 |
'use strict';
var BigNumber = require('../../type/BigNumber');
var Range = require('../../type/Range');
var Index = require('../../type/Index');
var isNumber = require('../../util/number').isNumber;
/**
* Attach a transform function to math.index
* Adds a property transform containing the transform function.
*
* This transform creates a one-based index instead of a zero-based index
* @param {Object} math
*/
module.exports = function (math) {
var transform = function () {
var args = [];
for (var i = 0, ii = arguments.length; i < ii; i++) {
var arg = arguments[i];
// change from one-based to zero based, and convert BigNumber to number
if (arg instanceof Range) {
arg.start--;
arg.end -= (arg.step > 0 ? 0 : 2);
}
else if (isNumber(arg)) {
arg--;
}
else if (arg instanceof BigNumber) {
arg = arg.toNumber() - 1;
}
else {
throw new TypeError('Ranges must be a Number or Range');
}
args[i] = arg;
}
var res = new Index();
Index.apply(res, args);
return res;
};
math.index.transform = transform;
return transform;
};
| MonoHearted/Flowerbless | node_modules/mathjs/lib/expression/transform/index.transform.js | JavaScript | mit | 1,170 |
define("ace/snippets/typescript",["require","exports","module"],function(e,t,n){"use strict";t.snippetText="",t.scope="typescript"});
(function() {
window.require(["ace/snippets/typescript"], function(m) {
if (typeof module == "object") {
module.exports = m;
}
});
})();
| holtkamp/cdnjs | ajax/libs/ace/1.3.2/snippets/typescript.js | JavaScript | mit | 431 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var React = _interopRequireWildcard(require("react"));
var _createSvgIcon = _interopRequireDefault(require("../../utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
/**
* @ignore - internal component.
*/
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"
}), 'Star');
exports.default = _default; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.36/node/internal/svg-icons/Star.js | JavaScript | mit | 738 |
// Copyright 2012 Mark Cavage, Inc. All rights reserved.
'use strict';
///--- Exports
/**
* JSONP formatter. like JSON, but with a callback invocation.
*
* Unicode escapes line and paragraph separators.
*
* @public
* @function formatJSONP
* @param {Object} req the request object
* @param {Object} res the response object
* @param {Object} body response body
* @returns {String}
*/
function formatJSONP(req, res, body) {
if (!body) {
res.setHeader('Content-Length', 0);
return (null);
}
if (Buffer.isBuffer(body)) {
body = body.toString('base64');
}
var _cb = req.query.callback || req.query.jsonp;
var data;
if (_cb) {
data = 'typeof ' + _cb + ' === \'function\' && ' +
_cb + '(' + JSON.stringify(body) + ');';
} else {
data = JSON.stringify(body);
}
data = data.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
res.setHeader('Content-Length', Buffer.byteLength(data));
return data;
}
module.exports = formatJSONP;
| eduardomrodrigues/atabey | ws-api/node_modules/restify/lib/formatters/jsonp.js | JavaScript | gpl-3.0 | 1,081 |
/*
Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
(function(){CKEDITOR.on("dialogDefinition",function(a){var b;b=a.data.name;a=a.data.definition;"link"==b?(a.removeContents("target"),a.removeContents("upload"),a.removeContents("advanced"),b=a.getContents("info"),b.remove("emailSubject"),b.remove("emailBody")):"image"==b&&(a.removeContents("advanced"),b=a.getContents("Link"),b.remove("cmbTarget"),b=a.getContents("info"),b.remove("txtAlt"),b.remove("basic"))});var l={b:"strong",u:"u",i:"em",color:"span",size:"span",left:"div",right:"div",center:"div",
justify:"div",quote:"blockquote",code:"code",url:"a",email:"span",img:"span","*":"li",list:"ol"},x={strong:"b",b:"b",u:"u",em:"i",i:"i",code:"code",li:"*"},m={strong:"b",em:"i",u:"u",li:"*",ul:"list",ol:"list",code:"code",a:"link",img:"img",blockquote:"quote"},y={color:"color",size:"font-size",left:"text-align",center:"text-align",right:"text-align",justify:"text-align"},z={url:"href",email:"mailhref",quote:"cite",list:"listType"},n=CKEDITOR.dtd,A=CKEDITOR.tools.extend({table:1},n.$block,n.$listItem,
n.$tableContent,n.$list),C=/\s*(?:;\s*|$)/,q={smiley:":)",sad:":(",wink:";)",laugh:":D",cheeky:":P",blush:":*)",surprise:":-o",indecision:":|",angry:"\x3e:(",angel:"o:)",cool:"8-)",devil:"\x3e:-)",crying:";(",kiss:":-*"},B={},r=[],t;for(t in q)B[q[t]]=t,r.push(q[t].replace(/\(|\)|\:|\/|\*|\-|\|/g,function(a){return"\\"+a}));var r=new RegExp(r.join("|"),"g"),D=function(){var a=[],b={nbsp:" ",shy:""},c;for(c in b)a.push(c);a=new RegExp("\x26("+a.join("|")+");","g");return function(c){return c.replace(a,
function(e,a){return b[a]})}}();CKEDITOR.BBCodeParser=function(){this._={bbcPartsRegex:/(?:\[([^\/\]=]*?)(?:=([^\]]*?))?\])|(?:\[\/([a-z]{1,16})\])/ig}};CKEDITOR.BBCodeParser.prototype={parse:function(a){for(var b,c,k=0;b=this._.bbcPartsRegex.exec(a);)if(c=b.index,c>k&&(k=a.substring(k,c),this.onText(k,1)),k=this._.bbcPartsRegex.lastIndex,(c=(b[1]||b[3]||"").toLowerCase())&&!l[c])this.onText(b[0]);else if(b[1]){var e=l[c],g={},h={};b=b[2];if("left"==c||"right"==c||"center"==c||"justify"==c)b=c;if(b)if("list"==
c&&(isNaN(b)?/^[a-z]+$/.test(b)?b="lower-alpha":/^[A-Z]+$/.test(b)&&(b="upper-alpha"):b="decimal"),y[c]){"size"==c&&(b+="%");h[y[c]]=b;b=g;var f="",d=void 0;for(d in h)var u=(d+":"+h[d]).replace(C,";"),f=f+u;b.style=f}else z[c]&&(g[z[c]]=CKEDITOR.tools.htmlDecode(b));if("email"==c||"img"==c)g.bbcode=c;this.onTagOpen(e,g,CKEDITOR.dtd.$empty[e])}else if(b[3])this.onTagClose(l[c]);if(a.length>k)this.onText(a.substring(k,a.length),1)}};CKEDITOR.htmlParser.fragment.fromBBCode=function(a){function b(e){if(0<
h.length)for(var a=0;a<h.length;a++){var b=h[a],c=b.name,g=CKEDITOR.dtd[c],f=d.name&&CKEDITOR.dtd[d.name];f&&!f[c]||e&&g&&!g[e]&&CKEDITOR.dtd[e]||(b=b.clone(),b.parent=d,d=b,h.splice(a,1),a--)}}function c(a,e){var b=d.children.length,c=0<b&&d.children[b-1],b=!c&&v.getRule(m[d.name],"breakAfterOpen"),c=c&&c.type==CKEDITOR.NODE_ELEMENT&&v.getRule(m[c.name],"breakAfterClose"),g=a&&v.getRule(m[a],e?"breakBeforeClose":"breakBeforeOpen");f&&(b||c||g)&&f--;f&&a in A&&f++;for(;f&&f--;)d.children.push(new CKEDITOR.htmlParser.element("br"))}
function k(a,e){c(a.name,1);e=e||d||g;var b=e.children.length;a.previous=0<b&&e.children[b-1]||null;a.parent=e;e.children.push(a);a.returnPoint&&(d=a.returnPoint,delete a.returnPoint)}var e=new CKEDITOR.BBCodeParser,g=new CKEDITOR.htmlParser.fragment,h=[],f=0,d=g,u;e.onTagOpen=function(a,g){var f=new CKEDITOR.htmlParser.element(a,g);if(CKEDITOR.dtd.$removeEmpty[a])h.push(f);else{var w=d.name,p=w&&(CKEDITOR.dtd[w]||(d._.isBlockLike?CKEDITOR.dtd.div:CKEDITOR.dtd.span));if(p&&!p[a]){var p=!1,l;a==w?
k(d,d.parent):(a in CKEDITOR.dtd.$listItem?(e.onTagOpen("ul",{}),l=d):(k(d,d.parent),h.unshift(d)),p=!0);d=l?l:d.returnPoint||d.parent;if(p){e.onTagOpen.apply(this,arguments);return}}b(a);c(a);f.parent=d;f.returnPoint=u;u=0;f.isEmpty?k(f):d=f}};e.onTagClose=function(a){for(var e=h.length-1;0<=e;e--)if(a==h[e].name){h.splice(e,1);return}for(var b=[],c=[],g=d;g.type&&g.name!=a;)g._.isBlockLike||c.unshift(g),b.push(g),g=g.parent;if(g.type){for(e=0;e<b.length;e++)a=b[e],k(a,a.parent);d=g;k(g,g.parent);
g==d&&(d=d.parent);h=h.concat(c)}};e.onText=function(a){var e=CKEDITOR.dtd[d.name];if(!e||e["#"])c(),b(),a.replace(/(\r\n|[\r\n])|[^\r\n]*/g,function(a,e){if(void 0!==e&&e.length)f++;else if(a.length){var b=0;a.replace(r,function(e,c){k(new CKEDITOR.htmlParser.text(a.substring(b,c)),d);k(new CKEDITOR.htmlParser.element("smiley",{desc:B[e]}),d);b=c+e.length});b!=a.length&&k(new CKEDITOR.htmlParser.text(a.substring(b,a.length)),d)}})};for(e.parse(CKEDITOR.tools.htmlEncode(a));d.type!=CKEDITOR.NODE_DOCUMENT_FRAGMENT;)a=
d.parent,k(d,a),d=a;return g};var v=new (CKEDITOR.tools.createClass({$:function(){this._={output:[],rules:[]};this.setRules("list",{breakBeforeOpen:1,breakAfterOpen:1,breakBeforeClose:1,breakAfterClose:1});this.setRules("*",{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:1,breakAfterClose:0});this.setRules("quote",{breakBeforeOpen:1,breakAfterOpen:0,breakBeforeClose:0,breakAfterClose:1})},proto:{setRules:function(a,b){var c=this._.rules[a];c?CKEDITOR.tools.extend(c,b,!0):this._.rules[a]=b},getRule:function(a,
b){return this._.rules[a]&&this._.rules[a][b]},openTag:function(a){a in l&&(this.getRule(a,"breakBeforeOpen")&&this.lineBreak(1),this.write("[",a))},openTagClose:function(a){"br"==a?this._.output.push("\n"):a in l&&(this.write("]"),this.getRule(a,"breakAfterOpen")&&this.lineBreak(1))},attribute:function(a,b){"option"==a&&this.write("\x3d",b)},closeTag:function(a){a in l&&(this.getRule(a,"breakBeforeClose")&&this.lineBreak(1),"*"!=a&&this.write("[/",a,"]"),this.getRule(a,"breakAfterClose")&&this.lineBreak(1))},
text:function(a){this.write(a)},comment:function(){},lineBreak:function(){!this._.hasLineBreak&&this._.output.length&&(this.write("\n"),this._.hasLineBreak=1)},write:function(){this._.hasLineBreak=0;var a=Array.prototype.join.call(arguments,"");this._.output.push(a)},reset:function(){this._.output=[];this._.hasLineBreak=0},getHtml:function(a){var b=this._.output.join("");a&&this.reset();return D(b)}}}));CKEDITOR.plugins.add("bbcode",{requires:"entities",beforeInit:function(a){CKEDITOR.tools.extend(a.config,
{enterMode:CKEDITOR.ENTER_BR,basicEntities:!1,entities:!1,fillEmptyBlocks:!1},!0);a.filter.disable();a.activeEnterMode=a.enterMode=CKEDITOR.ENTER_BR},init:function(a){function b(a){var b=a.data;a=CKEDITOR.htmlParser.fragment.fromBBCode(a.data.dataValue);var c=new CKEDITOR.htmlParser.basicWriter;a.writeHtml(c,k);a=c.getHtml(!0);b.dataValue=a}var c=a.config,k=new CKEDITOR.htmlParser.filter;k.addRules({elements:{blockquote:function(a){var b=new CKEDITOR.htmlParser.element("div");b.children=a.children;
a.children=[b];if(b=a.attributes.cite){var c=new CKEDITOR.htmlParser.element("cite");c.add(new CKEDITOR.htmlParser.text(b.replace(/^"|"$/g,"")));delete a.attributes.cite;a.children.unshift(c)}},span:function(a){var b;if(b=a.attributes.bbcode)"img"==b?(a.name="img",a.attributes.src=a.children[0].value,a.children=[]):"email"==b&&(a.name="a",a.attributes.href="mailto:"+a.children[0].value),delete a.attributes.bbcode},ol:function(a){a.attributes.listType?"decimal"!=a.attributes.listType&&(a.attributes.style=
"list-style-type:"+a.attributes.listType):a.name="ul";delete a.attributes.listType},a:function(a){a.attributes.href||(a.attributes.href=a.children[0].value)},smiley:function(a){a.name="img";var b=a.attributes.desc,h=c.smiley_images[CKEDITOR.tools.indexOf(c.smiley_descriptions,b)],h=CKEDITOR.tools.htmlEncode(c.smiley_path+h);a.attributes={src:h,"data-cke-saved-src":h,title:b,alt:b}}}});a.dataProcessor.htmlFilter.addRules({elements:{$:function(b){var c=b.attributes,h=CKEDITOR.tools.parseCssText(c.style,
1),f,d=b.name;if(d in x)d=x[d];else if("span"==d)if(f=h.color)d="color",f=CKEDITOR.tools.convertRgbToHex(f);else{if(f=h["font-size"])if(c=f.match(/(\d+)%$/))f=c[1],d="size"}else if("ol"==d||"ul"==d){if(f=h["list-style-type"])switch(f){case "lower-alpha":f="a";break;case "upper-alpha":f="A"}else"ol"==d&&(f=1);d="list"}else if("blockquote"==d){try{var k=b.children[0],l=b.children[1],m="cite"==k.name&&k.children[0].value;m&&(f='"'+m+'"',b.children=l.children)}catch(n){}d="quote"}else if("a"==d){if(f=
c.href)-1!==f.indexOf("mailto:")?(d="email",b.children=[new CKEDITOR.htmlParser.text(f.replace("mailto:",""))],f=""):((d=1==b.children.length&&b.children[0])&&d.type==CKEDITOR.NODE_TEXT&&d.value==f&&(f=""),d="url")}else if("img"==d){b.isEmpty=0;h=c["data-cke-saved-src"]||c.src;c=c.alt;if(h&&-1!=h.indexOf(a.config.smiley_path)&&c)return new CKEDITOR.htmlParser.text(q[c]);b.children=[new CKEDITOR.htmlParser.text(h)]}b.name=d;f&&(b.attributes.option=f);return null},div:function(a){var b=CKEDITOR.tools.parseCssText(a.attributes.style,
1)["text-align"]||"";if(b)return a.name=b,null},br:function(a){if((a=a.next)&&a.name in A)return!1}}},1);a.dataProcessor.writer=v;if(a.elementMode==CKEDITOR.ELEMENT_MODE_INLINE)a.once("contentDom",function(){a.on("setData",b)});else a.on("setData",b)},afterInit:function(a){var b;a._.elementsPath&&(b=a._.elementsPath.filters)&&b.push(function(b){var k=b.getName(),e=m[k]||!1;"link"==e&&0===b.getAttribute("href").indexOf("mailto:")?e="email":"span"==k?b.getStyle("font-size")?e="size":b.getStyle("color")&&
(e="color"):"div"==k&&b.getStyle("text-align")?e=b.getStyle("text-align"):"img"==e&&(b=b.data("cke-saved-src")||b.getAttribute("src"))&&0===b.indexOf(a.config.smiley_path)&&(e="smiley");return e})}})})(); | cmos3511/cmos_linux | python/op/op_site/op_static/npm/node_modules/ckeditor/plugins/bbcode/plugin.js | JavaScript | gpl-3.0 | 9,603 |
/**
* @file
* @copyright 2020 Aleksej Komarov
* @license MIT
*/
// Themes
import './styles/main.scss';
import './styles/themes/abductor.scss';
import './styles/themes/cardtable.scss';
import './styles/themes/hackerman.scss';
import './styles/themes/malfunction.scss';
import './styles/themes/neutral.scss';
import './styles/themes/ntos.scss';
import './styles/themes/paper.scss';
import './styles/themes/retro.scss';
import './styles/themes/syndicate.scss';
import './styles/themes/wizard.scss';
import { perf } from 'common/perf';
import { setupHotReloading } from 'tgui-dev-server/link/client';
import { setupHotKeys } from './hotkeys';
import { captureExternalLinks } from './links';
import { createRenderer } from './renderer';
import { configureStore, StoreProvider } from './store';
import { setupGlobalEvents } from './events';
perf.mark('inception', window.performance?.timing?.navigationStart);
perf.mark('init');
const store = configureStore();
const renderApp = createRenderer(() => {
const { getRoutedComponent } = require('./routes');
const Component = getRoutedComponent(store);
return (
<StoreProvider store={store}>
<Component />
</StoreProvider>
);
});
const setupApp = () => {
// Delay setup
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', setupApp);
return;
}
setupGlobalEvents();
setupHotKeys();
captureExternalLinks();
// Subscribe for state updates
store.subscribe(renderApp);
// Dispatch incoming messages
window.update = msg => store.dispatch(Byond.parseJson(msg));
// Process the early update queue
while (true) {
const msg = window.__updateQueue__.shift();
if (!msg) {
break;
}
window.update(msg);
}
// Enable hot module reloading
if (module.hot) {
setupHotReloading();
module.hot.accept([
'./components',
'./debug',
'./layouts',
'./routes',
], () => {
renderApp();
});
}
};
setupApp();
| optimumtact/-tg-station | tgui/packages/tgui/index.js | JavaScript | agpl-3.0 | 1,998 |
(function() {
'use strict';
Features.$inject = ['urls'];
function Features(urls) {
var self = this;
urls.links().then(function(links) {
angular.extend(self, links);
});
}
/**
* Provides info what features are available on server
*/
angular.module('superdesk.features', ['superdesk.api'])
.service('features', Features);
})();
| vladnicoara/superdesk-client-core | scripts/superdesk/features/features.js | JavaScript | agpl-3.0 | 355 |
// Tests for the JavaScriptMVC compatibility layer. Will be removed eventually
steal('funcunit/qunit', 'jquerypp/controller/view/test/qunit'
, 'jquerypp/class/class_test.js'
, 'jquerypp/model/test/qunit'
, 'jquerypp/controller/controller_test.js'
, 'jquerypp/view/test/qunit'
, 'jquerypp/dom/route/route_test.js'
, './integration.js'); | willametteuniversity/webcirc2 | static/jquerypp/test/qunit/jmvc.js | JavaScript | apache-2.0 | 341 |
/*
* CKFinder
* ========
* http://ckfinder.com
* Copyright (C) 2007-2011, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['el'] =
{
appTitle : 'CKFinder', // MISSING
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
ok : 'OK', // MISSING
cancel : 'Cancel', // MISSING
confirmationTitle : 'Confirmation', // MISSING
messageTitle : 'Information', // MISSING
inputTitle : 'Question', // MISSING
undo : 'Undo', // MISSING
redo : 'Redo', // MISSING
skip : 'Skip', // MISSING
skipAll : 'Skip all', // MISSING
makeDecision : 'What action should be taken?', // MISSING
rememberDecision: 'Remember my decision' // MISSING
},
dir : 'ltr', // MISSING
HelpLang : 'en',
LangCode : 'el',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['ΜΜ', 'ΠΜ'],
// Folders
FoldersTitle : 'Φάκελοι',
FolderLoading : 'Φόρτωση...',
FolderNew : 'Παρακαλούμε πληκτρολογήστε την ονομασία του νέου φακέλου: ',
FolderRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του φακέλου: ',
FolderDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το φάκελο "%1";',
FolderRenaming : ' (Μετονομασία...)',
FolderDeleting : ' (Διαγραφή...)',
// Files
FileRename : 'Παρακαλούμε πληκτρολογήστε την νέα ονομασία του αρχείου: ',
FileRenameExt : 'Είστε σίγουροι ότι θέλετε να αλλάξετε την επέκταση του αρχείου; Μετά από αυτή την ενέργεια το αρχείο μπορεί να μην μπορεί να χρησιμοποιηθεί',
FileRenaming : 'Μετονομασία...',
FileDelete : 'Είστε σίγουροι ότι θέλετε να διαγράψετε το αρχείο "%1"?',
FilesLoading : 'Loading...', // MISSING
FilesEmpty : 'Empty folder', // MISSING
FilesMoved : 'File %1 moved into %2:%3', // MISSING
FilesCopied : 'File %1 copied into %2:%3', // MISSING
// Basket
BasketFolder : 'Basket', // MISSING
BasketClear : 'Clear Basket', // MISSING
BasketRemove : 'Remove from basket', // MISSING
BasketOpenFolder : 'Open parent folder', // MISSING
BasketTruncateConfirm : 'Do you really want to remove all files from the basket?', // MISSING
BasketRemoveConfirm : 'Do you really want to remove the file "%1" from the basket?', // MISSING
BasketEmpty : 'No files in the basket, drag\'n\'drop some.', // MISSING
BasketCopyFilesHere : 'Copy Files from Basket', // MISSING
BasketMoveFilesHere : 'Move Files from Basket', // MISSING
BasketPasteErrorOther : 'File %s error: %e', // MISSING
BasketPasteMoveSuccess : 'The following files were moved: %s', // MISSING
BasketPasteCopySuccess : 'The following files were copied: %s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Μεταφόρτωση',
UploadTip : 'Μεταφόρτωση Νέου Αρχείου',
Refresh : 'Ανανέωση',
Settings : 'Ρυθμίσεις',
Help : 'Βοήθεια',
HelpTip : 'Βοήθεια',
// Context Menus
Select : 'Επιλογή',
SelectThumbnail : 'Επιλογή Μικρογραφίας',
View : 'Προβολή',
Download : 'Λήψη Αρχείου',
NewSubFolder : 'Νέος Υποφάκελος',
Rename : 'Μετονομασία',
Delete : 'Διαγραφή',
CopyDragDrop : 'Copy file here', // MISSING
MoveDragDrop : 'Move file here', // MISSING
// Dialogs
RenameDlgTitle : 'Rename', // MISSING
NewNameDlgTitle : 'New name', // MISSING
FileExistsDlgTitle : 'File already exists', // MISSING
SysErrorDlgTitle : 'System error', // MISSING
FileOverwrite : 'Overwrite', // MISSING
FileAutorename : 'Auto-rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Ακύρωση',
CloseBtn : 'Κλείσιμο',
// Upload Panel
UploadTitle : 'Μεταφόρτωση Νέου Αρχείου',
UploadSelectLbl : 'επιλέξτε το αρχείο που θέλετε να μεταφερθεί κάνοντας κλίκ στο κουμπί',
UploadProgressLbl : '(Η μεταφόρτωση εκτελείται, παρακαλούμε περιμένετε...)',
UploadBtn : 'Μεταφόρτωση Επιλεγμένου Αρχείου',
UploadBtnCancel : 'Cancel', // MISSING
UploadNoFileMsg : 'Παρακαλούμε επιλέξτε ένα αρχείο από τον υπολογιστή σας',
UploadNoFolder : 'Please select folder before uploading.', // MISSING
UploadNoPerms : 'File upload not allowed.', // MISSING
UploadUnknError : 'Error sending the file.', // MISSING
UploadExtIncorrect : 'File extension not allowed in this folder.', // MISSING
// Settings Panel
SetTitle : 'Ρυθμίσεις',
SetView : 'Προβολή:',
SetViewThumb : 'Μικρογραφίες',
SetViewList : 'Λίστα',
SetDisplay : 'Εμφάνιση:',
SetDisplayName : 'Όνομα Αρχείου',
SetDisplayDate : 'Ημερομηνία',
SetDisplaySize : 'Μέγεθος Αρχείου',
SetSort : 'Ταξινόμηση:',
SetSortName : 'βάσει Όνοματος Αρχείου',
SetSortDate : 'βάσει Ημερομήνιας',
SetSortSize : 'βάσει Μεγέθους',
// Status Bar
FilesCountEmpty : '<Κενός Φάκελος>',
FilesCountOne : '1 αρχείο',
FilesCountMany : '%1 αρχεία',
// Size and Speed
Kb : '%1 kB',
KbPerSecond : '%1 kB/s',
// Connector Error Messages.
ErrorUnknown : 'Η ενέργεια δεν ήταν δυνατόν να εκτελεστεί. (Σφάλμα %1)',
Errors :
{
10 : 'Λανθασμένη Εντολή.',
11 : 'Το resource type δεν ήταν δυνατόν να προσδιορίστεί.',
12 : 'Το resource type δεν είναι έγκυρο.',
102 : 'Το όνομα αρχείου ή φακέλου δεν είναι έγκυρο.',
103 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω έλλειψης δικαιωμάτων ασφαλείας.',
104 : 'Δεν ήταν δυνατή η εκτέλεση της ενέργειας λόγω περιορισμών του συστήματος αρχείων.',
105 : 'Λανθασμένη Επέκταση Αρχείου.',
109 : 'Λανθασμένη Ενέργεια.',
110 : 'Άγνωστο Λάθος.',
115 : 'Το αρχείο ή φάκελος υπάρχει ήδη.',
116 : 'Ο φάκελος δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
117 : 'Το αρχείο δεν βρέθηκε. Παρακαλούμε ανανεώστε τη σελίδα και προσπαθήστε ξανά.',
118 : 'Source and target paths are equal.', // MISSING
201 : 'Ένα αρχείο με την ίδια ονομασία υπάρχει ήδη. Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"',
202 : 'Λανθασμένο Αρχείο',
203 : 'Λανθασμένο Αρχείο. Το μέγεθος του αρχείου είναι πολύ μεγάλο.',
204 : 'Το μεταφορτωμένο αρχείο είναι χαλασμένο.',
205 : 'Δεν υπάρχει προσωρινός φάκελος για να χρησιμοποιηθεί για τις μεταφορτώσεις των αρχείων.',
206 : 'Η μεταφόρτωση ακυρώθηκε για λόγους ασφαλείας. Το αρχείο περιέχει δεδομένα μορφής HTML.',
207 : 'Το μεταφορτωμένο αρχείο μετονομάστηκε σε "%1"',
300 : 'Moving file(s) failed.', // MISSING
301 : 'Copying file(s) failed.', // MISSING
500 : 'Ο πλοηγός αρχείων έχει απενεργοποιηθεί για λόγους ασφαλείας. Παρακαλούμε επικοινωνήστε με τον διαχειριστή της ιστοσελίδας και ελέγξτε το αρχείο ρυθμίσεων του πλοηγού (CKFinder).',
501 : 'Η υποστήριξη των μικρογραφιών έχει απενεργοποιηθεί.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Η ονομασία του αρχείου δεν μπορεί να είναι κενή',
FileExists : 'File %s already exists', // MISSING
FolderEmpty : 'Η ονομασία του φακέλου δεν μπορεί να είναι κενή',
FileInvChar : 'Η ονομασία του αρχείου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
FolderInvChar : 'Η ονομασία του φακέλου δεν μπορεί να περιέχει τους ακόλουθους χαρακτήρες: \n\\ / : * ? " < > |',
PopupBlockView : 'Δεν ήταν εφικτό να ανοίξει το αρχείο σε νέο παράθυρο. Παρακαλώ, ελέγξτε τις ρυθμίσεις τους πλοηγού σας και απενεργοποιήστε όλους τους popup blockers για αυτή την ιστοσελίδα.'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Resize %s', // MISSING
sizeTooBig : 'Cannot set image height or width to a value bigger than the original size (%size).', // MISSING
resizeSuccess : 'Image resized successfully.', // MISSING
thumbnailNew : 'Create new thumbnail', // MISSING
thumbnailSmall : 'Small (%s)', // MISSING
thumbnailMedium : 'Medium (%s)', // MISSING
thumbnailLarge : 'Large (%s)', // MISSING
newSize : 'Set new size', // MISSING
width : 'Width', // MISSING
height : 'Height', // MISSING
invalidHeight : 'Invalid height.', // MISSING
invalidWidth : 'Invalid width.', // MISSING
invalidName : 'Invalid file name.', // MISSING
newImage : 'Create new image', // MISSING
noExtensionChange : 'The file extension cannot be changed.', // MISSING
imageSmall : 'Source image is too small', // MISSING
contextMenuName : 'Resize' // MISSING
},
// Fileeditor plugin
Fileeditor :
{
save : 'Save', // MISSING
fileOpenError : 'Unable to open file.', // MISSING
fileSaveSuccess : 'File saved successfully.', // MISSING
contextMenuName : 'Edit', // MISSING
loadingFile : 'Loading file, please wait...' // MISSING
}
};
| vikigroup/cbuilk | web/skin/temp12/scripts/ckfinder/lang/el.js | JavaScript | apache-2.0 | 11,785 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*! FixedHeader 2.1.2
* ©2010-2014 SpryMedia Ltd - datatables.net/license
*/
/**
* @summary FixedHeader
* @description Fix a table's header or footer, so it is always visible while
* Scrolling
* @version 2.1.2
* @file dataTables.fixedHeader.js
* @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
* @copyright Copyright 2009-2014 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/
/* Global scope for FixedColumns for backwards compatibility - will be removed
* in future. Not documented in 1.1.x.
*/
/* Global scope for FixedColumns */
var FixedHeader;
(function(window, document, undefined) {
var factory = function( $, DataTable ) {
"use strict";
/*
* Function: FixedHeader
* Purpose: Provide 'fixed' header, footer and columns for a DataTable
* Returns: object:FixedHeader - must be called with 'new'
* Inputs: mixed:mTable - target table
* @param {object} dt DataTables instance or HTML table node. With DataTables
* 1.10 this can also be a jQuery collection (with just a single table in its
* result set), a jQuery selector, DataTables API instance or settings
* object.
* @param {object} [oInit] initialisation settings, with the following
* properties (each optional)
* * bool:top - fix the header (default true)
* * bool:bottom - fix the footer (default false)
* * int:left - fix the left column(s) (default 0)
* * int:right - fix the right column(s) (default 0)
* * int:zTop - fixed header zIndex
* * int:zBottom - fixed footer zIndex
* * int:zLeft - fixed left zIndex
* * int:zRight - fixed right zIndex
*/
FixedHeader = function ( mTable, oInit ) {
/* Sanity check - you just know it will happen */
if ( ! this instanceof FixedHeader )
{
alert( "FixedHeader warning: FixedHeader must be initialised with the 'new' keyword." );
return;
}
var that = this;
var oSettings = {
"aoCache": [],
"oSides": {
"top": true,
"bottom": false,
"left": 0,
"right": 0
},
"oZIndexes": {
"top": 104,
"bottom": 103,
"left": 102,
"right": 101
},
"oCloneOnDraw": {
"top": false,
"bottom": false,
"left": true,
"right": true
},
"oMes": {
"iTableWidth": 0,
"iTableHeight": 0,
"iTableLeft": 0,
"iTableRight": 0, /* note this is left+width, not actually "right" */
"iTableTop": 0,
"iTableBottom": 0 /* note this is top+height, not actually "bottom" */
},
"oOffset": {
"top": 0
},
"nTable": null,
"bFooter": false,
"bInitComplete": false
};
/*
* Function: fnGetSettings
* Purpose: Get the settings for this object
* Returns: object: - settings object
* Inputs: -
*/
this.fnGetSettings = function () {
return oSettings;
};
/*
* Function: fnUpdate
* Purpose: Update the positioning and copies of the fixed elements
* Returns: -
* Inputs: -
*/
this.fnUpdate = function () {
this._fnUpdateClones();
this._fnUpdatePositions();
};
/*
* Function: fnPosition
* Purpose: Update the positioning of the fixed elements
* Returns: -
* Inputs: -
*/
this.fnPosition = function () {
this._fnUpdatePositions();
};
var dt = $.fn.dataTable.Api ?
new $.fn.dataTable.Api( mTable ).settings()[0] :
mTable.fnSettings();
dt._oPluginFixedHeader = this;
/* Let's do it */
this.fnInit( dt, oInit );
};
/*
* Variable: FixedHeader
* Purpose: Prototype for FixedHeader
* Scope: global
*/
FixedHeader.prototype = {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Initialisation
*/
/*
* Function: fnInit
* Purpose: The "constructor"
* Returns: -
* Inputs: {as FixedHeader function}
*/
fnInit: function ( oDtSettings, oInit )
{
var s = this.fnGetSettings();
var that = this;
/* Record the user definable settings */
this.fnInitSettings( s, oInit );
if ( oDtSettings.oScroll.sX !== "" || oDtSettings.oScroll.sY !== "" )
{
alert( "FixedHeader 2 is not supported with DataTables' scrolling mode at this time" );
return;
}
s.nTable = oDtSettings.nTable;
oDtSettings.aoDrawCallback.unshift( {
"fn": function () {
FixedHeader.fnMeasure();
that._fnUpdateClones.call(that);
that._fnUpdatePositions.call(that);
},
"sName": "FixedHeader"
} );
s.bFooter = ($('>tfoot', s.nTable).length > 0) ? true : false;
/* Add the 'sides' that are fixed */
if ( s.oSides.top )
{
s.aoCache.push( that._fnCloneTable( "fixedHeader", "FixedHeader_Header", that._fnCloneThead ) );
}
if ( s.oSides.bottom )
{
s.aoCache.push( that._fnCloneTable( "fixedFooter", "FixedHeader_Footer", that._fnCloneTfoot ) );
}
if ( s.oSides.left )
{
s.aoCache.push( that._fnCloneTable( "fixedLeft", "FixedHeader_Left", that._fnCloneTLeft, s.oSides.left ) );
}
if ( s.oSides.right )
{
s.aoCache.push( that._fnCloneTable( "fixedRight", "FixedHeader_Right", that._fnCloneTRight, s.oSides.right ) );
}
/* Event listeners for window movement */
FixedHeader.afnScroll.push( function () {
that._fnUpdatePositions.call(that);
} );
$(window).resize( function () {
FixedHeader.fnMeasure();
that._fnUpdateClones.call(that);
that._fnUpdatePositions.call(that);
} );
$(s.nTable)
.on('column-reorder.dt', function () {
FixedHeader.fnMeasure();
that._fnUpdateClones( true );
that._fnUpdatePositions();
} )
.on('column-visibility.dt', function () {
FixedHeader.fnMeasure();
that._fnUpdateClones( true );
that._fnUpdatePositions();
} );
/* Get things right to start with */
FixedHeader.fnMeasure();
that._fnUpdateClones();
that._fnUpdatePositions();
s.bInitComplete = true;
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Support functions
*/
/*
* Function: fnInitSettings
* Purpose: Take the user's settings and copy them to our local store
* Returns: -
* Inputs: object:s - the local settings object
* object:oInit - the user's settings object
*/
fnInitSettings: function ( s, oInit )
{
if ( oInit !== undefined )
{
if ( oInit.top !== undefined ) {
s.oSides.top = oInit.top;
}
if ( oInit.bottom !== undefined ) {
s.oSides.bottom = oInit.bottom;
}
if ( typeof oInit.left == 'boolean' ) {
s.oSides.left = oInit.left ? 1 : 0;
}
else if ( oInit.left !== undefined ) {
s.oSides.left = oInit.left;
}
if ( typeof oInit.right == 'boolean' ) {
s.oSides.right = oInit.right ? 1 : 0;
}
else if ( oInit.right !== undefined ) {
s.oSides.right = oInit.right;
}
if ( oInit.zTop !== undefined ) {
s.oZIndexes.top = oInit.zTop;
}
if ( oInit.zBottom !== undefined ) {
s.oZIndexes.bottom = oInit.zBottom;
}
if ( oInit.zLeft !== undefined ) {
s.oZIndexes.left = oInit.zLeft;
}
if ( oInit.zRight !== undefined ) {
s.oZIndexes.right = oInit.zRight;
}
if ( oInit.offsetTop !== undefined ) {
s.oOffset.top = oInit.offsetTop;
}
if ( oInit.alwaysCloneTop !== undefined ) {
s.oCloneOnDraw.top = oInit.alwaysCloneTop;
}
if ( oInit.alwaysCloneBottom !== undefined ) {
s.oCloneOnDraw.bottom = oInit.alwaysCloneBottom;
}
if ( oInit.alwaysCloneLeft !== undefined ) {
s.oCloneOnDraw.left = oInit.alwaysCloneLeft;
}
if ( oInit.alwaysCloneRight !== undefined ) {
s.oCloneOnDraw.right = oInit.alwaysCloneRight;
}
}
},
/*
* Function: _fnCloneTable
* Purpose: Clone the table node and do basic initialisation
* Returns: -
* Inputs: -
*/
_fnCloneTable: function ( sType, sClass, fnClone, iCells )
{
var s = this.fnGetSettings();
var nCTable;
/* We know that the table _MUST_ has a DIV wrapped around it, because this is simply how
* DataTables works. Therefore, we can set this to be relatively position (if it is not
* alreadu absolute, and use this as the base point for the cloned header
*/
if ( $(s.nTable.parentNode).css('position') != "absolute" )
{
s.nTable.parentNode.style.position = "relative";
}
/* Just a shallow clone will do - we only want the table node */
nCTable = s.nTable.cloneNode( false );
nCTable.removeAttribute( 'id' );
var nDiv = document.createElement( 'div' );
nDiv.style.position = "absolute";
nDiv.style.top = "0px";
nDiv.style.left = "0px";
nDiv.className += " FixedHeader_Cloned "+sType+" "+sClass;
/* Set the zIndexes */
if ( sType == "fixedHeader" )
{
nDiv.style.zIndex = s.oZIndexes.top;
}
if ( sType == "fixedFooter" )
{
nDiv.style.zIndex = s.oZIndexes.bottom;
}
if ( sType == "fixedLeft" )
{
nDiv.style.zIndex = s.oZIndexes.left;
}
else if ( sType == "fixedRight" )
{
nDiv.style.zIndex = s.oZIndexes.right;
}
/* remove margins since we are going to position it absolutely */
nCTable.style.margin = "0";
/* Insert the newly cloned table into the DOM, on top of the "real" header */
nDiv.appendChild( nCTable );
document.body.appendChild( nDiv );
return {
"nNode": nCTable,
"nWrapper": nDiv,
"sType": sType,
"sPosition": "",
"sTop": "",
"sLeft": "",
"fnClone": fnClone,
"iCells": iCells
};
},
/*
* Function: _fnMeasure
* Purpose: Get the current positioning of the table in the DOM
* Returns: -
* Inputs: -
*/
_fnMeasure: function ()
{
var
s = this.fnGetSettings(),
m = s.oMes,
jqTable = $(s.nTable),
oOffset = jqTable.offset(),
iParentScrollTop = this._fnSumScroll( s.nTable.parentNode, 'scrollTop' ),
iParentScrollLeft = this._fnSumScroll( s.nTable.parentNode, 'scrollLeft' );
m.iTableWidth = jqTable.outerWidth();
m.iTableHeight = jqTable.outerHeight();
m.iTableLeft = oOffset.left + s.nTable.parentNode.scrollLeft;
m.iTableTop = oOffset.top + iParentScrollTop;
m.iTableRight = m.iTableLeft + m.iTableWidth;
m.iTableRight = FixedHeader.oDoc.iWidth - m.iTableLeft - m.iTableWidth;
m.iTableBottom = FixedHeader.oDoc.iHeight - m.iTableTop - m.iTableHeight;
},
/*
* Function: _fnSumScroll
* Purpose: Sum node parameters all the way to the top
* Returns: int: sum
* Inputs: node:n - node to consider
* string:side - scrollTop or scrollLeft
*/
_fnSumScroll: function ( n, side )
{
var i = n[side];
while ( n = n.parentNode )
{
if ( n.nodeName == 'HTML' || n.nodeName == 'BODY' )
{
break;
}
i = n[side];
}
return i;
},
/*
* Function: _fnUpdatePositions
* Purpose: Loop over the fixed elements for this table and update their positions
* Returns: -
* Inputs: -
*/
_fnUpdatePositions: function ()
{
var s = this.fnGetSettings();
this._fnMeasure();
for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ )
{
if ( s.aoCache[i].sType == "fixedHeader" )
{
this._fnScrollFixedHeader( s.aoCache[i] );
}
else if ( s.aoCache[i].sType == "fixedFooter" )
{
this._fnScrollFixedFooter( s.aoCache[i] );
}
else if ( s.aoCache[i].sType == "fixedLeft" )
{
this._fnScrollHorizontalLeft( s.aoCache[i] );
}
else
{
this._fnScrollHorizontalRight( s.aoCache[i] );
}
}
},
/*
* Function: _fnUpdateClones
* Purpose: Loop over the fixed elements for this table and call their cloning functions
* Returns: -
* Inputs: -
*/
_fnUpdateClones: function ( full )
{
var s = this.fnGetSettings();
if ( full ) {
// This is a little bit of a hack to force a full clone draw. When
// `full` is set to true, we want to reclone the source elements,
// regardless of the clone-on-draw settings
s.bInitComplete = false;
}
for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ )
{
s.aoCache[i].fnClone.call( this, s.aoCache[i] );
}
if ( full ) {
s.bInitComplete = true;
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Scrolling functions
*/
/*
* Function: _fnScrollHorizontalLeft
* Purpose: Update the positioning of the scrolling elements
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnScrollHorizontalRight: function ( oCache )
{
var
s = this.fnGetSettings(),
oMes = s.oMes,
oWin = FixedHeader.oWin,
oDoc = FixedHeader.oDoc,
nTable = oCache.nWrapper,
iFixedWidth = $(nTable).outerWidth();
if ( oWin.iScrollRight < oMes.iTableRight )
{
/* Fully right aligned */
this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iFixedWidth)+"px", 'left', nTable.style );
}
else if ( oMes.iTableLeft < oDoc.iWidth-oWin.iScrollRight-iFixedWidth )
{
/* Middle */
this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', (oWin.iWidth-iFixedWidth)+"px", 'left', nTable.style );
}
else
{
/* Fully left aligned */
this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
}
},
/*
* Function: _fnScrollHorizontalLeft
* Purpose: Update the positioning of the scrolling elements
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnScrollHorizontalLeft: function ( oCache )
{
var
s = this.fnGetSettings(),
oMes = s.oMes,
oWin = FixedHeader.oWin,
oDoc = FixedHeader.oDoc,
nTable = oCache.nWrapper,
iCellWidth = $(nTable).outerWidth();
if ( oWin.iScrollLeft < oMes.iTableLeft )
{
/* Fully left align */
this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
}
else if ( oWin.iScrollLeft < oMes.iTableLeft+oMes.iTableWidth-iCellWidth )
{
this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', "0px", 'left', nTable.style );
}
else
{
/* Fully right align */
this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iCellWidth)+"px", 'left', nTable.style );
}
},
/*
* Function: _fnScrollFixedFooter
* Purpose: Update the positioning of the scrolling elements
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnScrollFixedFooter: function ( oCache )
{
var
s = this.fnGetSettings(),
oMes = s.oMes,
oWin = FixedHeader.oWin,
oDoc = FixedHeader.oDoc,
nTable = oCache.nWrapper,
iTheadHeight = $("thead", s.nTable).outerHeight(),
iCellHeight = $(nTable).outerHeight();
if ( oWin.iScrollBottom < oMes.iTableBottom )
{
/* Below */
this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+oMes.iTableHeight-iCellHeight)+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
}
else if ( oWin.iScrollBottom < oMes.iTableBottom+oMes.iTableHeight-iCellHeight-iTheadHeight )
{
this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', (oWin.iHeight-iCellHeight)+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style );
}
else
{
/* Above */
this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iCellHeight)+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
}
},
/*
* Function: _fnScrollFixedHeader
* Purpose: Update the positioning of the scrolling elements
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnScrollFixedHeader: function ( oCache )
{
var
s = this.fnGetSettings(),
oMes = s.oMes,
oWin = FixedHeader.oWin,
oDoc = FixedHeader.oDoc,
nTable = oCache.nWrapper,
iTbodyHeight = 0,
anTbodies = s.nTable.getElementsByTagName('tbody');
for (var i = 0; i < anTbodies.length; ++i) {
iTbodyHeight += anTbodies[i].offsetHeight;
}
if ( oMes.iTableTop > oWin.iScrollTop + s.oOffset.top )
{
/* Above the table */
this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
}
else if ( oWin.iScrollTop + s.oOffset.top > oMes.iTableTop+iTbodyHeight )
{
/* At the bottom of the table */
this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iTbodyHeight)+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
}
else
{
/* In the middle of the table */
this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
this._fnUpdateCache( oCache, 'sTop', s.oOffset.top+"px", 'top', nTable.style );
this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style );
}
},
/*
* Function: _fnUpdateCache
* Purpose: Check the cache and update cache and value if needed
* Returns: -
* Inputs: object:oCache - local cache object
* string:sCache - cache property
* string:sSet - value to set
* string:sProperty - object property to set
* object:oObj - object to update
*/
_fnUpdateCache: function ( oCache, sCache, sSet, sProperty, oObj )
{
if ( oCache[sCache] != sSet )
{
oObj[sProperty] = sSet;
oCache[sCache] = sSet;
}
},
/**
* Copy the classes of all child nodes from one element to another. This implies
* that the two have identical structure - no error checking is performed to that
* fact.
* @param {element} source Node to copy classes from
* @param {element} dest Node to copy classes too
*/
_fnClassUpdate: function ( source, dest )
{
var that = this;
if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" ||
source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" )
{
dest.className = source.className;
}
$(source).children().each( function (i) {
that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] );
} );
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Cloning functions
*/
/*
* Function: _fnCloneThead
* Purpose: Clone the thead element
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnCloneThead: function ( oCache )
{
var s = this.fnGetSettings();
var nTable = oCache.nNode;
if ( s.bInitComplete && !s.oCloneOnDraw.top )
{
this._fnClassUpdate( $('thead', s.nTable)[0], $('thead', nTable)[0] );
return;
}
/* Set the wrapper width to match that of the cloned table */
var iDtWidth = $(s.nTable).outerWidth();
oCache.nWrapper.style.width = iDtWidth+"px";
nTable.style.width = iDtWidth+"px";
/* Remove any children the cloned table has */
while ( nTable.childNodes.length > 0 )
{
$('thead th', nTable).unbind( 'click' );
nTable.removeChild( nTable.childNodes[0] );
}
/* Clone the DataTables header */
var nThead = $('thead', s.nTable).clone(true)[0];
nTable.appendChild( nThead );
/* Copy the widths across - apparently a clone isn't good enough for this */
var a = [];
var b = [];
$("thead>tr th", s.nTable).each( function (i) {
a.push( $(this).width() );
} );
$("thead>tr td", s.nTable).each( function (i) {
b.push( $(this).width() );
} );
$("thead>tr th", s.nTable).each( function (i) {
$("thead>tr th:eq("+i+")", nTable).width( a[i] );
$(this).width( a[i] );
} );
$("thead>tr td", s.nTable).each( function (i) {
$("thead>tr td:eq("+i+")", nTable).width( b[i] );
$(this).width( b[i] );
} );
// Stop DataTables 1.9 from putting a focus ring on the headers when
// clicked to sort
$('th.sorting, th.sorting_desc, th.sorting_asc', nTable).bind( 'click', function () {
this.blur();
} );
},
/*
* Function: _fnCloneTfoot
* Purpose: Clone the tfoot element
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnCloneTfoot: function ( oCache )
{
var s = this.fnGetSettings();
var nTable = oCache.nNode;
/* Set the wrapper width to match that of the cloned table */
oCache.nWrapper.style.width = $(s.nTable).outerWidth()+"px";
/* Remove any children the cloned table has */
while ( nTable.childNodes.length > 0 )
{
nTable.removeChild( nTable.childNodes[0] );
}
/* Clone the DataTables footer */
var nTfoot = $('tfoot', s.nTable).clone(true)[0];
nTable.appendChild( nTfoot );
/* Copy the widths across - apparently a clone isn't good enough for this */
$("tfoot:eq(0)>tr th", s.nTable).each( function (i) {
$("tfoot:eq(0)>tr th:eq("+i+")", nTable).width( $(this).width() );
} );
$("tfoot:eq(0)>tr td", s.nTable).each( function (i) {
$("tfoot:eq(0)>tr td:eq("+i+")", nTable).width( $(this).width() );
} );
},
/*
* Function: _fnCloneTLeft
* Purpose: Clone the left column(s)
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnCloneTLeft: function ( oCache )
{
var s = this.fnGetSettings();
var nTable = oCache.nNode;
var nBody = $('tbody', s.nTable)[0];
/* Remove any children the cloned table has */
while ( nTable.childNodes.length > 0 )
{
nTable.removeChild( nTable.childNodes[0] );
}
/* Is this the most efficient way to do this - it looks horrible... */
nTable.appendChild( $("thead", s.nTable).clone(true)[0] );
nTable.appendChild( $("tbody", s.nTable).clone(true)[0] );
if ( s.bFooter )
{
nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] );
}
/* Remove unneeded cells */
var sSelector = 'gt(' + (oCache.iCells - 1) + ')';
$('thead tr', nTable).each( function (k) {
$('th:' + sSelector, this).remove();
} );
$('tfoot tr', nTable).each( function (k) {
$('th:' + sSelector, this).remove();
} );
$('tbody tr', nTable).each( function (k) {
$('td:' + sSelector, this).remove();
} );
this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable );
this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable );
this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable );
var iWidth = 0;
for (var i = 0; i < oCache.iCells; i++) {
iWidth += $('thead tr th:eq(' + i + ')', s.nTable).outerWidth();
}
nTable.style.width = iWidth+"px";
oCache.nWrapper.style.width = iWidth+"px";
},
/*
* Function: _fnCloneTRight
* Purpose: Clone the right most column(s)
* Returns: -
* Inputs: object:oCache - the cached values for this fixed element
*/
_fnCloneTRight: function ( oCache )
{
var s = this.fnGetSettings();
var nBody = $('tbody', s.nTable)[0];
var nTable = oCache.nNode;
var iCols = $('tbody tr:eq(0) td', s.nTable).length;
/* Remove any children the cloned table has */
while ( nTable.childNodes.length > 0 )
{
nTable.removeChild( nTable.childNodes[0] );
}
/* Is this the most efficient way to do this - it looks horrible... */
nTable.appendChild( $("thead", s.nTable).clone(true)[0] );
nTable.appendChild( $("tbody", s.nTable).clone(true)[0] );
if ( s.bFooter )
{
nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] );
}
$('thead tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove();
$('tfoot tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove();
/* Remove unneeded cells */
$('tbody tr', nTable).each( function (k) {
$('td:lt('+(iCols-oCache.iCells)+')', this).remove();
} );
this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable );
this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable );
this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable );
var iWidth = 0;
for (var i = 0; i < oCache.iCells; i++) {
iWidth += $('thead tr th:eq('+(iCols-1-i)+')', s.nTable).outerWidth();
}
nTable.style.width = iWidth+"px";
oCache.nWrapper.style.width = iWidth+"px";
},
/**
* Equalise the heights of the rows in a given table node in a cross browser way. Note that this
* is more or less lifted as is from FixedColumns
* @method fnEqualiseHeights
* @returns void
* @param {string} parent Node type - thead, tbody or tfoot
* @param {element} original Original node to take the heights from
* @param {element} clone Copy the heights to
* @private
*/
"fnEqualiseHeights": function ( parent, original, clone )
{
var that = this;
var originals = $(parent +' tr', original);
var height;
$(parent+' tr', clone).each( function (k) {
height = originals.eq( k ).css('height');
// This is nasty :-(. IE has a sub-pixel error even when setting
// the height below (the Firefox fix) which causes the fixed column
// to go out of alignment. Need to add a pixel before the assignment
// Can this be feature detected? Not sure how...
if ( navigator.appName == 'Microsoft Internet Explorer' ) {
height = parseInt( height, 10 ) + 1;
}
$(this).css( 'height', height );
// For Firefox to work, we need to also set the height of the
// original row, to the value that we read from it! Otherwise there
// is a sub-pixel rounding error
originals.eq( k ).css( 'height', height );
} );
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static properties and methods
* We use these for speed! This information is common to all instances of FixedHeader, so no
* point if having them calculated and stored for each different instance.
*/
/*
* Variable: oWin
* Purpose: Store information about the window positioning
* Scope: FixedHeader
*/
FixedHeader.oWin = {
"iScrollTop": 0,
"iScrollRight": 0,
"iScrollBottom": 0,
"iScrollLeft": 0,
"iHeight": 0,
"iWidth": 0
};
/*
* Variable: oDoc
* Purpose: Store information about the document size
* Scope: FixedHeader
*/
FixedHeader.oDoc = {
"iHeight": 0,
"iWidth": 0
};
/*
* Variable: afnScroll
* Purpose: Array of functions that are to be used for the scrolling components
* Scope: FixedHeader
*/
FixedHeader.afnScroll = [];
/*
* Function: fnMeasure
* Purpose: Update the measurements for the window and document
* Returns: -
* Inputs: -
*/
FixedHeader.fnMeasure = function ()
{
var
jqWin = $(window),
jqDoc = $(document),
oWin = FixedHeader.oWin,
oDoc = FixedHeader.oDoc;
oDoc.iHeight = jqDoc.height();
oDoc.iWidth = jqDoc.width();
oWin.iHeight = jqWin.height();
oWin.iWidth = jqWin.width();
oWin.iScrollTop = jqWin.scrollTop();
oWin.iScrollLeft = jqWin.scrollLeft();
oWin.iScrollRight = oDoc.iWidth - oWin.iScrollLeft - oWin.iWidth;
oWin.iScrollBottom = oDoc.iHeight - oWin.iScrollTop - oWin.iHeight;
};
FixedHeader.version = "2.1.2";
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Global processing
*/
/*
* Just one 'scroll' event handler in FixedHeader, which calls the required components. This is
* done as an optimisation, to reduce calculation and proagation time
*/
$(window).scroll( function () {
FixedHeader.fnMeasure();
for ( var i=0, iLen=FixedHeader.afnScroll.length ; i<iLen ; i++ ) {
FixedHeader.afnScroll[i]();
}
} );
$.fn.dataTable.FixedHeader = FixedHeader;
$.fn.DataTable.FixedHeader = FixedHeader;
return FixedHeader;
}; // /factory
// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd ) {
define( ['jquery', 'datatables'], factory );
}
else if ( typeof exports === 'object' ) {
// Node/CommonJS
factory( require('jquery'), require('datatables') );
}
else if ( jQuery && !jQuery.fn.dataTable.FixedHeader ) {
// Otherwise simply initialise as normal, stopping multiple evaluation
factory( jQuery, jQuery.fn.dataTable );
}
})(window, document);
| jagathsisira/app-cloud | modules/setup-scripts/conf/wso2das-3.0.1/repository/deployment/server/jaggeryapps/monitoring/themes/theme0/ui/thirdparty/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js | JavaScript | apache-2.0 | 29,978 |
/*
* Copyright 2012 the original author or authors
* @license MIT, see LICENSE.txt for details
*
* @author Scott Andrews
*/
(function (define) {
'use strict';
var undef;
/**
* Aggregate messages into batches as they are received.
*/
define(function (require) {
var msgs = require('..');
/**
* Aggregates messages into batches as they are received. Batches may
* be chunked either by an absolute size and/or a timeout since the
* first message was received for the chunk. Either a batch size or
* timeout must be specified.
*
* @param {string} [name] the name to register the aggregator as
* @param {number} [opts.batch=0] absolute size of a chunk. If <=0,
* batch size is not a factor
* @param {number} [opts.timeout=0] number of milliseconds since the
* first message arrived to queue the chunk. If <=0, timeout is not a
* factor
* @param {string|Channel} [opts.output] the channel to post the
* aggregated messages to
* @param {string|Channel} [opts.input] the channel to receive message
* from
* @param {string|Channel} [opts.error] channel to receive errors
* @returns the aggregator
* @throws on invalid configuration, batch size or timeout is required
*/
msgs.prototype.batchingAggregator = msgs.utils.optionalName(function batchingAggregator(name, opts) {
var timeout, batch;
batch = [];
opts = opts || {};
opts.batch = opts.batch || 0;
opts.timeout = opts.timeout || 0;
if (opts.batch <= 0 && opts.timeout <= 0) {
throw new Error('Invalid configuration: batch size or timeout must be defined');
}
function releaseHelper(release) {
release(batch);
batch = [];
clearTimeout(timeout);
timeout = undef;
}
return this.aggregator(name, function (message, release) {
batch.push(message.payload);
if (opts.batch > 0 && batch.length >= opts.batch) {
releaseHelper(release);
}
else if (!timeout && opts.timeout > 0) {
timeout = setTimeout(function () {
releaseHelper(release);
}, opts.timeout);
}
}, opts);
});
return msgs;
});
}(
typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); }
// Boilerplate for AMD and Node
));
| timveil/iot-truck-streaming | storm-demo-webapp/src/main/webapp/assets/lib/msgs/aggregators/batching.js | JavaScript | apache-2.0 | 2,277 |
//>>built
define("dojox/atom/widget/nls/hr/FeedEntryViewer",{displayOptions:"[opcije prikaza]",title:"Naslov",authors:"Autori",contributors:"Doprinositelji",id:"ID",close:"[zatvori]",updated:"A\u017eurirano",summary:"Sa\u017eetak",content:"Sadr\u017eaj"}); | aconyteds/Esri-Ozone-Map-Widget | vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/atom/widget/nls/hr/FeedEntryViewer.js | JavaScript | apache-2.0 | 256 |
/**
* Copyright 2017 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {isLayoutSizeDefined} from '../../../src/layout';
import {tryParseJson} from '../../../src/json';
import {user} from '../../../src/log';
import {removeElement} from '../../../src/dom';
import {
installVideoManagerForDoc,
} from '../../../src/service/video-manager-impl';
import {isObject} from '../../../src/types';
import {listen} from '../../../src/event-helper';
import {VideoEvents} from '../../../src/video-interface';
import {videoManagerForDoc} from '../../../src/services';
/**
* @implements {../../../src/video-interface.VideoInterface}
*/
class Amp3QPlayer extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private {?Element} */
this.iframe_ = null;
/** @private {?Function} */
this.unlistenMessage_ = null;
/** @private {?Promise} */
this.playerReadyPromise_ = null;
/** @private {?Function} */
this.playerReadyResolver_ = null;
this.dataId = null;
}
/**
* @param {boolean=} opt_onLayout
* @override
*/
preconnectCallback(opt_onLayout) {
this.preconnect.url('https://playout.3qsdn.com', opt_onLayout);
}
/** @override */
buildCallback() {
this.dataId = user().assert(
this.element.getAttribute('data-id'),
'The data-id attribute is required for <amp-3q-player> %s',
this.element);
this.playerReadyPromise_ = new Promise(resolve => {
this.playerReadyResolver_ = resolve;
});
installVideoManagerForDoc(this.element);
videoManagerForDoc(this.element).register(this);
}
/** @override */
layoutCallback() {
const iframe = this.element.ownerDocument.createElement('iframe');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', 'true');
this.iframe_ = iframe;
this.unlistenMessage_ = listen(
this.win,
'message',
this.sdnBridge_.bind(this)
);
this.applyFillContent(iframe, true);
iframe.src = 'https://playout.3qsdn.com/' +
encodeURIComponent(this.dataId) + '?autoplay=false&=true';
this.element.appendChild(iframe);
return this.loadPromise(this.iframe_).then(() =>
this.playerReadyPromise_);
}
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
}
if (this.unlistenMessage_) {
this.unlistenMessage_();
}
this.playerReadyPromise_ = new Promise(resolve => {
this.playerReadyResolver_ = resolve;
});
return true;
}
/** @override */
isLayoutSupported(layout) {
return isLayoutSizeDefined(layout);
}
/** @override */
viewportCallback(visible) {
this.element.dispatchCustomEvent(VideoEvents.VISIBILITY, {visible});
}
/** @override */
pauseCallback() {
if (this.iframe_) {
this.pause();
}
}
sdnBridge_(event) {
if (event.source) {
if (event.source != this.iframe_.contentWindow) {
return;
}
}
const data = isObject(event.data) ? event.data : tryParseJson(event.data);
if (data === undefined) {
return;
}
switch (data.data) {
case 'ready':
this.element.dispatchCustomEvent(VideoEvents.LOAD);
this.playerReadyResolver_();
break;
case 'playing':
this.element.dispatchCustomEvent(VideoEvents.PLAY);
break;
case 'paused':
this.element.dispatchCustomEvent(VideoEvents.PAUSE);
break;
case 'muted':
this.element.dispatchCustomEvent(VideoEvents.MUTED);
break;
case 'unmuted':
this.element.dispatchCustomEvent(VideoEvents.UNMUTED);
break;
}
}
sdnPostMessage_(message) {
this.playerReadyPromise_.then(() => {
if (this.iframe_ && this.iframe_.contentWindow) {
this.iframe_.contentWindow./*OK*/postMessage(message, '*');
}
});
}
// VideoInterface Implementation. See ../src/video-interface.VideoInterface
/** @override */
play() {
this.sdnPostMessage_('play2');
}
/** @override */
pause() {
this.sdnPostMessage_('pause');
}
/** @override */
mute() {
this.sdnPostMessage_('mute');
}
/** @override */
unmute() {
this.sdnPostMessage_('unmute');
}
/** @override */
supportsPlatform() {
return true;
}
/** @override */
isInteractive() {
return true;
}
/** @override */
showControls() {
this.sdnPostMessage_('showControlbar');
}
/** @override */
hideControls() {
this.sdnPostMessage_('hideControlbar');
}
};
AMP.registerElement('amp-3q-player', Amp3QPlayer);
| ecoron/amphtml | extensions/amp-3q-player/0.1/amp-3q-player.js | JavaScript | apache-2.0 | 5,238 |
/**
* Coder for Raspberry Pi
* A simple platform for experimenting with web stuff.
* http://goo.gl/coder
*
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.settings={};
//These are dynamically updated by the runtime
//settings.appname - the app id (folder) where your app is installed
//settings.viewpath - prefix to where your view html files are located
//settings.staticurl - base url path to static assets /static/apps/appname
//settings.appurl - base url path to this app /app/appname
exports.get_routes = [
{ path:'/', handler:'index_handler' },
];
exports.post_routes = [
];
exports.index_handler = function( req, res ) {
var tmplvars = {};
tmplvars['static_url'] = exports.settings.staticurl;
tmplvars['app_name'] = exports.settings.appname;
tmplvars['app_url'] = exports.settings.appurl;
tmplvars['device_name'] = exports.settings.device_name;
res.render( exports.settings.viewpath + '/index', tmplvars );
};
exports.on_destroy = function() {
};
| jmp407/coderJmp | coder-base/apps/game2d/app.js | JavaScript | apache-2.0 | 1,564 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Asserts that device property values match properties in |expectedProperties|.
* The method will *not* assert that the device contains *only* properties
* specified in expected properties.
* @param {Object} expectedProperties Expected device properties.
* @param {Object} device Device object to test.
*/
function assertDeviceMatches(expectedProperties, device) {
Object.keys(expectedProperties).forEach(function(key) {
chrome.test.assertEq(expectedProperties[key], device[key],
'Property ' + key + ' of device ' + device.id);
});
}
/**
* Verifies that list of devices contains all and only devices from set of
* expected devices. If will fail the test if an unexpected device is found.
*
* @param {Object.<string, Object>} expectedDevices Expected set of test
* devices. Maps device ID to device properties.
* @param {Array.<Object>} devices List of input devices.
*/
function assertDevicesMatch(expectedDevices, devices) {
var deviceIds = {};
devices.forEach(function(device) {
chrome.test.assertFalse(!!deviceIds[device.id],
'Duplicated device id: \'' + device.id + '\'.');
deviceIds[device.id] = true;
});
function sortedKeys(obj) {
return Object.keys(obj).sort();
}
chrome.test.assertEq(sortedKeys(expectedDevices), sortedKeys(deviceIds));
devices.forEach(function(device) {
assertDeviceMatches(expectedDevices[device.id], device);
});
}
/**
*
* @param {Array.<Object>} devices List of devices returned by
* chrome.audio.getInfo or chrome.audio.getDevices.
* @return {Object.<string, Object>} List of devices formatted as map of
* expected devices used to assert devices match expectation.
*/
function deviceListToExpectedDevicesMap(devices) {
var expectedDevicesMap = {};
devices.forEach(function(device) {
expectedDevicesMap[device.id] = device;
});
return expectedDevicesMap;
}
/**
* @param {Array.<Object>} devices List of devices returned by
* chrome.audio.getInfo or chrome.audio.getDevices.
* @return {Array.<string>} Sorted list devices IDs for devices in |devices|.
*/
function getDeviceIds(devices) {
return devices.map(function(device) {return device.id;}).sort();
}
function EventListener(targetEvent) {
this.targetEvent = targetEvent;
this.listener = this.handleEvent.bind(this);
this.targetEvent.addListener(this.listener);
this.eventCount = 0;
}
EventListener.prototype.handleEvent = function() {
++this.eventCount;
}
EventListener.prototype.reset = function() {
this.targetEvent.removeListener(this.listener);
}
var deviceChangedListener = null;
chrome.test.runTests([
// Sets up a listener for audio.onDeviceChanged event -
// |verifyNoDeviceChangedEvents| test will later verify that no
// onDeviceChanged events have been observed.
function startDeviceChangedListener() {
deviceChangedListener = new EventListener(chrome.audio.onDeviceChanged);
chrome.test.succeed();
},
function getDevicesTest() {
// Test output devices. Maps device ID -> tested device properties.
var kTestDevices = {
'30001': {
id: '30001',
stableDeviceId: '0',
displayName: 'Jabra Speaker 1',
deviceName: 'Jabra Speaker',
streamType: 'OUTPUT'
},
'30002': {
id: '30002',
stableDeviceId: '1',
displayName: 'Jabra Speaker 2',
deviceName: 'Jabra Speaker',
streamType: 'OUTPUT'
},
'30003': {
id: '30003',
stableDeviceId: '2',
displayName: 'HDA Intel MID',
deviceName: 'HDMI output',
streamType: 'OUTPUT'
},
'40001': {
id: '40001',
stableDeviceId: '3',
displayName: 'Jabra Mic 1',
deviceName: 'Jabra Mic',
streamType: 'INPUT'
},
'40002': {
id: '40002',
stableDeviceId: '4',
displayName: 'Jabra Mic 2',
deviceName: 'Jabra Mic',
streamType: 'INPUT'
},
'40003': {
id: '40003',
stableDeviceId: '5',
displayName: 'Logitech Webcam',
deviceName: 'Webcam Mic',
streamType: 'INPUT'
}
};
chrome.audio.getDevices(chrome.test.callbackPass(function(devices) {
assertDevicesMatch(kTestDevices, devices);
}));
},
function getDevicesWithEmptyFilterTest() {
// Test output devices. Maps device ID -> tested device properties.
var kTestDevices = {
'30001': {
id: '30001',
stableDeviceId: '0',
displayName: 'Jabra Speaker 1',
deviceName: 'Jabra Speaker',
streamType: 'OUTPUT'
},
'30002': {
id: '30002',
stableDeviceId: '1',
displayName: 'Jabra Speaker 2',
deviceName: 'Jabra Speaker',
streamType: 'OUTPUT'
},
'30003': {
id: '30003',
stableDeviceId: '2',
displayName: 'HDA Intel MID',
deviceName: 'HDMI output',
streamType: 'OUTPUT'
},
'40001': {
id: '40001',
stableDeviceId: '3',
displayName: 'Jabra Mic 1',
deviceName: 'Jabra Mic',
streamType: 'INPUT'
},
'40002': {
id: '40002',
stableDeviceId: '4',
displayName: 'Jabra Mic 2',
deviceName: 'Jabra Mic',
streamType: 'INPUT'
},
'40003': {
id: '40003',
stableDeviceId: '5',
displayName: 'Logitech Webcam',
deviceName: 'Webcam Mic',
streamType: 'INPUT'
}
};
chrome.audio.getDevices({}, chrome.test.callbackPass(function(devices) {
assertDevicesMatch(kTestDevices, devices);
}));
},
function getInputDevicesTest() {
var kTestDevices = {
'40001': {
id: '40001',
streamType: 'INPUT'
},
'40002': {
id: '40002',
streamType: 'INPUT'
},
'40003': {
id: '40003',
streamType: 'INPUT'
}
};
chrome.audio.getDevices({
streamTypes: ['INPUT']
}, chrome.test.callbackPass(function(devices) {
assertDevicesMatch(kTestDevices, devices);
}));
},
function getOutputDevicesTest() {
var kTestDevices = {
'30001': {
id: '30001',
streamType: 'OUTPUT'
},
'30002': {
id: '30002',
streamType: 'OUTPUT'
},
'30003': {
id: '30003',
streamType: 'OUTPUT'
},
};
chrome.audio.getDevices({
streamTypes: ['OUTPUT']
}, chrome.test.callbackPass(function(devices) {
assertDevicesMatch(kTestDevices, devices);
}));
},
function getActiveDevicesTest() {
chrome.audio.getDevices(chrome.test.callbackPass(function(initial) {
var initialActiveDevices = initial.filter(function(device) {
return device.isActive;
});
chrome.test.assertTrue(initialActiveDevices.length > 0);
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(devices) {
assertDevicesMatch(
deviceListToExpectedDevicesMap(initialActiveDevices),
devices);
}));
var initialActiveInputs = initialActiveDevices.filter(function(device) {
return device.streamType === 'INPUT';
});
chrome.test.assertTrue(initialActiveInputs.length > 0);
chrome.audio.getDevices({
isActive: true,
streamTypes: ['INPUT']
}, chrome.test.callbackPass(function(devices) {
assertDevicesMatch(
deviceListToExpectedDevicesMap(initialActiveInputs),
devices);
}));
var initialActiveOutputs = initialActiveDevices.filter(function(device) {
return device.streamType === 'OUTPUT';
});
chrome.test.assertTrue(initialActiveOutputs.length > 0);
chrome.audio.getDevices({
isActive: true,
streamTypes: ['OUTPUT']
}, chrome.test.callbackPass(function(devices) {
assertDevicesMatch(
deviceListToExpectedDevicesMap(initialActiveOutputs),
devices);
}));
}));
},
function getInactiveDevicesTest() {
chrome.audio.getDevices(chrome.test.callbackPass(function(initial) {
var initialInactiveDevices = initial.filter(function(device) {
return !device.isActive;
});
chrome.test.assertTrue(initialInactiveDevices.length > 0);
chrome.audio.getDevices({
isActive: false
}, chrome.test.callbackPass(function(devices) {
assertDevicesMatch(
deviceListToExpectedDevicesMap(initialInactiveDevices),
devices);
}));
}));
},
function setPropertiesTest() {
chrome.audio.getDevices(chrome.test.callbackPass(function(initial) {
var expectedDevices = deviceListToExpectedDevicesMap(initial);
// Update expected input devices with values that should be changed in
// test.
var updatedInput = expectedDevices['40002'];
chrome.test.assertFalse(updatedInput.gain === 65);
updatedInput.level = 65;
// Update expected output devices with values that should be changed in
// test.
var updatedOutput = expectedDevices['30001'];
chrome.test.assertFalse(updatedOutput.volume === 45);
updatedOutput.level = 45;
chrome.audio.setProperties('30001', {
level: 45
}, chrome.test.callbackPass(function() {
chrome.audio.setProperties('40002', {
level: 65
}, chrome.test.callbackPass(function() {
chrome.audio.getDevices(chrome.test.callbackPass(function(devices) {
assertDevicesMatch(expectedDevices, devices);
}));
}));
}));
}));
},
function inputMuteTest() {
var getMute = function(callback) {
chrome.audio.getMute('INPUT', chrome.test.callbackPass(callback));
};
getMute(function(originalValue) {
chrome.audio.setMute(
'INPUT', !originalValue, chrome.test.callbackPass(function() {
getMute(function(value) {
chrome.test.assertEq(!originalValue, value);
});
}));
});
},
function outputMuteTest() {
var getMute = function(callback) {
chrome.audio.getMute('OUTPUT', chrome.test.callbackPass(callback));
};
getMute(function(originalValue) {
chrome.audio.setMute(
'OUTPUT', !originalValue, chrome.test.callbackPass(function() {
getMute(function(value) {
chrome.test.assertEq(!originalValue, value);
});
}));
});
},
function setActiveDevicesTest() {
chrome.audio.setActiveDevices({
input: ['40002', '40003'],
output: ['30001']
}, chrome.test.callbackPass(function() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(activeDevices) {
chrome.test.assertEq(['30001', '40002', '40003'],
getDeviceIds(activeDevices));
}));
}));
},
function setActiveDevicesOutputOnlyTest() {
chrome.audio.getDevices({
streamTypes: ['INPUT'],
isActive: true
}, chrome.test.callbackPass(function(initial) {
var initialActiveInputs = getDeviceIds(initial);
chrome.test.assertTrue(initialActiveInputs.length > 0);
chrome.audio.setActiveDevices({
output: ['30003']
}, chrome.test.callbackPass(function() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(devices) {
var expected = ['30003'].concat(initialActiveInputs).sort();
chrome.test.assertEq(expected, getDeviceIds(devices));
}));
}));
}));
},
function setActiveDevicesFailInputTest() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(initial) {
var initialActiveIds = getDeviceIds(initial);
chrome.test.assertTrue(initialActiveIds.length > 0);
chrome.audio.setActiveDevices({
input: ['0000000'], /* does not exist */
output: []
}, chrome.test.callbackFail('Failed to set active devices.', function() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(devices) {
chrome.test.assertEq(initialActiveIds, getDeviceIds(devices));
}));
}));
}));
},
function setActiveDevicesFailOutputTest() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(initial) {
var initialActiveIds = getDeviceIds(initial);
chrome.test.assertTrue(initialActiveIds.length > 0);
chrome.audio.setActiveDevices({
input: [],
output: ['40001'] /* id is input node ID */
}, chrome.test.callbackFail('Failed to set active devices.', function() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(devices) {
chrome.test.assertEq(initialActiveIds, getDeviceIds(devices));
}));
}));
}));
},
function clearActiveDevicesTest() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(initial) {
chrome.test.assertTrue(getDeviceIds(initial).length > 0);
chrome.audio.setActiveDevices({
input: [],
output: []
}, chrome.test.callbackPass(function() {
chrome.audio.getDevices({
isActive: true
}, chrome.test.callbackPass(function(devices) {
chrome.test.assertEq([], devices);
}));
}));
}));
},
function verifyNoDeviceChangedEvents() {
chrome.test.assertTrue(!!deviceChangedListener);
chrome.test.assertEq(0, deviceChangedListener.eventCount);
deviceChangedListener.reset();
deviceChangedListener = null;
chrome.test.succeed();
},
// Tests verifying the app doesn't have access to deprecated part of the API:
function deprecated_GetInfoTest() {
chrome.audio.getInfo(chrome.test.callbackFail(
'audio.getInfo is deprecated, use audio.getDevices instead.'));
},
function deprecated_setProperties_isMuted() {
chrome.audio.getDevices(chrome.test.callbackPass(function(initial) {
var expectedDevices = deviceListToExpectedDevicesMap(initial);
var expectedError =
'|isMuted| property is deprecated, use |audio.setMute|.';
chrome.audio.setProperties('30001', {
isMuted: true,
// Output device - should have volume set.
level: 55
}, chrome.test.callbackFail(expectedError, function() {
// Assert that device properties haven't changed.
chrome.audio.getDevices(chrome.test.callbackPass(function(devices) {
assertDevicesMatch(expectedDevices, devices);
}));
}));
}));
},
function deprecated_setProperties_volume() {
chrome.audio.getDevices(chrome.test.callbackPass(function(initial) {
var expectedDevices = deviceListToExpectedDevicesMap(initial);
var expectedError = '|volume| property is deprecated, use |level|.';
chrome.audio.setProperties('30001', {
volume: 2,
// Output device - should have volume set.
level: 55
}, chrome.test.callbackFail(expectedError, function() {
// Assert that device properties haven't changed.
chrome.audio.getDevices(chrome.test.callbackPass(function(devices) {
assertDevicesMatch(expectedDevices, devices);
}));
}));
}));
},
function deprecated_setProperties_gain() {
chrome.audio.getDevices(chrome.test.callbackPass(function(initial) {
var expectedDevices = deviceListToExpectedDevicesMap(initial);
var expectedError = '|gain| property is deprecated, use |level|.';
chrome.audio.setProperties('40001', {
gain: 2,
// Output device - should have volume set.
level: 55
}, chrome.test.callbackFail(expectedError, function() {
// Assert that device properties haven't changed.
chrome.audio.getDevices(chrome.test.callbackPass(function(devices) {
assertDevicesMatch(expectedDevices, devices);
}));
}));
}));
},
function deprecated_SetActiveDevicesTest() {
var kExpectedError =
'String list |ids| is deprecated, use DeviceIdLists type.';
chrome.audio.setActiveDevices([
'30003',
'40002'
], chrome.test.callbackFail(kExpectedError));
},
]);
| scheib/chromium | extensions/test/data/api_test/audio/test.js | JavaScript | bsd-3-clause | 16,571 |
/* eslint strict:0 */
var modules = Object.create(null);
var inGuard = false;
function define(id, factory) {
modules[id] = {
factory,
module: {exports: {}},
isInitialized: false,
hasError: false,
};
if (__DEV__) { // HMR
Object.assign(modules[id].module, {
hot: {
acceptCallback: null,
accept: function(callback) {
modules[id].module.hot.acceptCallback = callback;
}
}
});
}
}
function require(id) {
var mod = modules[id];
if (mod && mod.isInitialized) {
return mod.module.exports;
}
return requireImpl(id);
}
function requireImpl(id) {
if (global.ErrorUtils && !inGuard) {
inGuard = true;
var returnValue;
try {
returnValue = requireImpl.apply(this, arguments);
} catch (e) {
global.ErrorUtils.reportFatalError(e);
}
inGuard = false;
return returnValue;
}
var mod = modules[id];
if (!mod) {
var msg = 'Requiring unknown module "' + id + '"';
if (__DEV__) {
msg += '. If you are sure the module is there, try restarting the packager.';
}
throw new Error(msg);
}
if (mod.hasError) {
throw new Error(
'Requiring module "' + id + '" which threw an exception'
);
}
try {
// We must optimistically mark mod as initialized before running the factory to keep any
// require cycles inside the factory from causing an infinite require loop.
mod.isInitialized = true;
__DEV__ && Systrace().beginEvent('JS_require_' + id);
// keep args in sync with with defineModuleCode in
// packager/react-packager/src/Resolver/index.js
mod.factory.call(global, global, require, mod.module, mod.module.exports);
__DEV__ && Systrace().endEvent();
} catch (e) {
mod.hasError = true;
mod.isInitialized = false;
throw e;
}
return mod.module.exports;
}
const Systrace = __DEV__ && (() => {
var _Systrace;
try {
_Systrace = require('Systrace');
} catch (e) {}
return _Systrace && _Systrace.beginEvent ?
_Systrace : { beginEvent: () => {}, endEvent: () => {} };
});
global.__d = define;
global.require = require;
if (__DEV__) { // HMR
function accept(id, factory) {
var mod = modules[id];
if (!mod) {
define(id, factory);
return; // new modules don't need to be accepted
}
if (!mod.module.hot) {
console.warn(
'Cannot accept module because Hot Module Replacement ' +
'API was not installed.'
);
return;
}
if (mod.module.hot.acceptCallback) {
mod.factory = factory;
mod.isInitialized = false;
require(id);
mod.module.hot.acceptCallback();
} else {
console.warn(
'[HMR] Module `' + id + '` can\'t be hot reloaded because it ' +
'doesn\'t provide accept callback hook. Reload the app to get the updates.'
);
}
}
global.__accept = accept;
}
| shinate/react-native | packager/react-packager/src/Resolver/polyfills/require.js | JavaScript | bsd-3-clause | 2,910 |
Subsets and Splits