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
//// [jsxFactoryAndJsxFragmentFactoryNull.tsx] declare var h: any; <></>; <><span>1</span><><span>2.1</span><span>2.2</span></></>; //// [jsxFactoryAndJsxFragmentFactoryNull.js] h(null, null); h(null, null, h("span", null, "1"), h(null, null, h("span", null, "2.1"), h("span", null, "2.2")));
kitsonk/TypeScript
tests/baselines/reference/jsxFactoryAndJsxFragmentFactoryNull.js
JavaScript
apache-2.0
329
import Component from '@ember/component'; import layout from './template'; import { get, set, observer, setProperties } from '@ember/object'; import C from 'ui/utils/constants'; export default Component.extend({ layout, authConfig: null, isEnabled: null, region: null, init() { this._super(...arguments); if ( get(this, 'isEnabled') ) { const endpoint = get(this, 'authConfig.endpoint'); if ( C.AZURE_AD.STANDARD.ENDPOINT.startsWith(endpoint) ) { set(this, 'region', C.AZURE_AD.STANDARD.KEY); } else if ( C.AZURE_AD.CHINA.ENDPOINT.startsWith(endpoint) ) { set(this, 'region', C.AZURE_AD.CHINA.KEY); } else { set(this, 'region', C.AZURE_AD.CUSTOM.KEY); } } else { set(this, 'region', C.AZURE_AD.STANDARD.KEY); this.regionDidChange(); } }, regionDidChange: observer('region', 'authConfig.tenantId', function() { const config = get(this, 'authConfig'); const tenantId = get(this, 'authConfig.tenantId') || ''; const region = get(this, 'region'); switch (region) { case C.AZURE_AD.STANDARD.KEY: setProperties(config, { endpoint: C.AZURE_AD.STANDARD.ENDPOINT, graphEndpoint: C.AZURE_AD.STANDARD.GRAPH_ENDPOINT, tokenEndpoint: `${ C.AZURE_AD.STANDARD.ENDPOINT }${ tenantId }/oauth2/token`, authEndpoint: `${ C.AZURE_AD.STANDARD.ENDPOINT }${ tenantId }/oauth2/authorize`, }); break; case C.AZURE_AD.CHINA.KEY: setProperties(config, { endpoint: C.AZURE_AD.CHINA.ENDPOINT, graphEndpoint: C.AZURE_AD.CHINA.GRAPH_ENDPOINT, tokenEndpoint: `${ C.AZURE_AD.CHINA.ENDPOINT }${ tenantId }/oauth2/token`, authEndpoint: `${ C.AZURE_AD.CHINA.ENDPOINT }${ tenantId }/oauth2/authorize`, }); break; case C.AZURE_AD.CUSTOM.KEY: setProperties(config, { endpoint: C.AZURE_AD.STANDARD.ENDPOINT, graphEndpoint: '', tokenEndpoint: '', authEndpoint: '', }); break; } }), });
westlywright/ui
lib/global-admin/addon/components/azuread-endpoints/component.js
JavaScript
apache-2.0
2,054
/*! * WeX5 v3 (htttp://www.justep.com) * Copyright 2015 Justep, Inc. * Licensed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) */ /** * properties type: string, number, boolean, array, object * binds: key是DOM上的属性名称, value是收集到component中的名称 */ define(function(require){ return { properties: { data: "string", relation: "string", min: "number", max: "number", disabled: "boolean" }, events:["onChange", "onRender"], binds:{"bind-ref": "ref"} }; });
Diaosir/WeX5
UI2/system/components/justep/input/range.config.js
JavaScript
apache-2.0
568
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var index = 0; exports.default = { generate: function generate() { return 'mui-id-' + index++; } }; module.exports = exports['default'];
Maxwelloff/react-football
node_modules/material-ui/lib/utils/unique-id.js
JavaScript
apache-2.0
225
//// [derivedClassTransitivity.ts] // subclassing is not transitive when you can remove required parameters and add optional parameters class C { foo(x: number) { } } class D extends C { foo() { } // ok to drop parameters } class E extends D { foo(x?: string) { } // ok to add optional parameters } var c: C; var d: D; var e: E; c = e; var r = c.foo(1); var r2 = e.foo(''); //// [derivedClassTransitivity.js] // subclassing is not transitive when you can remove required parameters and add optional parameters var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var C = /** @class */ (function () { function C() { } C.prototype.foo = function (x) { }; return C; }()); var D = /** @class */ (function (_super) { __extends(D, _super); function D() { return _super !== null && _super.apply(this, arguments) || this; } D.prototype.foo = function () { }; // ok to drop parameters return D; }(C)); var E = /** @class */ (function (_super) { __extends(E, _super); function E() { return _super !== null && _super.apply(this, arguments) || this; } E.prototype.foo = function (x) { }; // ok to add optional parameters return E; }(D)); var c; var d; var e; c = e; var r = c.foo(1); var r2 = e.foo('');
kitsonk/TypeScript
tests/baselines/reference/derivedClassTransitivity.js
JavaScript
apache-2.0
2,039
$(document).ready(function () { setTablePagination(0); getLocationSessionData(); }); function createAuthorizationCode() { var action = "createAuthCodeRequest"; var key = $("#key").val(); var secret = $("#secret").val(); if ((jQuery.trim(key).length > 0) && (jQuery.trim(secret).length > 0)) { jagg.post("/site/blocks/authorization-api/ajax/authorization-api.jag", { action: action, key: key, secret: secret }, function (result) { if (!result.error) { if (result.data != "null") { $('#lbsAddMessage').show(); $('#lbsAddMessage').delay(4000).hide('fast'); $('#authCode').val(result.data); $('#auth_header').val('Basic ' + result.data); $('#token').val(result.data); //window.location.reload(); } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } }, "json"); } else { document.getElementById("error_message").innerHTML = "Please enter a valid Consumer Key and a Consumer Secret to proceed"; } }; var reqUrl; function saveRefreshToken() { var action = "generateRefreshToken"; var granttype = $("#granttype").val(); var username = $("#username").val(); var password = $("#password").val(); var scope = $("#scope").val(); var token = $("#token").val(); jagg.post("/site/blocks/authorization-api/ajax/authorization-api.jag", { action: action, granttype: granttype, username: username, password: password, scope: scope, token: token }, function (result) { reqUrl = 'https://ideabiz.lk/apicall/token?grant_type=' + granttype + '&username=' + username + '&password=' + password + '&scope=' + scope $("#granttype").val(''); $("#username").val(''); $("#password").val(''); $("#scope").val(''); $("#token").val(''); $("#url").val(reqUrl); if (!result.error) { if (result.data != "null") { $('#lbsAddMessage').show(); $('#lbsAddMessage').delay(4000).hide('fast'); window.location.reload(); } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } setTablePagination(0); } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } }, "json"); }; function sendMobileIdApiRequestWithToken(authorization) { var action = "sendMobileIdApiRequestWithToken"; jagg.post("/site/blocks/authorization-api/ajax/authorization-api.jag", { action: action, authorization: authorization }, function (result) { if (!result.error) { if (result.data != "null") { $('#json-response').val(result.data); $("#mobileidapi_table_content").empty(); //createMobileIdApiTable(result.table); } else { $('#errorMessage').show(); $('#errorMessage').delay(4000).hide('fast'); } setTablePagination(0); } else { $('#errorMessage').show(); $('#errorMessage').delay(4000).hide('fast'); } }, "json"); }; function setTablePagination(pageNumber) { paginator(pageNumber); } function paginator(pageNumber) { var rows = $("#loc_request_table tbody tr").length; var rowsPerPage = 10; if (rows > rowsPerPage) { var numberOfPages = Math.ceil(rows / rowsPerPage); var currentPageStart = pageNumber * rowsPerPage; var currentPageEnd = (pageNumber * rowsPerPage) + rowsPerPage; for (var i = 0; i < rows; i++) { if ((currentPageStart <= i) & (i < currentPageEnd)) { $("#loc_request_table tr").eq(i).show(); } else { $("#loc_request_table tbody tr").eq(i).hide(); } } loadPaginatorView(numberOfPages, pageNumber); } else { $(".pagination").html(''); } } function loadPaginatorView(numberOfPages, currentPage) { $(".pagination").html('<ul></ul>'); var previousAppender = '<li><a href="javascript:paginator(0)"><<</a></li>'; if (currentPage == 0) { previousAppender = '<li class="disabled"><a><<</a></li>'; } $(".pagination ul").append(previousAppender); for (var i = 0; i < numberOfPages; i++) { var currentRow; var rowSticker = i + 1; if (i == currentPage) { currentRow = '<li class="active"><a>' + rowSticker + '</a></li>'; } else { currentRow = '<li><a href="javascript:paginator(' + i + ')">' + rowSticker + '</a></li>'; } $(".pagination ul").append(currentRow); } var lastPage = numberOfPages - 1; var postAppender = '<li><a href="javascript:paginator(' + lastPage + ')">>></a></li>'; if (currentPage == lastPage) { postAppender = '<li class="disabled"><a>>></a></li>'; } $(".pagination ul").append(postAppender); } function generateRefreshToken() { var action = "getRefreshToken"; var url = $("#url").val(); jagg.post("/site/blocks/authorization-api/ajax/authorization-api.jag", { action: action, url: url }, function (result) { var json = result.data, obj = JSON.parse(json); obj.MobileIdApiRequest.refreshToken; $('#refresh_token').val(obj.MobileIdApiRequest.refreshToken); $('#json-response').val(result.data); if (!result.error) { if (result.data != "null") { $('#lbsAddMessage').show(); $('#lbsAddMessage').delay(4000).hide('fast'); window.location.reload(); } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } setTablePagination(0); } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } }, "json"); }; function generateAccessToken() { var action = "generateAccessTokenRequest"; var grant_type = $("#grant_type").val(); var refresh_token = $("#refresh_token").val(); var scope = $("#token_scope").val(); var auth_code = $("#authCode").val(); if ((jQuery.trim(grant_type).length > 0) && (jQuery.trim(refresh_token).length > 0) && (jQuery.trim(scope).length > 0) && (jQuery.trim(auth_code).length > 0)) { jagg.post("/site/blocks/authorization-api/ajax/authorization-api.jag", { action: action, grant_type: grant_type, refresh_token: refresh_token, scope: scope, auth_code: auth_code }, function (result) { if (!result.error) { if (result.data != "null") { $('#lbsAddMessage').show(); $('#lbsAddMessage').delay(4000).hide('fast'); $('#json-response-token').val(result.data); var url = $('#access_token_url').val() + grant_type + '&refresh_token=' + refresh_token + '&scope=' + scope; $('#access_token_url').val(url); window.location.reload(); } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } } else { $('#lbsErrorMessage').show(); $('#lbsErrorMessage').delay(4000).hide('fast'); } }, "json"); } else { document.getElementById("access_token_error_message").innerHTML = "Please enter a valid grant type and a Scope to proceed"; } };
WSO2Telco/component-dep
components/jaggery-apps/sandbox/src/main/sandbox/site/themes/default/templates/authorization-api/js/authorization-api.js
JavaScript
apache-2.0
8,165
$(document).ready( function() { $("table.table-striped").each( function(i,o) { $(o).tablesorter(); }); });
GEANT/met
static/js/sort_startup.js
JavaScript
bsd-2-clause
124
Rickshaw.namespace("Rickshaw.Graph.Renderer"); Rickshaw.Graph.Renderer = Rickshaw.Class.create( { initialize: function(args) { this.graph = args.graph; this.tension = args.tension || this.tension; this.graph.unstacker = this.graph.unstacker || new Rickshaw.Graph.Unstacker( { graph: this.graph } ); this.configure(args); }, seriesPathFactory: function() { //implement in subclass }, seriesStrokeFactory: function() { // implement in subclass }, defaults: function() { return { tension: 0.8, strokeWidth: 2, unstack: true, padding: { top: 0.01, right: 0, bottom: 0.01, left: 0 }, stroke: false, fill: false }; }, domain: function() { var values = { xMin: [], xMax: [], y: [] }; var stackedData = this.graph.stackedData || this.graph.stackData(); var firstPoint = stackedData[0][0]; var xMin = firstPoint.x; var xMax = firstPoint.x var yMin = firstPoint.y + firstPoint.y0; var yMax = firstPoint.y + firstPoint.y0; stackedData.forEach( function(series) { series.forEach( function(d) { var y = d.y + d.y0; if (y < yMin) yMin = y; if (y > yMax) yMax = y; } ); if (series[0].x < xMin) xMin = series[0].x; if (series[series.length - 1].x > xMax) xMax = series[series.length - 1].x; } ); xMin -= (xMax - xMin) * this.padding.left; xMax += (xMax - xMin) * this.padding.right; yMin = this.graph.min === 'auto' ? yMin : this.graph.min || 0; yMax = this.graph.max || yMax; if (this.graph.min === 'auto' || yMin < 0) { yMin -= (yMax - yMin) * this.padding.bottom; } if (this.graph.max === undefined) { yMax += (yMax - yMin) * this.padding.top; } return { x: [xMin, xMax], y: [yMin, yMax] }; }, render: function() { var graph = this.graph; graph.vis.selectAll('*').remove(); var nodes = graph.vis.selectAll("path") .data(this.graph.stackedData) .enter().append("svg:path") .attr("d", this.seriesPathFactory()); var i = 0; graph.series.forEach( function(series) { if (series.disabled) return; series.path = nodes[0][i++]; this._styleSeries(series); }, this ); }, _styleSeries: function(series) { var fill = this.fill ? series.color : 'none'; var stroke = this.stroke ? series.color : 'none'; series.path.setAttribute('fill', fill); series.path.setAttribute('stroke', stroke); series.path.setAttribute('stroke-width', this.strokeWidth); series.path.setAttribute('class', series.className); }, configure: function(args) { args = args || {}; Rickshaw.keys(this.defaults()).forEach( function(key) { if (!args.hasOwnProperty(key)) { this[key] = this[key] || this.graph[key] || this.defaults()[key]; return; } if (typeof this.defaults()[key] == 'object') { Rickshaw.keys(this.defaults()[key]).forEach( function(k) { this[key][k] = args[key][k] !== undefined ? args[key][k] : this[key][k] !== undefined ? this[key][k] : this.defaults()[key][k]; }, this ); } else { this[key] = args[key] !== undefined ? args[key] : this[key] !== undefined ? this[key] : this.graph[key] !== undefined ? this.graph[key] : this.defaults()[key]; } }, this ); }, setStrokeWidth: function(strokeWidth) { if (strokeWidth !== undefined) { this.strokeWidth = strokeWidth; } }, setTension: function(tension) { if (tension !== undefined) { this.tension = tension; } } } );
cwvh/scalable-maker
ui/public/js/Rickshaw.Graph.Renderer.js
JavaScript
bsd-2-clause
3,423
// global variables var listAllScope = ["global", "public", "private", "testMethod", "webService"]; // document ready function $(function () { readScopeCookie(); hideAllScopes(); showScopes(); }); function expandListToClass(liClass) { var cl = $('#mynavbar').collapsibleList('.header', {search: false, animate: false}); var clist = $('#mynavbar').data('collapsibleList'); clist.collapseAll(); $('.nav-selected').each(function() { $(this).removeClass('nav-selected'); }); if (liClass != null) { // liClass is a jquery object. liClass.addClass('nav-selected'); clist.expandToElementListScope(liClass, getListScope()); } else { // get just the filename without extension from the url var i = location.pathname.lastIndexOf("/"); var filename = location.pathname.substring(i + 1, location.pathname.length - 5); // select the filename in the list node = document.getElementById('idMenu' + filename); if (node != null) { node.classList.add('nav-selected'); var li = $('#idMenu'+filename); clist.expandToElementListScope(li, getListScope()); } } } function getListScope() { var list = []; $('input:checkbox').each(function(index, elem) { if (elem.checked) { var str = elem.id; str = str.replace('cbx', ''); list.push(str); } }); return list; } function showScopes() { var list = getListScope(); for (var i = 0; i < list.length; i++) { ToggleScope(list[i], true); } } function showAllScopes() { for (var i = 0; i < listAllScope.length; i++) { ToggleScope(listAllScope[i], true); } } function hideAllScopes() { for (var i = 0; i < listAllScope.length; i++) { ToggleScope(listAllScope[i], false); } } function setScopeCookie() { var list = getListScope(); var strScope = ''; var comma = ''; for (var i = 0; i < list.length; i++) { strScope += comma + list[i]; comma = ','; } document.cookie = 'scope=' + strScope + '; path=/'; } function readScopeCookie() { var strScope = getCookie('scope'); if (strScope != null && strScope != '') { // first clear all the scope checkboxes $('input:checkbox').each(function(index, elem) { elem.checked = false; }); // now check the appropriate scope checkboxes var list = strScope.split(','); for (var i = 0; i < list.length; i++) { var id = 'cbx' + list[i]; $('#' + id).prop('checked', true); } } else { showAllScopes(); } } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length, c.length); } return ""; } function gotomenu(url, event) { if (document.location.href.toLowerCase().indexOf(url.toLowerCase()) == -1) document.location.href = url; else { var clist = $('#mynavbar').data('collapsibleList'); var filename = url.replace('.html', ''); //var li = $('#idMenu'+filename); var li = $(event.currentTarget.parentNode); var isCollapsed = li.hasClass('collapsed'); if (isCollapsed) { expandListToClass(li); event.stopImmediatePropagation(); } else { clist.collapseElement(li); event.stopImmediatePropagation(); } } } function ToggleScope(scope, isShow) { setScopeCookie(); if (isShow == true) { // show all properties of the given scope $('.propertyscope' + scope).show(); // show all methods of the given scope $('.methodscope' + scope).show(); // redisplay the class list expandListToClass(); } else { // hide all properties of the given scope $('.propertyscope' + scope).hide(); // hide all methods of the given scope $('.methodscope' + scope).hide(); // hide all classes of the given scope $('.classscope' + scope).hide(); } }
force2b/ApexDoc
src/org/salesforce/apexdoc/ApexDoc.js
JavaScript
bsd-3-clause
4,472
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. const path = require('path'); const fs = require('fs-extra'); const Handlebars = require('handlebars'); const Build = require('@jupyterlab/builder').Build; const webpack = require('webpack'); const merge = require('webpack-merge').default; const baseConfig = require('@jupyterlab/builder/lib/webpack.config.base'); const { ModuleFederationPlugin } = webpack.container; const packageData = require('./package.json'); const jlab = packageData.jupyterlab; // Create a list of application extensions and mime extensions from // jlab.extensions const extensions = {}; const mimeExtensions = {}; for (const key of jlab.extensions) { const { jupyterlab: { extension, mimeExtension } } = require(`${key}/package.json`); if (extension !== undefined) { extensions[key] = extension === true ? '' : extension; } if (mimeExtension !== undefined) { mimeExtensions[key] = mimeExtension === true ? '' : mimeExtension; } } // buildDir is a temporary directory where files are copied before the build. const buildDir = path.resolve(jlab.buildDir); fs.emptyDirSync(buildDir); // outputDir is where the final built assets go const outputDir = path.resolve(jlab.outputDir); fs.emptyDirSync(outputDir); // <schemaDir>/schemas is where the settings schemas live const schemaDir = path.resolve(jlab.schemaDir || outputDir); // ensureAssets puts schemas in the schemas subdirectory fs.emptyDirSync(path.join(schemaDir, 'schemas')); // <themeDir>/themes is where theme assets live const themeDir = path.resolve(jlab.themeDir || outputDir); // ensureAssets puts themes in the themes subdirectory fs.emptyDirSync(path.join(themeDir, 'themes')); // Configuration to handle extension assets const extensionAssetConfig = Build.ensureAssets({ packageNames: jlab.extensions, output: buildDir, schemaOutput: schemaDir, themeOutput: themeDir }); // Create the entry point and other assets in build directory. const template = Handlebars.compile( fs.readFileSync('index.template.js').toString() ); fs.writeFileSync( path.join(buildDir, 'index.js'), template({ extensions, mimeExtensions }) ); // Create the bootstrap file that loads federated extensions and calls the // initialization logic in index.js const entryPoint = path.join(buildDir, 'bootstrap.js'); fs.copySync('./bootstrap.js', entryPoint); /** * Create the webpack ``shared`` configuration */ function createShared(packageData) { // Set up module federation sharing config const shared = {}; const extensionPackages = packageData.jupyterlab.extensions; // Make sure any resolutions are shared for (let [pkg, requiredVersion] of Object.entries(packageData.resolutions)) { shared[pkg] = { requiredVersion }; } // Add any extension packages that are not in resolutions (i.e., installed from npm) for (let pkg of extensionPackages) { if (!shared[pkg]) { shared[pkg] = { requiredVersion: require(`${pkg}/package.json`).version }; } } // Add dependencies and sharedPackage config from extension packages if they // are not already in the shared config. This means that if there is a // conflict, the resolutions package version is the one that is shared. const extraShared = []; for (let pkg of extensionPackages) { let pkgShared = {}; let { dependencies = {}, jupyterlab: { sharedPackages = {} } = {} } = require(`${pkg}/package.json`); for (let [dep, requiredVersion] of Object.entries(dependencies)) { if (!shared[dep]) { pkgShared[dep] = { requiredVersion }; } } // Overwrite automatic dependency sharing with custom sharing config for (let [dep, config] of Object.entries(sharedPackages)) { if (config === false) { delete pkgShared[dep]; } else { if ('bundled' in config) { config.import = config.bundled; delete config.bundled; } pkgShared[dep] = config; } } extraShared.push(pkgShared); } // Now merge the extra shared config const mergedShare = {}; for (let sharedConfig of extraShared) { for (let [pkg, config] of Object.entries(sharedConfig)) { // Do not override the basic share config from resolutions if (shared[pkg]) { continue; } // Add if we haven't seen the config before if (!mergedShare[pkg]) { mergedShare[pkg] = config; continue; } // Choose between the existing config and this new config. We do not try // to merge configs, which may yield a config no one wants let oldConfig = mergedShare[pkg]; // if the old one has import: false, use the new one if (oldConfig.import === false) { mergedShare[pkg] = config; } } } Object.assign(shared, mergedShare); // Transform any file:// requiredVersion to the version number from the // imported package. This assumes (for simplicity) that the version we get // importing was installed from the file. for (let [pkg, { requiredVersion }] of Object.entries(shared)) { if (requiredVersion && requiredVersion.startsWith('file:')) { shared[pkg].requiredVersion = require(`${pkg}/package.json`).version; } } // Add singleton package information for (let pkg of packageData.jupyterlab.singletonPackages) { shared[pkg].singleton = true; } return shared; } const plugins = [ new ModuleFederationPlugin({ library: { type: 'var', name: ['_JUPYTERLAB', 'CORE_LIBRARY_FEDERATION'] }, name: 'CORE_FEDERATION', shared: createShared(packageData) }) ]; module.exports = [ merge(baseConfig, { mode: 'development', devtool: 'source-map', entry: ['./publicpath.js', entryPoint], output: { path: path.resolve(outputDir), library: { type: 'var', name: ['_JUPYTERLAB', 'CORE_OUTPUT'] }, filename: 'bundle.js' }, optimization: { splitChunks: { chunks: 'all', cacheGroups: { jlab_core: { test: /[\\/](node_modules[\\/]@(jupyterlab|lumino)|packages)[\\/]/, name: 'jlab_core' } } } }, plugins }) ].concat(extensionAssetConfig); // For debugging, write the config out fs.writeFileSync( path.join(buildDir, 'webpack.config-log.json'), JSON.stringify(module.exports, null, ' ') );
jupyter/jupyterlab
examples/federated/core_package/webpack.config.js
JavaScript
bsd-3-clause
6,455
SDPUtil = { iceparams: function (mediadesc, sessiondesc) { var data = null; if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) && SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) { data = { ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)), pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) }; } return data; }, parse_iceufrag: function (line) { return line.substring(12); }, build_iceufrag: function (frag) { return 'a=ice-ufrag:' + frag; }, parse_icepwd: function (line) { return line.substring(10); }, build_icepwd: function (pwd) { return 'a=ice-pwd:' + pwd; }, parse_mid: function (line) { return line.substring(6); }, parse_mline: function (line) { var parts = line.substring(2).split(' '), data = {}; data.media = parts.shift(); data.port = parts.shift(); data.proto = parts.shift(); if (parts[parts.length - 1] === '') { // trailing whitespace parts.pop(); } data.fmt = parts; return data; }, build_mline: function (mline) { return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' '); }, parse_rtpmap: function (line) { var parts = line.substring(9).split(' '), data = {}; data.id = parts.shift(); parts = parts[0].split('/'); data.name = parts.shift(); data.clockrate = parts.shift(); data.channels = parts.length ? parts.shift() : '1'; return data; }, /** * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it. * @param line eg. "a=sctpmap:5000 webrtc-datachannel" * @returns [SCTP port number, protocol, streams] */ parse_sctpmap: function (line) { var parts = line.substring(10).split(' '); var sctpPort = parts[0]; var protocol = parts[1]; // Stream count is optional var streamCount = parts.length > 2 ? parts[2] : null; return [sctpPort, protocol, streamCount];// SCTP port }, build_rtpmap: function (el) { var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate'); if (el.getAttribute('channels') && el.getAttribute('channels') != '1') { line += '/' + el.getAttribute('channels'); } return line; }, parse_crypto: function (line) { var parts = line.substring(9).split(' '), data = {}; data.tag = parts.shift(); data['crypto-suite'] = parts.shift(); data['key-params'] = parts.shift(); if (parts.length) { data['session-params'] = parts.join(' '); } return data; }, parse_fingerprint: function (line) { // RFC 4572 var parts = line.substring(14).split(' '), data = {}; data.hash = parts.shift(); data.fingerprint = parts.shift(); // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ? return data; }, parse_fmtp: function (line) { var parts = line.split(' '), i, key, value, data = []; parts.shift(); parts = parts.join(' ').split(';'); for (i = 0; i < parts.length; i++) { key = parts[i].split('=')[0]; while (key.length && key[0] == ' ') { key = key.substring(1); } value = parts[i].split('=')[1]; if (key && value) { data.push({name: key, value: value}); } else if (key) { // rfc 4733 (DTMF) style stuff data.push({name: '', value: key}); } } return data; }, parse_icecandidate: function (line) { var candidate = {}, elems = line.split(' '); candidate.foundation = elems[0].substring(12); candidate.component = elems[1]; candidate.protocol = elems[2].toLowerCase(); candidate.priority = elems[3]; candidate.ip = elems[4]; candidate.port = elems[5]; // elems[6] => "typ" candidate.type = elems[7]; candidate.generation = 0; // default value, may be overwritten below for (var i = 8; i < elems.length; i += 2) { switch (elems[i]) { case 'raddr': candidate['rel-addr'] = elems[i + 1]; break; case 'rport': candidate['rel-port'] = elems[i + 1]; break; case 'generation': candidate.generation = elems[i + 1]; break; case 'tcptype': candidate.tcptype = elems[i + 1]; break; default: // TODO console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"'); } } candidate.network = '1'; candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random return candidate; }, build_icecandidate: function (cand) { var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' '); line += ' '; switch (cand.type) { case 'srflx': case 'prflx': case 'relay': if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) { line += 'raddr'; line += ' '; line += cand['rel-addr']; line += ' '; line += 'rport'; line += ' '; line += cand['rel-port']; line += ' '; } break; } if (cand.hasOwnAttribute('tcptype')) { line += 'tcptype'; line += ' '; line += cand.tcptype; line += ' '; } line += 'generation'; line += ' '; line += cand.hasOwnAttribute('generation') ? cand.generation : '0'; return line; }, parse_ssrc: function (desc) { // proprietary mapping of a=ssrc lines // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs // and parse according to that var lines = desc.split('\r\n'), data = {}; for (var i = 0; i < lines.length; i++) { if (lines[i].substring(0, 7) == 'a=ssrc:') { var idx = lines[i].indexOf(' '); data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1]; } } return data; }, parse_rtcpfb: function (line) { var parts = line.substr(10).split(' '); var data = {}; data.pt = parts.shift(); data.type = parts.shift(); data.params = parts; return data; }, parse_extmap: function (line) { var parts = line.substr(9).split(' '); var data = {}; data.value = parts.shift(); if (data.value.indexOf('/') != -1) { data.direction = data.value.substr(data.value.indexOf('/') + 1); data.value = data.value.substr(0, data.value.indexOf('/')); } else { data.direction = 'both'; } data.uri = parts.shift(); data.params = parts; return data; }, find_line: function (haystack, needle, sessionpart) { var lines = haystack.split('\r\n'); for (var i = 0; i < lines.length; i++) { if (lines[i].substring(0, needle.length) == needle) { return lines[i]; } } if (!sessionpart) { return false; } // search session part lines = sessionpart.split('\r\n'); for (var j = 0; j < lines.length; j++) { if (lines[j].substring(0, needle.length) == needle) { return lines[j]; } } return false; }, find_lines: function (haystack, needle, sessionpart) { var lines = haystack.split('\r\n'), needles = []; for (var i = 0; i < lines.length; i++) { if (lines[i].substring(0, needle.length) == needle) needles.push(lines[i]); } if (needles.length || !sessionpart) { return needles; } // search session part lines = sessionpart.split('\r\n'); for (var j = 0; j < lines.length; j++) { if (lines[j].substring(0, needle.length) == needle) { needles.push(lines[j]); } } return needles; }, candidateToJingle: function (line) { // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0 // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../> if (line.indexOf('candidate:') === 0) { line = 'a=' + line; } else if (line.substring(0, 12) != 'a=candidate:') { console.log('parseCandidate called with a line that is not a candidate line'); console.log(line); return null; } if (line.substring(line.length - 2) == '\r\n') // chomp it line = line.substring(0, line.length - 2); var candidate = {}, elems = line.split(' '), i; if (elems[6] != 'typ') { console.log('did not find typ in the right place'); console.log(line); return null; } candidate.foundation = elems[0].substring(12); candidate.component = elems[1]; candidate.protocol = elems[2].toLowerCase(); candidate.priority = elems[3]; candidate.ip = elems[4]; candidate.port = elems[5]; // elems[6] => "typ" candidate.type = elems[7]; candidate.generation = '0'; // default, may be overwritten below for (i = 8; i < elems.length; i += 2) { switch (elems[i]) { case 'raddr': candidate['rel-addr'] = elems[i + 1]; break; case 'rport': candidate['rel-port'] = elems[i + 1]; break; case 'generation': candidate.generation = elems[i + 1]; break; case 'tcptype': candidate.tcptype = elems[i + 1]; break; default: // TODO console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"'); } } candidate.network = '1'; candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random return candidate; }, candidateFromJingle: function (cand) { var line = 'a=candidate:'; line += cand.getAttribute('foundation'); line += ' '; line += cand.getAttribute('component'); line += ' '; line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this line += ' '; line += cand.getAttribute('priority'); line += ' '; line += cand.getAttribute('ip'); line += ' '; line += cand.getAttribute('port'); line += ' '; line += 'typ'; line += ' ' + cand.getAttribute('type'); line += ' '; switch (cand.getAttribute('type')) { case 'srflx': case 'prflx': case 'relay': if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) { line += 'raddr'; line += ' '; line += cand.getAttribute('rel-addr'); line += ' '; line += 'rport'; line += ' '; line += cand.getAttribute('rel-port'); line += ' '; } break; } if (cand.getAttribute('protocol').toLowerCase() == 'tcp') { line += 'tcptype'; line += ' '; line += cand.getAttribute('tcptype'); line += ' '; } line += 'generation'; line += ' '; line += cand.getAttribute('generation') || '0'; return line + '\r\n'; } }; module.exports = SDPUtil;
dwanghf/jitsi-meet
modules/xmpp/SDPUtil.js
JavaScript
mit
12,879
/* * RequireJS 'is' plugin * * Usage: * * is!myFeature?module:another * is!~myFeature?module (negation) * * * Features can be set as startup config with * config: { * is: { * var: true * } * } * * Otherwise the feature is assumed to be a moduleId resolving to a boolean. * * Thus to write a dynamic feature, say iphone.js, just do: * * iphone.js: * define(function() { * if (typeof navigator === 'undefined' || typeof navigator.userAgent === 'undefined') * return false; * return navigator.userAgent.match(/iPhone/i); * }); * * Which can then be used with a require of the form: is!iphone?iphone-scripts. * * * Builds * The build environment features are computed in the same way as in development. The only difference is * that features are not at all evaluated. * * It is important to retain the config for features that don't resolve to moduleIds as this is the only * distinction between feature detection modules and configuration items. * Simply set them all to 'true' to indicate that we don't need to build in their feature detection code. * * By default, all conditional modules are written in to the build layer. * * Then to exclude a feature's modules in a layer, simply add the 'isExclude' array of features to the module config, * or the global build config - both are respected and complementary. * * This will entirely exxlude those feature modules from the layer build. The condition itself still remains * undetermined until the environment execution. * * Feature layers can be created with config as in the following - * * Example: * * { * modules: [ * { * name: 'core', * create: true, * include: ['some', 'core', 'modules'], * isExclude: ['mobile'], //exclude all is!mobile? conditional dependencies * }, * { * name: 'core-mobile', * create: true, * include: ['some', 'core', 'modules'], * exclude: ['core'] * } * ] * } * * isExclude can also be a global config for single file builds, or sharing config between the builds. * */ define(['module', './is-api', 'require'], function(module, api, require) { is = {}; is.pluginBuilder = './is-builder'; is.normalize = api.normalize; is.features = module.config() || {}; //add 'browser' feature if (is.features.browser === undefined) is.features.browser = (typeof window != 'undefined'); if (is.features.build === undefined) is.features.build = false; //build tracking is.curModule = null; is.modules = null; is.empty = function() { return null; } is.lookup = function(feature, complete) { if (is.features[feature] !== undefined) { complete(is.features[feature]); return; } require([feature], function(_feature) { if (_feature !== true && _feature !== false) throw 'Feature module ' + feature + ' must return true or false.'; is.features[feature] = _feature; complete(_feature); }); } is.load = function(name, req, load, config) { var f = api.parse(name); if (f.type == 'lookup') is.lookup(f.feature, load); if (f.type == 'load_if' || f.type == 'load_if_not') { //check feature is.lookup(f.feature, function(_feature) { if ((_feature && f.type == 'load_if') || (!_feature && f.type == 'load_if_not')) //if doing a build, check if we are including the module or not require([f.yesModuleId], load); else if ((!_feature && f.type == 'load_if' && f.noModuleId) || (_feature && f.type == 'load_if_not' && f.noModuleId)) require([f.noModuleId], load); else load(is.empty()); }); } } return is; });
Lugribossk/publication-api-experiment
src/main/javascript/lib/require-is/is.js
JavaScript
mit
3,768
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * * @format */ 'use strict'; const readline = require('readline'); const throttle = require('lodash/throttle'); const tty = require('tty'); const util = require('util'); /** * Clear some text that was previously printed on an interactive stream, * without trailing newline character (so we have to move back to the * beginning of the line). */ function clearStringBackwards(stream, str) { readline.moveCursor(stream, -stream.columns, 0); readline.clearLine(stream, 0); let lineCount = (str.match(/\n/g) || []).length; while (lineCount > 0) { readline.moveCursor(stream, 0, -1); readline.clearLine(stream, 0); --lineCount; } } /** * Cut a string into an array of string of the specific maximum size. A newline * ends a chunk immediately (it's not included in the "." RexExp operator), and * is not included in the result. */ function chunkString(str, size) { return str.match(new RegExp(`.{1,${size}}`, 'g')) || []; } /** * Get the stream as a TTY if it effectively looks like a valid TTY. */ function getTTYStream(stream) { if ( stream instanceof tty.WriteStream && stream.isTTY && stream.columns >= 1) { return stream; } return null; } /** * We don't just print things to the console, sometimes we also want to show * and update progress. This utility just ensures the output stays neat: no * missing newlines, no mangled log lines. * * const terminal = Terminal.default; * terminal.status('Updating... 38%'); * terminal.log('warning: Something happened.'); * terminal.status('Updating, done.'); * terminal.persistStatus(); * * The final output: * * warning: Something happened. * Updating, done. * * Without the status feature, we may get a mangled output: * * Updating... 38%warning: Something happened. * Updating, done. * * This is meant to be user-readable and TTY-oriented. We use stdout by default * because it's more about status information than diagnostics/errors (stderr). * * Do not add any higher-level functionality in this class such as "warning" and * "error" printers, as it is not meant for formatting/reporting. It has the * single responsibility of handling status messages. */ class Terminal { constructor(stream) { this._logLines = []; this._nextStatusStr = ''; this._scheduleUpdate = throttle(this._update, 0); this._statusStr = ''; this._stream = stream; } /** * Clear and write the new status, logging in bulk in-between. Doing this in a * throttled way (in a different tick than the calls to `log()` and * `status()`) prevents us from repeatedly rewriting the status in case * `terminal.log()` is called several times. */ _update() {const _statusStr = this._statusStr,_stream = this._stream; const ttyStream = getTTYStream(_stream); if (_statusStr === this._nextStatusStr && this._logLines.length === 0) { return; } if (ttyStream != null) { clearStringBackwards(ttyStream, _statusStr); } this._logLines.forEach(line => { _stream.write(line); _stream.write('\n'); }); this._logLines = []; if (ttyStream != null) { this._nextStatusStr = chunkString( this._nextStatusStr, ttyStream.columns). join('\n'); _stream.write(this._nextStatusStr); } this._statusStr = this._nextStatusStr; } /** * Shows some text that is meant to be overriden later. Return the previous * status that was shown and is no more. Calling `status()` with no argument * removes the status altogether. The status is never shown in a * non-interactive terminal: for example, if the output is redirected to a * file, then we don't care too much about having a progress bar. */ status(format) {const _nextStatusStr = this._nextStatusStr;for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {args[_key - 1] = arguments[_key];} this._nextStatusStr = util.format(format, ...args); this._scheduleUpdate(); return _nextStatusStr; } /** * Similar to `console.log`, except it moves the status/progress text out of * the way correctly. In non-interactive terminals this is the same as * `console.log`. */ log(format) {for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {args[_key2 - 1] = arguments[_key2];} this._logLines.push(util.format(format, ...args)); this._scheduleUpdate(); } /** * Log the current status and start from scratch. This is useful if the last * status was the last one of a series of updates. */ persistStatus() { this.log(this._nextStatusStr); this._nextStatusStr = ''; }} module.exports = Terminal;
gunaangs/Feedonymous
node_modules/metro-bundler/src/lib/Terminal.js
JavaScript
mit
5,317
'use strict'; module.exports = function (client) { client.disco.addFeature('urn:xmpp:carbons:2'); client.enableCarbons = function (cb) { return this.sendIq({ type: 'set', enableCarbons: true }, cb); }; client.disableCarbons = function (cb) { return this.sendIq({ type: 'set', disableCarbons: true }, cb); }; client.on('message', function (msg) { if (msg.carbonSent) { return client.emit('carbon:sent', msg); } if (msg.carbonReceived) { return client.emit('carbon:received', msg); } }); client.on('carbon:*', function (name, carbon) { var dir = name.split(':')[1]; if (carbon.from.bare !== client.jid.bare) { return; } var msg, delay; if (dir === 'received') { msg = carbon.carbonReceived.forwarded.message; delay = carbon.carbonReceived.forwarded.delay; } else { msg = carbon.carbonSent.forwarded.message; delay = carbon.carbonSent.forwarded.delay; } if (!msg.delay) { if (delay) { msg.delay.stamp = delay.stamp; } else { msg.delay = { stamp: new Date(Date.now()) }; } } msg.carbon = true; // Treat the carbon copied message however we would // have originally treated it ourself. if (msg.from.bare === client.jid.bare) { client.emit('message:sent', msg); } else { client.emit('message', msg); } }); };
glpenghui/stanza.io
lib/plugins/carbons.js
JavaScript
mit
1,696
/* */ var isObject = require('./_is-object'); require('./_object-sap')('isFrozen', function($isFrozen) { return function isFrozen(it) { return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; }; });
alexandre-spieser/AureliaAspNetCoreAuth
src/AureliaAspNetCoreAuth/wwwroot/jspm_packages/npm/[email protected]/modules/es6.object.is-frozen.js
JavaScript
mit
216
/*! jQuery UI - v1.9.2 - 2013-05-03 * http://jqueryui.com * Includes: jquery.ui.datepicker-hi.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.hi={closeText:"बंद",prevText:"पिछला",nextText:"अगला",currentText:"आज",monthNames:["जनवरी ","फरवरी","मार्च","अप्रेल","मई","जून","जूलाई","अगस्त ","सितम्बर","अक्टूबर","नवम्बर","दिसम्बर"],monthNamesShort:["जन","फर","मार्च","अप्रेल","मई","जून","जूलाई","अग","सित","अक्ट","नव","दि"],dayNames:["रविवार","सोमवार","मंगलवार","बुधवार","गुरुवार","शुक्रवार","शनिवार"],dayNamesShort:["रवि","सोम","मंगल","बुध","गुरु","शुक्र","शनि"],dayNamesMin:["रवि","सोम","मंगल","बुध","गुरु","शुक्र","शनि"],weekHeader:"हफ्ता",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.hi)});
onlyvicisvicboy/nva
web/demo/cuthtml/development-bundle/ui/minified/i18n/jquery.ui.datepicker-hi.min.js
JavaScript
mit
1,272
angular.module('app') .controller('MainController', function($scope, $http, $location) { _this = this; this.user; this.session = "ko"; this.login = {status: ''} this.signout = function() { $http.post('/logout') .then(function (res) { $scope.main.session = "ko"; $scope.main.user = {}; $location.path('/users/SignIn') }); }; }).controller('UserController', function($scope, $http, md5, $location) { var _this = this; this.getUser = function () { $http.get('/api/user') .then(function (res) { _this.user = res.data[0]; }); }; this.signin = function() { var hashedPassword = md5.createHash(this.user.password); this.user.password = hashedPassword; $http.post('/login', this.user) .then(function (res) { $scope.main.user = res.data; $scope.login = {status: 'ok'}; $scope.main.session = "ok"; $location.path('/'); },function (res){ $scope.login = {status: 'ko'} ; }); }; this.sendUser = function() { if (!this.newuser || !this.newuser.first_name || !this.newuser.last_name || !this.newuser.email || !this.newuser.password || !this.newuser.confirm_password) { $scope.SignUpEmpty = {status: 'ko'}; return; } else{ $scope.SignUpEmpty = {status: 'ok'}; } if(this.newuser.password != this.newuser.confirm_password) { $scope.SignUpPassword = {status: 'ko'}; return; } else { $scope.SignUpPassword = {status: 'ok'}; } var hashedPassword = md5.createHash(this.newuser.confirm_password); this.newuser.confirm_password = hashedPassword; var hashedPassword = md5.createHash(this.newuser.password); this.newuser.password = hashedPassword; this.newuser.admin = 0; $http.post('/signup', this.newuser) .then(function (res) { $scope.main.user = res.data; this.newuser = {}; $scope.login = {status: 'ok'} ; $scope.main.session = "ok"; $location.path('/') }); }; $http.post('/api/me') .then(function (res) { if (res.data._id) { _this.user = res.data $scope.main.session = "ok" } }); }).controller('DataController', function($scope, $http, $location) { var _this = this this.getData =function(){ if($scope.main.user == undefined) { }else { $http.get('/api/Data',$scope.main.user) .then(function (res) { console.log(res.data); _this.datas = res.data; }); } }; this.getData(); this.sendData = function(img){ this.data = {}; var date = new Date(); this.data.created = date; this.data.idUser = $scope.main.user._id; this.data.images = img; $http.post('/api/sendData', this.data) $location.path('/users/data') } this.sendSettings = function(){ if(!this.settings.nbr_img){ this.settings.nbr_img = 1; } if(!this.settings.length_ramp){ this.settings.length_ramp = 100; } if(!this.settings.position_ramp){ this.settings.position_ramp = 0; } if(!this.settings.nbrPix){ this.settings.nbrPix = 2049; } if(!this.settings.decimation){ this.settings.decimation = 1; } $http.post('/api/sendSettings', this.settings); $http.put('/api/SetNbrImg', this.settings); $http.get('/api/receive').then(function(res){ $scope.data.sendData(res.data) }) } });
benchoufi/PRJ-medtec_sigproc
echopen-leaderboard/SignalProcessingEmulator/echopen/client/js/MainController.js
JavaScript
mit
4,086
/* global EmberDev */ import Controller from '../../controllers/controller'; import Service from '../../system/service'; import { Mixin, get } from 'ember-metal'; import EmberObject from '../../system/object'; import inject from '../../inject'; import { buildOwner } from 'internal-test-helpers'; QUnit.module('Controller event handling'); QUnit.test('can access `actions` hash via `_actions` [DEPRECATED]', function() { expect(2); let controller = Controller.extend({ actions: { foo: function() { ok(true, 'called foo action'); } } }).create(); expectDeprecation(function() { controller._actions.foo(); }, 'Usage of `_actions` is deprecated, use `actions` instead.'); }); QUnit.test('Action can be handled by a function on actions object', function() { expect(1); let TestController = Controller.extend({ actions: { poke() { ok(true, 'poked'); } } }); let controller = TestController.create(); controller.send('poke'); }); QUnit.test('A handled action can be bubbled to the target for continued processing', function() { expect(2); let TestController = Controller.extend({ actions: { poke() { ok(true, 'poked 1'); return true; } } }); let controller = TestController.create({ target: Controller.extend({ actions: { poke() { ok(true, 'poked 2'); } } }).create() }); controller.send('poke'); }); QUnit.test('Action can be handled by a superclass\' actions object', function() { expect(4); let SuperController = Controller.extend({ actions: { foo() { ok(true, 'foo'); }, bar(msg) { equal(msg, 'HELLO'); } } }); let BarControllerMixin = Mixin.create({ actions: { bar(msg) { equal(msg, 'HELLO'); this._super(msg); } } }); let IndexController = SuperController.extend(BarControllerMixin, { actions: { baz() { ok(true, 'baz'); } } }); let controller = IndexController.create({}); controller.send('foo'); controller.send('bar', 'HELLO'); controller.send('baz'); }); QUnit.module('Controller deprecations'); QUnit.module('Controller Content -> Model Alias'); QUnit.test('`model` is aliased as `content`', function() { expect(1); let controller = Controller.extend({ model: 'foo-bar' }).create(); equal(controller.get('content'), 'foo-bar', 'content is an alias of model'); }); QUnit.test('`content` is moved to `model` when `model` is unset', function() { expect(2); let controller; ignoreDeprecation(function() { controller = Controller.extend({ content: 'foo-bar' }).create(); }); equal(controller.get('model'), 'foo-bar', 'model is set properly'); equal(controller.get('content'), 'foo-bar', 'content is set properly'); }); QUnit.test('specifying `content` (without `model` specified) results in deprecation', function() { expect(1); expectDeprecation(function() { Controller.extend({ content: 'foo-bar' }).create(); }, 'Do not specify `content` on a Controller, use `model` instead.'); }); QUnit.test('specifying `content` (with `model` specified) does not result in deprecation', function() { expect(3); expectNoDeprecation(); let controller = Controller.extend({ content: 'foo-bar', model: 'blammo' }).create(); equal(get(controller, 'content'), 'foo-bar'); equal(get(controller, 'model'), 'blammo'); }); QUnit.module('Controller injected properties'); if (!EmberDev.runningProdBuild) { QUnit.test('defining a controller on a non-controller should fail assertion', function() { expectAssertion(function() { let owner = buildOwner(); let AnObject = EmberObject.extend({ foo: inject.controller('bar') }); owner.register('controller:bar', EmberObject.extend()); owner.register('foo:main', AnObject); owner.lookup('foo:main'); }, /Defining an injected controller property on a non-controller is not allowed./); }); } QUnit.test('controllers can be injected into controllers', function() { let owner = buildOwner(); owner.register('controller:post', Controller.extend({ postsController: inject.controller('posts') })); owner.register('controller:posts', Controller.extend()); let postController = owner.lookup('controller:post'); let postsController = owner.lookup('controller:posts'); equal(postsController, postController.get('postsController'), 'controller.posts is injected'); }); QUnit.test('services can be injected into controllers', function() { let owner = buildOwner(); owner.register('controller:application', Controller.extend({ authService: inject.service('auth') })); owner.register('service:auth', Service.extend()); let appController = owner.lookup('controller:application'); let authService = owner.lookup('service:auth'); equal(authService, appController.get('authService'), 'service.auth is injected'); });
bantic/ember.js
packages/ember-runtime/tests/controllers/controller_test.js
JavaScript
mit
5,037
module.exports={title:"The Mighty",slug:"themighty",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>The Mighty</title><path d="'+this.path+'"/></svg>'},path:"M19.178.001h-4.432L12.05 13.988 9.309.001H4.856c.216.219.334.634.39 1.072v21.21c0 .621-.105 1.383-.425 1.717 1.014-.214 2.307-.416 3.414-.611V9.375l2.489 12.375c.07.46.135 1.084-.021 1.198.847-.129 1.694-.252 2.544-.366-.105-.16-.064-.652-.005-1.061L15.696 9.15v13.095c1.054-.123 2.366-.24 3.47-.349l.012-.008c-.324-.328-.43-1.1-.43-1.724V1.726c0-.627.105-1.396.43-1.726v.001z",source:"https://themighty.com/",hex:"D0072A",guidelines:void 0,license:void 0};
cdnjs/cdnjs
ajax/libs/simple-icons/5.24.0/themighty.min.js
JavaScript
mit
662
if (!dojo._hasResource["openils.widget.HoldingCode"]) { dojo.provide("openils.widget.HoldingCode"); dojo.require("dijit.layout.ContentPane"); dojo.require("dijit.form.DropDownButton"); dojo.require("dijit.form.TextBox"); dojo.requireLocalization('openils.serial', 'serial'); /* XXX These variables and functions preceding the call to dojo.declar() * all pollute the window namespace. They're not written as methods for * the openils.widget.HoldingCode "class," but they should probably move * into there anyway. */ var _localeStrings = dojo.i18n.getLocalization('openils.serial', 'serial'); var _needed_fields = "abcdefghijklm"; var _season_store = new dojo.data.ItemFileReadStore({ "data": { "identifier": "code", "label": "label", "items": [ {"code": 21, "label": _localeStrings.SEASON_SPRING}, {"code": 22, "label": _localeStrings.SEASON_SUMMER}, {"code": 23, "label": _localeStrings.SEASON_FALL}, {"code": 24, "label": _localeStrings.SEASON_WINTER} ] } }); /* XXX i18n the above seasons. Also maybe don't hardcode MFHD seasons here? */ function _prepare_ttip_dialog(div, wizard) { dojo.empty(div); var selector = wizard.args.scap_selector; var caption_and_pattern = new scap().fromStoreItem(selector.item); /* we're going to look for subfields a-h and i-m now. There may already * be JS libs available to make this easier, but for now I'm doing this * the fastest way I know. */ var pattern_code; try { pattern_code = JSON2js(caption_and_pattern.pattern_code()); } catch (E) { /* no-op */; } if (!dojo.isArray(pattern_code)) { div.innerHTML = _localeStrings.SELECT_VALID_CAP; return; } var fields = []; for (var i = 0; i < pattern_code.length; i += 2) { var subfield = pattern_code[i]; var value = pattern_code[i + 1]; if (_needed_fields.indexOf(subfield) != -1) fields.push({"subfield": subfield, "caption": value, "pattern_value": value}); } if (!fields.length) { div.innerHTML = _localeStrings.NO_CAP_SUBFIELDS; return; } _prepare_ttip_dialog_fields(div, fields, wizard); } function _generate_dijit_for_field(field, tr) { dojo.create("td", {"innerHTML": field.caption}, tr); /* Any more special cases than this and we should switch to a dispatch * table or something. */ var input; if (field.pattern_value.match(/season/)) { input = new dijit.form.FilteringSelect( { "name": field.subfield, "store": _season_store, "searchAttr": "label", "scrollOnFocus": false }, dojo.create("td", null, tr) ); } else { input = new dijit.form.TextBox( {"name": field.subfield, "scrollOnFocus": false}, dojo.create("td", null, tr) ); } input.startup(); return input; } function _prepare_ttip_dialog_fields(div, fields, wizard) { /* XXX TODO Don't assume these defaults for the indicators and $8, and * provide reasonable control over them. */ var holding_code = ["4", "1", "8", "1"]; var inputs = []; wizard.wizard_button.attr("disabled", true); var table = dojo.create("table", {"className": "serial-holding-code"}); fields.forEach( function(field) { var tr = dojo.create("tr", null, table); field.caption = field.caption.replace(/^\(?([^\)]+)\)?$/, "$1"); if (field.subfield > "h") { field.caption = field.caption.slice(0,1).toUpperCase() + field.caption.slice(1); } var input = _generate_dijit_for_field(field, tr); wizard.preset_input_by_date(input, field.caption.toLowerCase()); inputs.push({"subfield": field.subfield, "input": input}); } ); new dijit.form.Button( { "label": _localeStrings.COMPILE, "onClick": function() { inputs.forEach( function(input) { var value = input.input.attr("value"); if (value === null || value === "") { alert(_localeStrings.ERROR_BLANK_FIELDS); } holding_code.push(input.subfield); holding_code.push(value); } ); wizard.code_text_box.attr("value", js2JSON(holding_code)); wizard.wizard_button.attr("disabled", false); dojo.empty(div); }, "scrollOnFocus": false }, dojo.create( "span", null, dojo.create( "td", {"colspan": 2}, dojo.create("tr", null, table) ) ) ); dojo.place(table, div, "only"); } /* Approximate a season value given a date using the same logic as * OpenILS::Utils::MFHD::Holding::chron_to_date(). */ function _loose_season(D) { var m = D.getMonth() + 1; var d = D.getDate(); if ( (m == 1 || m == 2) || (m == 12 && d >= 21) || (m == 3 && d < 20) ) { return 24; /* MFHD winter */ } else if ( (m == 4 || m == 5) || (m == 3 && d >= 20) || (m == 6 && d < 21) ) { return 21; /* spring */ } else if ( (m == 7 || m == 8) || (m == 6 && d >= 21) || (m == 9 && d < 22) ) { return 22; /* summer */ } else { return 23; /* autumn */ } } dojo.declare( "openils.widget.HoldingCode", dijit.layout.ContentPane, { "constructor": function(args) { this.args = args || {}; }, "startup": function() { var self = this; this.inherited(arguments); var dialog_div = dojo.create( "div", { "style": "padding:1em;margin:0;text-align:center;" }, this.domNode ); var target_div = dojo.create("div", null, this.domNode); dojo.create("br", null, this.domNode); this.wizard_button = new dijit.form.Button( { "label": _localeStrings.WIZARD, "onClick": function() { _prepare_ttip_dialog(target_div, self); } }, dojo.create("span", null, dialog_div) ); this.code_text_box = new dijit.form.ValidationTextBox( {}, dojo.create("div", null, this.domNode) ); /* This by no means will fully validate plausible holding codes, * but it will perhaps help users who experiment with typing * the holding code in here freehand (a little). */ this.code_text_box.validator = function(value) { try { return dojo.isArray(dojo.fromJson(value)); } catch(E) { return false; } }; this.code_text_box.startup(); }, "attr": function(name, value) { if (name == "value") { /* XXX can this get called before any subdijits are * built (before startup() is run)? */ if (value) { this.code_text_box.attr(name, value); } return this.code_text_box.attr(name); } else { return this.inherited(arguments); } }, "update_scap_selector": function(selector) { this.args.scap_selector = selector; this.attr("value", ""); }, "preset_input_by_date": function(input, chron_part) { try { input.attr("value", { /* NOTE: week is specifically not covered. I'm * not sure there's an acceptably standard way * to number the weeks in a year. Do we count * from the week of January 1? Or the first week * with a day of the week matching our example * date? Do weeks run Mon-Sun or Sun-Sat? */ "year": function(d) { return d.getFullYear(); }, "season": function(d) { return _loose_season(d); }, "month": function(d) { return d.getMonth() + 1; }, "day": function(d) { return d.getDate(); }, "hour": function(d) { return d.getHours(); }, }[chron_part](this.date_widget.attr("value")) ); } catch (E) { ; /* Oh well; can't win them all. */ } }, "date_widget": null } ); }
kidaa/Evergreen
Open-ILS/web/js/dojo/openils/widget/HoldingCode.js
JavaScript
gpl-2.0
9,850
(function() { /* Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.add( 'wpfilebase', { requires: [ 'iframedialog' ], init : function( editor ) { var me = this; CKEDITOR.dialog.add( 'WPFilebaseDialog', function (){ var postId = '',idEl = document.getElementById("post_ID"); if(idEl) postId = idEl.getAttribute('value'); return { title : 'WP-Filebase', minWidth : 680, minHeight : 400, contents : [ { id : 'iframe', label : 'WP-Filebase', expand : true, elements : [ { type : 'html', id : 'pageWPFilebase', label : 'WP-Filebase', style : 'width:680px; height:400px;', html : '<iframe src="'+me.path+'../../editor_plugin.php?post_id='+postId+'" frameborder="0" name="iframeWPFilebase" id="iframeWPFilebase" allowtransparency="1" style="width:100%;height:400px;margin:0;padding:0;"></iframe>' } ] } ] /*, onOk : function() { var editor = this.getParentEditor(), ratingcode = document.getElementById('iframeWPFilebase').contentWindow.insertWPFilebaseCode(); editor.insertHtml(ratingcode[0]); }*/ }; }); // Register the toolbar buttons. editor.ui.addButton( 'WPFilebase', { label : 'WP-Filebase', icon: this.path + 'images/btn.gif', command : 'wpfb-dialog' }); // Register the commands. editor.addCommand( 'wpfb-dialog', new CKEDITOR.dialogCommand( 'WPFilebaseDialog' )); } }); })();
3dot14/intranet-riobz
wp-content/plugins/wp-filebase/extras/ckeditor/plugin.js
JavaScript
gpl-2.0
1,692
/** * */ //<feature charts> Ext.define("Kitchensink.view.sprite.Column3D", { alias: 'sprite.columnSeries3d', extend: 'Ext.chart.series.sprite.Bar', inheritableStatics: { def: { defaults: { transformFillStroke: true } } }, lastClip: null, drawBar: function (ctx, surface, clip, left, top, right, bottom, itemId) { var me = this, attr = me.attr, center = (left + right) / 2, barWidth = (right - left) * 0.33333, depthWidth = barWidth * 0.5, color = Ext.draw.Color.create(attr.fillStyle), darkerColor = color.createDarker(0.05), lighterColor = color.createLighter(0.25); ctx.beginPath(); ctx.moveTo(center - barWidth, top); ctx.lineTo(center - barWidth + depthWidth, top + depthWidth); ctx.lineTo(center + barWidth + depthWidth, top + depthWidth); ctx.lineTo(center + barWidth, top); ctx.lineTo(center - barWidth, top); ctx.fillStyle = lighterColor.toString(); ctx.fillStroke(attr); ctx.beginPath(); ctx.moveTo(center + barWidth, top); ctx.lineTo(center + barWidth + depthWidth, top + depthWidth); ctx.lineTo(center + barWidth + depthWidth, bottom + depthWidth); ctx.lineTo(center + barWidth, bottom); ctx.lineTo(center + barWidth, top); ctx.fillStyle = darkerColor.toString(); ctx.fillStroke(attr); ctx.beginPath(); ctx.moveTo(center - barWidth, bottom); ctx.lineTo(center - barWidth, top); ctx.lineTo(center + barWidth, top); ctx.lineTo(center + barWidth, bottom); ctx.lineTo(center - barWidth, bottom); ctx.fillStyle = darkerColor.toString(); if (!(surface instanceof Ext.draw.engine.Svg)) { if (!this.lastClip || this.lastClip[0] !== Math.round(clip[1]) || this.lastClip[1] !== Math.round(clip[3])) { this.lastClip = [Math.round(clip[1]), Math.round(clip[3])]; this.grad = ctx.createLinearGradient(0, clip[1], 0, clip[3]); this.grad.addColorStop(0, lighterColor.toString()); this.grad.addColorStop(1, darkerColor.toString()); } ctx.fillStyle = this.grad; } else { ctx.fillStyle = color.toString(); } ctx.fillStroke(attr); } }); //</feature>
gaiaehr/gaiaehr
lib/sencha-touch-2.1.0-gpl/examples/kitchensink/app/view/sprite/Column3D.js
JavaScript
gpl-3.0
2,452
odoo.define('website.s_tabs_options', function (require) { 'use strict'; const options = require('web_editor.snippets.options'); options.registry.NavTabs = options.Class.extend({ isTopOption: true, /** * @override */ start: function () { this._findLinksAndPanes(); return this._super.apply(this, arguments); }, /** * @override */ onBuilt: function () { this._generateUniqueIDs(); }, /** * @override */ onClone: function () { this._generateUniqueIDs(); }, //-------------------------------------------------------------------------- // Options //-------------------------------------------------------------------------- /** * Creates a new tab and tab-pane. * * @see this.selectClass for parameters */ addTab: function (previewMode, widgetValue, params) { var $activeItem = this.$navLinks.filter('.active').parent(); var $activePane = this.$tabPanes.filter('.active'); var $navItem = $activeItem.clone(); var $navLink = $navItem.find('.nav-link').removeClass('active show'); var $tabPane = $activePane.clone().removeClass('active show'); $navItem.insertAfter($activeItem); $tabPane.insertAfter($activePane); this._findLinksAndPanes(); this._generateUniqueIDs(); $navLink.tab('show'); }, /** * Removes the current active tab and its content. * * @see this.selectClass for parameters */ removeTab: function (previewMode, widgetValue, params) { var self = this; var $activeLink = this.$navLinks.filter('.active'); var $activePane = this.$tabPanes.filter('.active'); var $next = this.$navLinks.eq((this.$navLinks.index($activeLink) + 1) % this.$navLinks.length); return new Promise(resolve => { $next.one('shown.bs.tab', function () { $activeLink.parent().remove(); $activePane.remove(); self._findLinksAndPanes(); resolve(); }); $next.tab('show'); }); }, //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- /** * @override */ _computeWidgetVisibility: async function (widgetName, params) { if (widgetName === 'remove_tab_opt') { return (this.$tabPanes.length > 2); } return this._super(...arguments); }, /** * @private */ _findLinksAndPanes: function () { this.$navLinks = this.$target.find('.nav:first .nav-link'); this.$tabPanes = this.$target.find('.tab-content:first .tab-pane'); }, /** * @private */ _generateUniqueIDs: function () { for (var i = 0; i < this.$navLinks.length; i++) { var id = _.now() + '_' + _.uniqueId(); var idLink = 'nav_tabs_link_' + id; var idContent = 'nav_tabs_content_' + id; this.$navLinks.eq(i).attr({ 'id': idLink, 'href': '#' + idContent, 'aria-controls': idContent, }); this.$tabPanes.eq(i).attr({ 'id': idContent, 'aria-labelledby': idLink, }); } }, }); options.registry.NavTabsStyle = options.Class.extend({ //-------------------------------------------------------------------------- // Options //-------------------------------------------------------------------------- /** * Set the style of the tabs. * * @see this.selectClass for parameters */ setStyle: function (previewMode, widgetValue, params) { const $nav = this.$target.find('.s_tabs_nav:first .nav'); const isPills = widgetValue === 'pills'; $nav.toggleClass('nav-tabs card-header-tabs', !isPills); $nav.toggleClass('nav-pills', isPills); this.$target.find('.s_tabs_nav:first').toggleClass('card-header', !isPills).toggleClass('mb-3', isPills); this.$target.toggleClass('card', !isPills); this.$target.find('.s_tabs_content:first').toggleClass('card-body', !isPills); }, /** * Horizontal/vertical nav. * * @see this.selectClass for parameters */ setDirection: function (previewMode, widgetValue, params) { const isVertical = widgetValue === 'vertical'; this.$target.toggleClass('row s_col_no_resize s_col_no_bgcolor', isVertical); this.$target.find('.s_tabs_nav:first .nav').toggleClass('flex-column', isVertical); this.$target.find('.s_tabs_nav:first > .nav-link').toggleClass('py-2', isVertical); this.$target.find('.s_tabs_nav:first').toggleClass('col-md-3', isVertical); this.$target.find('.s_tabs_content:first').toggleClass('col-md-9', isVertical); }, //-------------------------------------------------------------------------- // Private //-------------------------------------------------------------------------- /** * @override */ _computeWidgetState: function (methodName, params) { switch (methodName) { case 'setStyle': return this.$target.find('.s_tabs_nav:first .nav').hasClass('nav-pills') ? 'pills' : 'tabs'; case 'setDirection': return this.$target.find('.s_tabs_nav:first .nav').hasClass('flex-column') ? 'vertical' : 'horizontal'; } return this._super(...arguments); }, }); });
ygol/odoo
addons/website/static/src/snippets/s_tabs/options.js
JavaScript
agpl-3.0
5,635
/* Component: ui.customization */ $.extend(UI, { loadCustomization: function() { if ($.cookie('user_customization')) { this.custom = $.parseJSON($.cookie('user_customization')); } else { this.custom = { "extended_concordance": false, "extended_tagmode": false }; this.saveCustomization(); } //Tag Projection: the tag-mode is always extended if (this.enableTagProjection) { // Disable Tag Crunched Mode this.custom.extended_tagmode = true; } }, saveCustomization: function() { $.cookie('user_customization', JSON.stringify(this.custom), { expires: 3650 }); }, setShortcuts: function() { if($('#settings-shortcuts .list').length) return; $('#settings-shortcuts #default-shortcuts').before('<table class="list"></table>'); $.each(this.shortcuts, function() { $('#settings-shortcuts .list').append('<tr><td class="label">' + this.label + '</td><td class="combination"><span contenteditable="true" class="keystroke">' + ((UI.isMac) ? ((typeof this.keystrokes.mac == 'undefined')? UI.viewShortcutSymbols(this.keystrokes.standard) : UI.viewShortcutSymbols(this.keystrokes.mac)) : UI.viewShortcutSymbols(this.keystrokes.standard)) + '</span></td></tr>'); }); }, viewShortcutSymbols: function(txt) { txt = txt.replace(/meta/gi, '&#8984').replace(/return/gi, '&#8629').replace(/alt/gi, '&#8997').replace(/shift/gi, '&#8679').replace(/up/gi, '&#8593').replace(/down/gi, '&#8595').replace(/left/gi, '&#8592').replace(/right/gi, '&#8594'); return txt; }, writeNewShortcut: function(c, s, k) { $(k).html(s.html().substring(0, s.html().length - 1)).removeClass('changing').addClass('modified').blur(); $(s).remove(); $('.msg', c).remove(); $('#settings-shortcuts.modifying').removeClass('modifying'); $('.popup-settings .submenu li[data-tab="settings-shortcuts"]').addClass('modified'); $('.popup-settings').addClass('modified'); } });
Mind2mind/MateCat
public/js/cat_source/ui.customization.js
JavaScript
lgpl-3.0
1,916
/* * Copyright 2019 ThoughtWorks, 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. */ describe("BuildSummaryObserverSpec", function BuildSummaryObserverSpec() { var orig_write_attribute = Element.writeAttribute; var contextPath = "/dashboard"; var observer; beforeEach(function () { setFixtures("<div id=\"container\" class=\"build_detail\">\n" + " <span class=\"page_panel\"><b class=\"rtop\"><b class=\"r1\"></b> <b class=\"r2\"></b> <b class=\"r3\"></b> <b class=\"r4\"></b></b></span>\n" + "\n" + "<div id=\"build_status\" class=\"build-status\"></div>\n" + "<div class=\"build_detail_summary\">\n" + " <ul class=\"summary\">\n" + " <li><strong>Building since:</strong> $buildSince</li>\n" + " <li><strong>Elapsed time:</strong> <span id=\"${projectName}_time_elapsed\"><img\n" + " src=\"images/spinner.gif\"/></span></li>\n" + " <li><strong>Previous successful build:</strong> $durationToSuccessfulBuild</li>\n" + " <li><strong>Remaining time:</strong> <span id=\"${projectName}_time_remaining\"><img\n" + " src=\"images/spinner.gif\"/></span></li>\n" + " <span id=\"build_status\"></span>\n" + " </ul>\n" + "</div>\n" + "<span class=\"page_panel\"><b class=\"rbottom\"><b class=\"r4\"></b> <b class=\"r3\"></b> <b class=\"r2\"></b> <b\n" + " class=\"r1\"></b></b></span>\n" + "</div>\n" + "\n" + "<span class=\"buildoutput_pre\"></span>\n" + "\n" + "<div id=\"trans_content\"></div>"); Element.addMethods({writeAttribute: orig_write_attribute}); jQuery('.buildoutput_pre').html(''); observer = new BuildSummaryObserver(jQuery(".build_detail_summary")); jQuery('#container').addClass("building_passed"); jQuery('#trans_content').html(''); TransMessage.prototype.initialize = Prototype.emptyFunction; }); it("test_ajax_periodical_refresh_active_build_should_update_css", function () { var status = jQuery(".build-status").addClass("building_passed"); var json = failed_json('project1') observer.updateBuildResult(json); assertTrue(status.hasClass("failed")); }); it("test_should_invoke_word_break_to_break_text", function () { $$WordBreaker.break_text = function () { return "split text"; }; observer.displayAnyErrorMessages(inactive_json("project1")); assertTrue(jQuery('#trans_content').text().indexOf("split text") > -1); }); });
naveenbhaskar/gocd
server/webapp/WEB-INF/rails/spec/javascripts/build_summary_observer_spec.js
JavaScript
apache-2.0
3,264
define(['template'], function (template) { function anonymous($data,$filename /**/) { 'use strict'; $data=$data||{}; var $utils=template.utils,$helpers=$utils.$helpers,$escape=$utils.$escape,id=$data.id,$out='';$out+='<div class="comp-box di-o_o-line">\n <div data-o_o-di="'; $out+=$escape(id); $out+='">\n </div>\n</div>'; return $out; } return { render: anonymous }; });
qqming113/bi-platform
designer/src/main/resources/public/silkroad/src/report/component-box/components/ecui-input-tree-vm-template.js
JavaScript
apache-2.0
451
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("babylonjs")); else if(typeof define === 'function' && define.amd) define("babylonjs-serializers", ["babylonjs"], factory); else if(typeof exports === 'object') exports["babylonjs-serializers"] = factory(require("babylonjs")); else root["SERIALIZERS"] = factory(root["BABYLON"]); })((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function(__WEBPACK_EXTERNAL_MODULE_babylonjs_Maths_math__) { return /******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./legacy/legacy-objSerializer.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "../../node_modules/webpack/buildin/global.js": /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ "./OBJ/index.ts": /*!**********************!*\ !*** ./OBJ/index.ts ***! \**********************/ /*! exports provided: OBJExport */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _objSerializer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./objSerializer */ "./OBJ/objSerializer.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return _objSerializer__WEBPACK_IMPORTED_MODULE_0__["OBJExport"]; }); /***/ }), /***/ "./OBJ/objSerializer.ts": /*!******************************!*\ !*** ./OBJ/objSerializer.ts ***! \******************************/ /*! exports provided: OBJExport */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return OBJExport; }); /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Maths/math"); /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__); /** * Class for generating OBJ data from a Babylon scene. */ var OBJExport = /** @class */ (function () { function OBJExport() { } /** * Exports the geometry of a Mesh array in .OBJ file format (text) * @param mesh defines the list of meshes to serialize * @param materials defines if materials should be exported * @param matlibname defines the name of the associated mtl file * @param globalposition defines if the exported positions are globals or local to the exported mesh * @returns the OBJ content */ OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) { var output = []; var v = 1; if (materials) { if (!matlibname) { matlibname = 'mat'; } output.push("mtllib " + matlibname + ".mtl"); } for (var j = 0; j < mesh.length; j++) { output.push("g object" + j); output.push("o object_" + j); //Uses the position of the item in the scene, to the file (this back to normal in the end) var lastMatrix = null; if (globalposition) { var newMatrix = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z); lastMatrix = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z)); mesh[j].bakeTransformIntoVertices(newMatrix); } //TODO: submeshes (groups) //TODO: smoothing groups (s 1, s off); if (materials) { var mat = mesh[j].material; if (mat) { output.push("usemtl " + mat.id); } } var g = mesh[j].geometry; if (!g) { babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("No geometry is present on the mesh"); continue; } var trunkVerts = g.getVerticesData('position'); var trunkNormals = g.getVerticesData('normal'); var trunkUV = g.getVerticesData('uv'); var trunkFaces = g.getIndices(); var curV = 0; if (!trunkVerts || !trunkFaces) { babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("There are no position vertices or indices on the mesh!"); continue; } for (var i = 0; i < trunkVerts.length; i += 3) { output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]); curV++; } if (trunkNormals != null) { for (i = 0; i < trunkNormals.length; i += 3) { output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]); } } if (trunkUV != null) { for (i = 0; i < trunkUV.length; i += 2) { output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]); } } for (i = 0; i < trunkFaces.length; i += 3) { var indices = [String(trunkFaces[i + 2] + v), String(trunkFaces[i + 1] + v), String(trunkFaces[i] + v)]; var blanks = ["", "", ""]; var facePositions = indices; var faceUVs = trunkUV != null ? indices : blanks; var faceNormals = trunkNormals != null ? indices : blanks; output.push("f " + facePositions[0] + "/" + faceUVs[0] + "/" + faceNormals[0] + " " + facePositions[1] + "/" + faceUVs[1] + "/" + faceNormals[1] + " " + facePositions[2] + "/" + faceUVs[2] + "/" + faceNormals[2]); } //back de previous matrix, to not change the original mesh in the scene if (globalposition && lastMatrix) { mesh[j].bakeTransformIntoVertices(lastMatrix); } v += curV; } var text = output.join("\n"); return (text); }; /** * Exports the material(s) of a mesh in .MTL file format (text) * @param mesh defines the mesh to extract the material from * @returns the mtl content */ //TODO: Export the materials of mesh array OBJExport.MTL = function (mesh) { var output = []; var m = mesh.material; output.push("newmtl mat1"); output.push(" Ns " + m.specularPower.toFixed(4)); output.push(" Ni 1.5000"); output.push(" d " + m.alpha.toFixed(4)); output.push(" Tr 0.0000"); output.push(" Tf 1.0000 1.0000 1.0000"); output.push(" illum 2"); output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4)); output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4)); output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4)); output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4)); //TODO: uv scale, offset, wrap //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures? var uvscale = ""; if (m.ambientTexture) { output.push(" map_Ka " + uvscale + m.ambientTexture.name); } if (m.diffuseTexture) { output.push(" map_Kd " + uvscale + m.diffuseTexture.name); //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d) } if (m.specularTexture) { output.push(" map_Ks " + uvscale + m.specularTexture.name); /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???) if (m.useGlossinessFromSpecularMapAlpha) { output.push(" map_Ns "+uvscale + m.specularTexture.name); } */ } /* TODO: emissive texture not in .MAT format (???) if (m.emissiveTexture) { output.push(" map_d "+uvscale+m.emissiveTexture.name); } */ if (m.bumpTexture) { output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name); } if (m.opacityTexture) { output.push(" map_d " + uvscale + m.opacityTexture.name); } var text = output.join("\n"); return (text); }; return OBJExport; }()); /***/ }), /***/ "./legacy/legacy-objSerializer.ts": /*!****************************************!*\ !*** ./legacy/legacy-objSerializer.ts ***! \****************************************/ /*! exports provided: OBJExport */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _OBJ__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OBJ */ "./OBJ/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["OBJExport"]; }); /** * This is the entry point for the UMD module. * The entry point for a future ESM package should be index.ts */ var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined); if (typeof globalObject !== "undefined") { for (var serializer in _OBJ__WEBPACK_IMPORTED_MODULE_0__) { globalObject.BABYLON[serializer] = _OBJ__WEBPACK_IMPORTED_MODULE_0__[serializer]; } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "babylonjs/Maths/math": /*!****************************************************************************************************!*\ !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***! \****************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Maths_math__; /***/ }) /******/ }); }); //# sourceMappingURL=babylon.objSerializer.js.map
BabylonJS/Babylon.js
dist/previous releases/4.0/serializers/babylon.objSerializer.js
JavaScript
apache-2.0
15,040
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * String.prototype.split(separator, limit): * i) can be transferred to other kinds of objects for use as a method. * separator and limit can be any kinds of object since: * ii) if separator is not RegExp ToString(separator) performs and * iii) ToInteger(limit) performs * * @path ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A1_T10.js * @description Arguments are objects, and instance is string. * First object have overrided toString function. * Second object have overrided valueOf function */ var __obj = {toString:function(){return "\u0042B";}} var __obj2 = {valueOf:function(){return true;}} var __str = "ABB\u0041BABAB"; with(__str){ __split = split(__obj, __obj2); } ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (typeof __split !== "object") { $ERROR('#1: var __obj = {toString:function(){return "u0042B";}}; var __obj2 = {valueOf:function(){return true;}}; var __str = "ABBu0041BABAB"; with(__str){__split = split(__obj, __obj2);}; typeof __split === "object". Actual: '+typeof __split ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (__split.constructor !== Array) { $ERROR('#2: var __obj = {toString:function(){return "u0042B";}}; var __obj2 = {valueOf:function(){return true;}}; var __str = "ABBu0041BABAB"; with(__str){__split = split(__obj, __obj2);}; __split.constructor === Array. Actual: '+__split.constructor ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if (__split.length !== 1) { $ERROR('#3: var __obj = {toString:function(){return "u0042B";}}; var __obj2 = {valueOf:function(){return true;}}; var __str = "ABBu0041BABAB"; with(__str){__split = split(__obj, __obj2);}; __split.length === 1. Actual: '+__split.length ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#4 if (__split[0] !== "A") { $ERROR('#4: var __obj = {toString:function(){return "u0042B";}}; var __obj2 = {valueOf:function(){return true;}}; var __str = "ABBu0041BABAB"; with(__str){__split = split(__obj, __obj2);}; __split[0] === "A". Actual: '+__split[0] ); } // //////////////////////////////////////////////////////////////////////////////
hippich/typescript
tests/Fidelity/test262/suite/ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A1_T10.js
JavaScript
apache-2.0
2,624
/**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * @memberOf cc * @function * @param {Number} a * @param {Number} b * @param {Number} c * @param {Number} d * @param {Number} tx * @param {Number} ty */ cc.AffineTransform = function (a, b, c, d, tx, ty) { this.a = a; this.b = b; this.c = c; this.d = d; this.tx = tx; this.ty = ty; }; /** * @memberOf cc * @function * @param {Number} a * @param {Number} b * @param {Number} c * @param {Number} d * @param {Number} tx * @param {Number} ty * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformMake = function (a, b, c, d, tx, ty) { return {a: a, b: b, c: c, d: d, tx: tx, ty: ty}; }; /** * @memberOf cc * @function * @param {cc.Point} point * @param {cc.AffineTransform} t * @return {cc.Point} * Constructor */ cc.PointApplyAffineTransform = function (point, t) { return {x: t.a * point.x + t.c * point.y + t.tx, y: t.b * point.x + t.d * point.y + t.ty}; }; cc._PointApplyAffineTransform = function (x, y, t) { return {x: t.a * x + t.c * y + t.tx, y: t.b * x + t.d * y + t.ty}; }; /** * @memberOf cc * @function * @param {cc.Size} size * @param {cc.AffineTransform} t * @return {cc.Size} * Constructor */ cc.SizeApplyAffineTransform = function (size, t) { return {width: t.a * size.width + t.c * size.height, height: t.b * size.width + t.d * size.height}; }; /** * @memberOf cc * @function * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformMakeIdentity = function () { return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0}; }; /** * @memberOf cc * @function * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformIdentity = function () { return {a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0}; }; /** * @memberOf cc * @function * @param {cc.Rect} rect * @param {cc.AffineTransform} anAffineTransform * @return {cc.Rect} * Constructor */ cc.RectApplyAffineTransform = function (rect, anAffineTransform) { var top = cc.rectGetMinY(rect); var left = cc.rectGetMinX(rect); var right = cc.rectGetMaxX(rect); var bottom = cc.rectGetMaxY(rect); var topLeft = cc._PointApplyAffineTransform(left, top, anAffineTransform); var topRight = cc._PointApplyAffineTransform(right, top, anAffineTransform); var bottomLeft = cc._PointApplyAffineTransform(left, bottom, anAffineTransform); var bottomRight = cc._PointApplyAffineTransform(right, bottom, anAffineTransform); var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); return cc.rect(minX, minY, (maxX - minX), (maxY - minY)); }; cc._RectApplyAffineTransformIn = function(rect, anAffineTransform){ var top = cc.rectGetMinY(rect); var left = cc.rectGetMinX(rect); var right = cc.rectGetMaxX(rect); var bottom = cc.rectGetMaxY(rect); var topLeft = cc._PointApplyAffineTransform(left, top, anAffineTransform); var topRight = cc._PointApplyAffineTransform(right, top, anAffineTransform); var bottomLeft = cc._PointApplyAffineTransform(left, bottom, anAffineTransform); var bottomRight = cc._PointApplyAffineTransform(right, bottom, anAffineTransform); var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); rect.x = minX; rect.y = minY; rect.width = maxX - minX; rect.height = maxY - minY; return rect; }; /** * @memberOf cc * @function * @param {cc.AffineTransform} t * @param {Number} tx * @param {Number}ty * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformTranslate = function (t, tx, ty) { return { a: t.a, b: t.b, c: t.c, d: t.d, tx: t.tx + t.a * tx + t.c * ty, ty: t.ty + t.b * tx + t.d * ty }; }; /** * @memberOf cc * @function * @param {cc.AffineTransform} t * @param {Number} sx * @param {Number} sy * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformScale = function (t, sx, sy) { return {a: t.a * sx, b: t.b * sx, c: t.c * sy, d: t.d * sy, tx: t.tx, ty: t.ty}; }; /** * @memberOf cc * @function * @param {cc.AffineTransform} aTransform * @param {Number} anAngle * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformRotate = function (aTransform, anAngle) { var fSin = Math.sin(anAngle); var fCos = Math.cos(anAngle); return {a: aTransform.a * fCos + aTransform.c * fSin, b: aTransform.b * fCos + aTransform.d * fSin, c: aTransform.c * fCos - aTransform.a * fSin, d: aTransform.d * fCos - aTransform.b * fSin, tx: aTransform.tx, ty: aTransform.ty}; }; /** * Concatenate `t2' to `t1' and return the result:<br/> * t' = t1 * t2 * @memberOf cc * @function * @param {cc.AffineTransform} t1 * @param {cc.AffineTransform} t2 * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformConcat = function (t1, t2) { return {a: t1.a * t2.a + t1.b * t2.c, //a b: t1.a * t2.b + t1.b * t2.d, //b c: t1.c * t2.a + t1.d * t2.c, //c d: t1.c * t2.b + t1.d * t2.d, //d tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx, //tx ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty}; //ty }; /** * Return true if `t1' and `t2' are equal, false otherwise. * @memberOf cc * @function * @param {cc.AffineTransform} t1 * @param {cc.AffineTransform} t2 * @return {Boolean} * Constructor */ cc.AffineTransformEqualToTransform = function (t1, t2) { return ((t1.a === t2.a) && (t1.b === t2.b) && (t1.c === t2.c) && (t1.d === t2.d) && (t1.tx === t2.tx) && (t1.ty === t2.ty)); }; /** * Get the invert value of an AffineTransform object * @memberOf cc * @function * @param {cc.AffineTransform} t * @return {cc.AffineTransform} * Constructor */ cc.AffineTransformInvert = function (t) { var determinant = 1 / (t.a * t.d - t.b * t.c); return {a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a, tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty)}; };
rasterbrain/box2d-radialgravity-cocos2djs
frameworks/cocos2d-html5/cocos2d/core/cocoa/CCAffineTransform.js
JavaScript
apache-2.0
7,956
// tryJSX var React = require("react"); var Hello = React.createClass({ render: function(){ return ( <div> Watch Webpack & React! </div> ) } }) React.render( <Hello />, document.body )
zhangxx0/jenkins
rxjava-keynote-master/example/webpack/tryJSX.js
JavaScript
apache-2.0
235
// Copyright 2011 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @path ch15/15.2/15.2.4/15.2.4.2/S15.2.4.2_A13.js * @description If the this value is null, return "[object Null]". */ if (Object.prototype.toString.call(null) !== "[object Null]") { $ERROR('If the this value is null, return "[object Null]".'); }
hippich/typescript
tests/Fidelity/test262/suite/ch15/15.2/15.2.4/15.2.4.2/S15.2.4.2_A13.js
JavaScript
apache-2.0
392
(function() { 'use strict'; angular.module('app.components') .directive('serviceBasicDetails', ServiceBasicDetailsDirective); /** @ngInject */ function ServiceBasicDetailsDirective() { var directive = { restrict: 'AE', scope: { service: '=' }, link: link, templateUrl: 'app/components/service-basic-details/service-basic-details.html', controller: ServiceBasicDetailsController, controllerAs: 'vm', bindToController: true }; return directive; function link(scope, element, attrs, vm, transclude) { vm.activate(); } /** @ngInject */ function ServiceBasicDetailsController() { var vm = this; vm.activate = activate; function activate() { } } } })();
sonejah21/api
src/client/app/components/service-basic-details/service-basic-details.directive.js
JavaScript
apache-2.0
787
// This file was procedurally generated from the following sources: // - src/async-generators/yield-star-getiter-sync-not-callable-boolean-throw.case // - src/async-generators/default/async-obj-method.template /*--- description: Throws a TypeError on a non-callable [Symbol.iterator] (boolean) (Async generator method) esid: prod-AsyncGeneratorMethod features: [Symbol.iterator, async-iteration] flags: [generated, async] info: | Async Generator Function Definitions AsyncGeneratorMethod : async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody } YieldExpression: yield * AssignmentExpression 1. Let exprRef be the result of evaluating AssignmentExpression. 2. Let value be ? GetValue(exprRef). 3. Let generatorKind be ! GetGeneratorKind(). 4. Let iterator be ? GetIterator(value, generatorKind). ... GetIterator ( obj [ , hint ] ) ... 3. If hint is async, a. Set method to ? GetMethod(obj, @@asyncIterator). b. If method is undefined, i. Let syncMethod be ? GetMethod(obj, @@iterator). ... GetMethod ( V, P ) ... 2. Let func be ? GetV(V, P). ... 4. If IsCallable(func) is false, throw a TypeError exception. ... ---*/ var obj = { [Symbol.iterator]: false }; var callCount = 0; var gen = { async *method() { callCount += 1; yield* obj; throw new Test262Error('abrupt completion closes iter'); } }.method; var iter = gen(); iter.next().then(() => { throw new Test262Error('Promise incorrectly fulfilled.'); }, v => { assert.sameValue(v.constructor, TypeError, "TypeError"); iter.next().then(({ done, value }) => { assert.sameValue(done, true, 'the iterator is completed'); assert.sameValue(value, undefined, 'value is undefined'); }).then($DONE, $DONE); }).catch($DONE); assert.sameValue(callCount, 1);
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/object/method-definition/async-gen-yield-star-getiter-sync-not-callable-boolean-throw.js
JavaScript
bsd-2-clause
1,892
/** * Yii validation module. * * This JavaScript module provides the validation methods for the built-in validators. * * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ * @author Qiang Xue <[email protected]> * @since 2.0 */ yii.validation = (function ($) { var isEmpty = function (value, trim) { return value === null || value === undefined || value == [] || value === '' || trim && $.trim(value) === ''; }; var addMessage = function (messages, message, value) { messages.push(message.replace(/\{value\}/g, value)); }; return { required: function (value, messages, options) { var valid = false; if (options.requiredValue === undefined) { if (options.strict && value !== undefined || !options.strict && !isEmpty(value, true)) { valid = true; } } else if (!options.strict && value == options.requiredValue || options.strict && value === options.requiredValue) { valid = true; } if (!valid) { addMessage(messages, options.message, value); } }, boolean: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } var valid = !options.strict && (value == options.trueValue || value == options.falseValue) || options.strict && (value === options.trueValue || value === options.falseValue); if (!valid) { addMessage(messages, options.message, value); } }, string: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } if (typeof value !== 'string') { addMessage(messages, options.message, value); return; } if (options.min !== undefined && value.length < options.min) { addMessage(messages, options.tooShort, value); } if (options.max !== undefined && value.length > options.max) { addMessage(messages, options.tooLong, value); } if (options.is !== undefined && value.length != options.is) { addMessage(messages, options.is, value); } }, number: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } if (typeof value === 'string' && !value.match(options.pattern)) { addMessage(messages, options.message, value); return; } if (options.min !== undefined && value < options.min) { addMessage(messages, options.tooSmall, value); } if (options.max !== undefined && value > options.max) { addMessage(messages, options.tooBig, value); } }, range: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } var valid = !options.not && $.inArray(value, options.range) > -1 || options.not && $.inArray(value, options.range) == -1; if (!valid) { addMessage(messages, options.message, value); } }, regularExpression: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } if (!options.not && !value.match(options.pattern) || options.not && value.match(options.pattern)) { addMessage(messages, options.message, value); } }, email: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } var valid = true; if (options.enableIDN) { var regexp = /^(.*<?)(.*)@(.*)(>?)$/, matches = regexp.exec(value); if (matches === null) { valid = false; } else { value = matches[1] + punycode.toASCII(matches[2]) + '@' + punycode.toASCII(matches[3]) + matches[4]; } } if (!valid || !(value.match(options.pattern) || (options.allowName && value.match(options.fullPattern)))) { addMessage(messages, options.message, value); } }, url: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } if (options.defaultScheme && !value.match(/:\/\//)) { value = options.defaultScheme + '://' + value; } var valid = true; if (options.enableIDN) { var regexp = /^([^:]+):\/\/([^\/]+)(.*)$/, matches = regexp.exec(value); if (matches === null) { valid = false; } else { value = matches[1] + '://' + punycode.toASCII(matches[2]) + matches[3]; } } if (!valid || !value.match(options.pattern)) { addMessage(messages, options.message, value); } }, captcha: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } // CAPTCHA may be updated via AJAX and the updated hash is stored in body data var hash = $('body').data(options.hashKey); if (hash == null) { hash = options.hash; } else { hash = hash[options.caseSensitive ? 0 : 1]; } var v = options.caseSensitive ? value : value.toLowerCase(); for (var i = v.length - 1, h = 0; i >= 0; --i) { h += v.charCodeAt(i); } if (h != hash) { addMessage(messages, options.message, value); } }, compare: function (value, messages, options) { if (options.skipOnEmpty && isEmpty(value)) { return; } var compareValue, valid = true; if (options.compareAttribute === undefined) { compareValue = options.compareValue; } else { compareValue = $('#' + options.compareAttribute).val(); } switch (options.operator) { case '==': valid = value == compareValue; break; case '===': valid = value === compareValue; break; case '!=': valid = value != compareValue; break; case '!==': valid = value !== compareValue; break; case '>': valid = value > compareValue; break; case '>=': valid = value >= compareValue; break; case '<': valid = value < compareValue; break; case '<=': valid = value <= compareValue; break; default: valid = false; break; } if (!valid) { addMessage(messages, options.message, value); } } }; })(jQuery);
seem-sky/FrameworkBenchmarks
php-yii2/app/vendor/yiisoft/yii2/assets/yii.validation.js
JavaScript
bsd-3-clause
5,938
// addCollapseToAllStackedInlines.js ( function(a) { a(document).ready(function() { //a("div.inline-group").wrapInner("<fieldset class=\"module aligned collapse\"></fieldset>"); a("div.inline-group").each(function(index) { var header = a(this).find('h2').get(0); if(header) { var headerTitle = a(header).find('.formset_title').get(0); var headerText = a(headerTitle).text(); if(headerText[0] == '_') { headerText = headerText.replace(/^_/, ""); a(headerTitle).text(headerText); a(this).wrapInner("<fieldset class=\"module aligned collapse\"></fieldset>"); } } }); return false; }) } )(django.jQuery);
JuliBakagianni/META-SHARE
metashare/static/metashare/js/addCollapseToAllStackedInlines.js
JavaScript
bsd-3-clause
714
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: 1. Evaluate Expression es5id: 12.13_A3_T3 description: Evaluating number expression ---*/ // CHECK#1 try{ throw 10+3; } catch(e){ if (e!==13) $ERROR('#1: Exception ===13(operaton +). Actual: Exception ==='+ e); } // CHECK#2 var b=10; var a=3; try{ throw a+b; } catch(e){ if (e!==13) $ERROR('#2: Exception ===13(operaton +). Actual: Exception ==='+ e); } // CHECK#3 try{ throw 3.15-1.02; } catch(e){ if (e!==2.13) $ERROR('#3: Exception ===2.13(operaton -). Actual: Exception ==='+ e); } // CHECK#4 try{ throw 2*2; } catch(e){ if (e!==4) $ERROR('#4: Exception ===4(operaton *). Actual: Exception ==='+ e); } // CHECK#5 try{ throw 1+Infinity; } catch(e){ if (e!==+Infinity) $ERROR('#5: Exception ===+Infinity(operaton +). Actual: Exception ==='+ e); } // CHECK#6 try{ throw 1-Infinity; } catch(e){ if (e!==-Infinity) $ERROR('#6: Exception ===-Infinity(operaton -). Actual: Exception ==='+ e); } // CHECK#7 try{ throw 10/5; } catch(e){ if (e!==2) $ERROR('#7: Exception ===2(operaton /). Actual: Exception ==='+ e); } // CHECK#8 try{ throw 8>>2; } catch(e){ if (e!==2) $ERROR('#8: Exception ===2(operaton >>). Actual: Exception ==='+ e); } // CHECK#9 try{ throw 2<<2; } catch(e){ if (e!==8) $ERROR('#9: Exception ===8(operaton <<). Actual: Exception ==='+ e); } // CHECK#10 try{ throw 123%100; } catch(e){ if (e!==23) $ERROR('#10: Exception ===23(operaton %). Actual: Exception ==='+ e); }
PiotrDabkowski/Js2Py
tests/test_cases/language/statements/throw/S12.13_A3_T3.js
JavaScript
mit
1,590
// The `dc.app.searcher` is the core controller for running document searches // from the client side. It's main "view" is the dc.ui.SearchBox. dc.controllers.Searcher = Backbone.Router.extend({ // Error messages to display when your search returns no results. NO_RESULTS : { project : _.t('not_found_project'), account : _.t('not_found_account'), group : _.t('not_found_group'), published : _.t('not_found_published'), annotated : _.t('not_found_annotated'), search : _.t('not_found_search'), all : _.t('not_found_all') }, PAGE_MATCHER : (/\/p(\d+)$/), DOCUMENTS_URL : '/search/documents.json', FACETS_URL : '/search/facets.json', fragment : null, flags : {}, routes : { 'search/*query/p:page': 'searchByHash', 'search/*query': 'searchByHash' }, // Creating a new SearchBox registers #search page fragments. initialize : function() { this.searchBox = dc.app.searchBox; this.flags.hasEntities = false; this.currentSearch = null; this.titleBox = $('.search_tab_content .title_box_inner'); _.bindAll(this, '_loadSearchResults', '_loadFacetsResults', '_loadFacetResults', 'loadDefault', 'loadFacets'); dc.app.navigation.bind('tab:search', this.loadDefault); }, urlFragment : function() { return this.fragment + (this.page ? '/p' + this.page : ''); }, // Load the default starting-point search. loadDefault : function(options) { options || (options = {}); if (options.clear) { Documents.reset(); this.searchBox.value(''); } if (this.currentSearch) return; if (!Documents.isEmpty()) { this.navigate(this.urlFragment()); this.showDocuments(); } else if (this.searchBox.value()) { this.search(this.searchBox.value()); } else if (dc.account && dc.account.get('hasDocuments')) { Accounts.current().openDocuments(); } else if (Projects.first()) { Projects.first().open(); } else if (options.showHelp && dc.account) { dc.app.navigation.open('help'); } else { this.search(''); } }, // Paginate forwards or backwards in the search results. loadPage : function(page, callback) { page = page || this.page || 1; var max = dc.app.paginator.pageCount(); if (page < 1) page = 1; if (page > max) page = max; this.search(this.searchBox.value(), page, callback); }, // Quote a string if necessary (contains whitespace). quote : function(string) { return string.match(/\s/) ? '"' + string + '"' : string; }, publicQuery : function() { // Swap out projects. var projects = []; var projectNames = dc.app.visualSearch.searchQuery.values('project'); _.each(projectNames, function(projectName) { projects.push(Projects.find(projectName)); }); var query = dc.app.visualSearch.searchQuery.withoutCategory('project'); if ( ! _.isEmpty(projects) ){ query = _.map(projects, function(p) { return 'projectid: ' + p.slug(); }).join(' ') + ' ' + query; } // Swap out documents for short ids. query = query.replace(/(document: \d+)-\S+/g, '$1'); return query; }, queryText : function() { return dc.app.visualSearch.searchQuery.find('text'); }, searchKeySubstitutions: function(){ if ( dc.app && dc.app.workspace ){ return this._searchKeys || ( this._searchKeys = _.invert( dc.app.workspace.searchKeySubstitutions ) ); } else { return {}; } }, searchValueSubstitutions: function(){ if ( this._searchValues ){ return this._searchValues; } if ( dc.app && dc.app.workspace ){ var values = {}; _.each( dc.app.workspace.searchValueSubstitutions, function(value,key) { values[ key ] = _.invert( value ); }); return this._searchValues = values; } else { return {}; } }, // Start a search for a query string, updating the page URL. search : function(query, pageNumber, callback) { dc.ui.spinner.show(); dc.app.navigation.open('search'); if (this.currentSearch) this.currentSearch.abort(); this.searchBox.value(query); this.flags.related = query.indexOf('related:') >= 0; this.flags.specific = query.indexOf('document:') >= 0; this.flags.hasEntities = false; this.page = pageNumber <= 1 ? null : pageNumber; this.fragment = 'search/' + query; this.showDocuments(); this.navigate(this.urlFragment()); Documents.reset(); this._afterSearch = callback; var keys = this.searchKeySubstitutions(), values = this.searchValueSubstitutions(), parts = []; // Turn the translated strings back into the appropriate // keys and values to send to the server dc.app.visualSearch.searchQuery.each(_.bind(function(facet, i) { facet = facet.clone(); var category = facet.get('category'), options = values[ keys[category] ]; facet.set({ category: keys[category] || category }); if ( options ){ facet.set({ value: options[ facet.get('value') ] || facet.get('value') }); } parts.push(facet.serialize()); }, this)); var params = _.extend(dc.app.paginator.queryParams(), {q : parts.join(' ') }); if (dc.app.navigation.isOpen('entities')) params.include_facets = true; if (this.page) params.page = this.page; this.currentSearch = $.ajax({ url: this.DOCUMENTS_URL, data: params, success: this._loadSearchResults, error: function(req, textStatus, errorThrown) { if (req.status == 403) Accounts.forceLogout(); }, dataType: 'json' }); }, showDocuments : function() { var query = this.searchBox.value(); var title = dc.model.DocumentSet.entitle(query); var projectName = dc.app.visualSearch.searchQuery.find( _.t('project') ); var groupName = dc.app.visualSearch.searchQuery.find( _.t('group') ); $(document.body).setMode('active', 'search'); this.titleBox.html(title); dc.app.organizer.highlight(projectName, groupName); }, // Hide the spinner and remove the search lock when finished searching. doneSearching : function() { var count = dc.app.paginator.query.total; var searchType = this.searchType(); if (this.flags.specific) { this.titleBox.text( _.t('x_documents', count ) ); } else if (searchType == 'search') { var quote = dc.app.visualSearch.searchQuery.has( _.t('project') ); if ( count ){ this.titleBox.html( _.t('x_results',count) ); } else { this.titleBox.html( _.t('no_results_for', (quote ? '“' : '') + this.titleBox.html() + (quote ? '”' : '') ) ); } } if (count <= 0) { $(document.body).setMode('empty', 'search'); var explanation = this.NO_RESULTS[searchType] || this.NO_RESULTS['search']; $('#no_results .explanation').text(explanation); } dc.ui.spinner.hide(); dc.app.scroller.checkLater(); }, searchType : function() { var single = false; var multiple = false; dc.app.visualSearch.searchQuery.each(function(facet) { var category = facet.get('category'); var value = facet.get('value'); if (value) { if (!single && !multiple) { single = category; } else { multiple = true; single = false; } } }); if ( single == _.t('filter') ) { return dc.app.visualSearch.searchQuery.first().get('value'); } else if (single == _.t('projectid') ) { return 'project'; } else if (_.contains([_.t('project'), _.t('group'), _.t('account')], single)) { return single; } else if (!single && !multiple) { return 'all'; } return 'search'; }, loadFacets : function() { if (this.flags.hasEntities) return; var query = this.searchBox.value() || ''; dc.ui.spinner.show(); this.currentSearch = $.get(this.FACETS_URL, {q: query}, this._loadFacetsResults, 'json'); }, loadFacet : function(facet) { dc.ui.spinner.show(); this.currentSearch = $.get(this.FACETS_URL, {q : this.searchBox.value(), facet : facet}, this._loadFacetResults, 'json'); }, // When searching by the URL's hash value, we need to unescape first. searchByHash : function(query, page) { _.defer(_.bind(function() { this.search(query ? decodeURIComponent(query) : '', page && parseInt(page, 10)); }, this)); }, // Toggle a query fragment in the search. toggleSearch : function(category, value) { if (dc.app.visualSearch.searchQuery.has(category)) { this.removeFromSearch(category); } else { this.addToSearch(category, value); } }, // Add a query fragment to the search and search again, if it's not already // present in the current search. addToSearch : function(category, value, callback) { if (dc.app.visualSearch.searchQuery.has(category, value)) return; dc.app.visualSearch.searchQuery.add({category: category, value: value, app: dc.app.visualSearch}); var query = dc.app.visualSearch.searchQuery.serialize(); this.search(query, null, callback); }, // Remove a query fragment from the search and search again, only if it's // present in the current search. removeFromSearch : function(category) { var query = dc.app.visualSearch.searchQuery.withoutCategory(category); this.search(query); return true; }, viewEntities : function(docs) { dc.app.navigation.open('entities', true); this.search(_.map(docs, function(doc){ return 'document: ' + doc.canonicalId(); }).join(' ')); }, // After the initial search results come back, send out a request for the // associated metadata, as long as something was found. Think about returning // the metadata right alongside the document JSON. _loadSearchResults : function(resp) { dc.app.paginator.setQuery(resp.query, this); if (resp.facets) this._loadFacetsResults(resp); var docs = resp.documents; for (var i = 0, l = docs.length; i < l; i++) docs[i].index = i; Documents.reset(docs); this.doneSearching(); this.currentSearch = null; if (this._afterSearch) this._afterSearch(); }, _loadFacetsResults : function(resp) { dc.app.workspace.entityList.renderFacets(resp.facets, 5, resp.query.total); dc.ui.spinner.hide(); this.currentSearch = null; this.flags.hasEntities = true; }, _loadFacetResults : function(resp) { dc.app.workspace.entityList.mergeFacets(resp.facets, 500, resp.query.total); dc.ui.spinner.hide(); this.currentSearch = null; } });
ivarvong/documentcloud
public/javascripts/app/searcher.js
JavaScript
mit
10,649
/* Copyright 2014 Mozilla Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; (function (root, factory) { if (typeof define === 'function' && define.amd) { define('pdfjs/core/ps_parser', ['exports', 'pdfjs/shared/util', 'pdfjs/core/parser'], factory); } else if (typeof exports !== 'undefined') { factory(exports, require('../shared/util.js'), require('./parser.js')); } else { factory((root.pdfjsCorePsParser = {}), root.pdfjsSharedUtil, root.pdfjsCoreParser); } }(this, function (exports, sharedUtil, coreParser) { var error = sharedUtil.error; var isSpace = sharedUtil.isSpace; var EOF = coreParser.EOF; var PostScriptParser = (function PostScriptParserClosure() { function PostScriptParser(lexer) { this.lexer = lexer; this.operators = []; this.token = null; this.prev = null; } PostScriptParser.prototype = { nextToken: function PostScriptParser_nextToken() { this.prev = this.token; this.token = this.lexer.getToken(); }, accept: function PostScriptParser_accept(type) { if (this.token.type === type) { this.nextToken(); return true; } return false; }, expect: function PostScriptParser_expect(type) { if (this.accept(type)) { return true; } error('Unexpected symbol: found ' + this.token.type + ' expected ' + type + '.'); }, parse: function PostScriptParser_parse() { this.nextToken(); this.expect(PostScriptTokenTypes.LBRACE); this.parseBlock(); this.expect(PostScriptTokenTypes.RBRACE); return this.operators; }, parseBlock: function PostScriptParser_parseBlock() { while (true) { if (this.accept(PostScriptTokenTypes.NUMBER)) { this.operators.push(this.prev.value); } else if (this.accept(PostScriptTokenTypes.OPERATOR)) { this.operators.push(this.prev.value); } else if (this.accept(PostScriptTokenTypes.LBRACE)) { this.parseCondition(); } else { return; } } }, parseCondition: function PostScriptParser_parseCondition() { // Add two place holders that will be updated later var conditionLocation = this.operators.length; this.operators.push(null, null); this.parseBlock(); this.expect(PostScriptTokenTypes.RBRACE); if (this.accept(PostScriptTokenTypes.IF)) { // The true block is right after the 'if' so it just falls through on // true else it jumps and skips the true block. this.operators[conditionLocation] = this.operators.length; this.operators[conditionLocation + 1] = 'jz'; } else if (this.accept(PostScriptTokenTypes.LBRACE)) { var jumpLocation = this.operators.length; this.operators.push(null, null); var endOfTrue = this.operators.length; this.parseBlock(); this.expect(PostScriptTokenTypes.RBRACE); this.expect(PostScriptTokenTypes.IFELSE); // The jump is added at the end of the true block to skip the false // block. this.operators[jumpLocation] = this.operators.length; this.operators[jumpLocation + 1] = 'j'; this.operators[conditionLocation] = endOfTrue; this.operators[conditionLocation + 1] = 'jz'; } else { error('PS Function: error parsing conditional.'); } } }; return PostScriptParser; })(); var PostScriptTokenTypes = { LBRACE: 0, RBRACE: 1, NUMBER: 2, OPERATOR: 3, IF: 4, IFELSE: 5 }; var PostScriptToken = (function PostScriptTokenClosure() { function PostScriptToken(type, value) { this.type = type; this.value = value; } var opCache = Object.create(null); PostScriptToken.getOperator = function PostScriptToken_getOperator(op) { var opValue = opCache[op]; if (opValue) { return opValue; } return opCache[op] = new PostScriptToken(PostScriptTokenTypes.OPERATOR, op); }; PostScriptToken.LBRACE = new PostScriptToken(PostScriptTokenTypes.LBRACE, '{'); PostScriptToken.RBRACE = new PostScriptToken(PostScriptTokenTypes.RBRACE, '}'); PostScriptToken.IF = new PostScriptToken(PostScriptTokenTypes.IF, 'IF'); PostScriptToken.IFELSE = new PostScriptToken(PostScriptTokenTypes.IFELSE, 'IFELSE'); return PostScriptToken; })(); var PostScriptLexer = (function PostScriptLexerClosure() { function PostScriptLexer(stream) { this.stream = stream; this.nextChar(); this.strBuf = []; } PostScriptLexer.prototype = { nextChar: function PostScriptLexer_nextChar() { return (this.currentChar = this.stream.getByte()); }, getToken: function PostScriptLexer_getToken() { var comment = false; var ch = this.currentChar; // skip comments while (true) { if (ch < 0) { return EOF; } if (comment) { if (ch === 0x0A || ch === 0x0D) { comment = false; } } else if (ch === 0x25) { // '%' comment = true; } else if (!isSpace(ch)) { break; } ch = this.nextChar(); } switch (ch | 0) { case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: // '0'-'4' case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: // '5'-'9' case 0x2B: case 0x2D: case 0x2E: // '+', '-', '.' return new PostScriptToken(PostScriptTokenTypes.NUMBER, this.getNumber()); case 0x7B: // '{' this.nextChar(); return PostScriptToken.LBRACE; case 0x7D: // '}' this.nextChar(); return PostScriptToken.RBRACE; } // operator var strBuf = this.strBuf; strBuf.length = 0; strBuf[0] = String.fromCharCode(ch); while ((ch = this.nextChar()) >= 0 && // and 'A'-'Z', 'a'-'z' ((ch >= 0x41 && ch <= 0x5A) || (ch >= 0x61 && ch <= 0x7A))) { strBuf.push(String.fromCharCode(ch)); } var str = strBuf.join(''); switch (str.toLowerCase()) { case 'if': return PostScriptToken.IF; case 'ifelse': return PostScriptToken.IFELSE; default: return PostScriptToken.getOperator(str); } }, getNumber: function PostScriptLexer_getNumber() { var ch = this.currentChar; var strBuf = this.strBuf; strBuf.length = 0; strBuf[0] = String.fromCharCode(ch); while ((ch = this.nextChar()) >= 0) { if ((ch >= 0x30 && ch <= 0x39) || // '0'-'9' ch === 0x2D || ch === 0x2E) { // '-', '.' strBuf.push(String.fromCharCode(ch)); } else { break; } } var value = parseFloat(strBuf.join('')); if (isNaN(value)) { error('Invalid floating point number: ' + value); } return value; } }; return PostScriptLexer; })(); exports.PostScriptLexer = PostScriptLexer; exports.PostScriptParser = PostScriptParser; }));
kabrice/3iSchool
web/library/pdfjs/src/core/ps_parser.js
JavaScript
mit
7,553
/** * @license * Copyright 2013 David Eberlein ([email protected]) * MIT-licensed (http://opensource.org/licenses/MIT) */ /** * @fileoverview DataHandler implementation for the fractions option. * @author David Eberlein ([email protected]) */ /*global Dygraph:false */ "use strict"; import DygraphDataHandler from './datahandler'; import DefaultHandler from './default'; /** * @extends DefaultHandler * @constructor */ var DefaultFractionHandler = function() { }; DefaultFractionHandler.prototype = new DefaultHandler(); DefaultFractionHandler.prototype.extractSeries = function(rawData, i, options) { // TODO(danvk): pre-allocate series here. var series = []; var x, y, point, num, den, value; var mult = 100.0; var logScale = options.get('logscale'); for ( var j = 0; j < rawData.length; j++) { x = rawData[j][0]; point = rawData[j][i]; if (logScale && point !== null) { // On the log scale, points less than zero do not exist. // This will create a gap in the chart. if (point[0] <= 0 || point[1] <= 0) { point = null; } } // Extract to the unified data format. if (point !== null) { num = point[0]; den = point[1]; if (num !== null && !isNaN(num)) { value = den ? num / den : 0.0; y = mult * value; // preserve original values in extras for further filtering series.push([ x, y, [ num, den ] ]); } else { series.push([ x, num, [ num, den ] ]); } } else { series.push([ x, null, [ null, null ] ]); } } return series; }; DefaultFractionHandler.prototype.rollingAverage = function(originalData, rollPeriod, options) { rollPeriod = Math.min(rollPeriod, originalData.length); var rollingData = []; var i; var num = 0; var den = 0; // numerator/denominator var mult = 100.0; for (i = 0; i < originalData.length; i++) { num += originalData[i][2][0]; den += originalData[i][2][1]; if (i - rollPeriod >= 0) { num -= originalData[i - rollPeriod][2][0]; den -= originalData[i - rollPeriod][2][1]; } var date = originalData[i][0]; var value = den ? num / den : 0.0; rollingData[i] = [ date, mult * value ]; } return rollingData; }; export default DefaultFractionHandler;
vhotspur/dygraphs
src/datahandler/default-fractions.js
JavaScript
mit
2,332
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** File Name: lexical-006.js Corresponds To: 7.4.2-1.js ECMA Section: 7.4.2 Description: The following tokens are ECMAScript keywords and may not be used as identifiers in ECMAScript programs. Syntax Keyword :: one of break for new var continue function return void delete if this while else in typeof with This test verifies that the keyword cannot be used as an identifier. Functioinal tests of the keyword may be found in the section corresponding to the function of the keyword. Author: [email protected] Date: 12 november 1997 */ var SECTION = "lexical-006"; var VERSION = "JS1_4"; var TITLE = "Keywords"; startTest(); writeHeaderToLog( SECTION + " "+ TITLE); var result = "Failed"; var exception = "No exception thrown"; var expect = "Passed"; try { eval("break = new Object();"); } catch ( e ) { result = expect; exception = e.toString(); } new TestCase( SECTION, "break = new Object()" + " (threw " + exception +")", expect, result ); test();
kostaspl/SpiderMonkey38
js/src/tests/ecma_2/Exceptions/lexical-006.js
JavaScript
mpl-2.0
1,433
(function(global) { "use strict"; const { Float32Array, Float64Array, Object, Reflect, SharedArrayBuffer, WeakMap, assertEq } = global; const { apply: Reflect_apply, construct: Reflect_construct, } = Reflect; const { get: WeakMap_prototype_get, has: WeakMap_prototype_has, } = WeakMap.prototype; const sharedConstructors = new WeakMap(); // Synthesize a constructor for a shared memory array from the constructor // for unshared memory. This has "good enough" fidelity for many uses. In // cases where it's not good enough, call isSharedConstructor for local // workarounds. function sharedConstructor(baseConstructor) { // Create SharedTypedArray as a subclass of %TypedArray%, following the // built-in %TypedArray% subclasses. class SharedTypedArray extends Object.getPrototypeOf(baseConstructor) { constructor(...args) { var array = Reflect_construct(baseConstructor, args); var {buffer, byteOffset, length} = array; var sharedBuffer = new SharedArrayBuffer(buffer.byteLength); var sharedArray = Reflect_construct(baseConstructor, [sharedBuffer, byteOffset, length], new.target); for (var i = 0; i < length; i++) sharedArray[i] = array[i]; assertEq(sharedArray.buffer, sharedBuffer); return sharedArray; } } // 22.2.5.1 TypedArray.BYTES_PER_ELEMENT Object.defineProperty(SharedTypedArray, "BYTES_PER_ELEMENT", {__proto__: null, value: baseConstructor.BYTES_PER_ELEMENT}); // 22.2.6.1 TypedArray.prototype.BYTES_PER_ELEMENT Object.defineProperty(SharedTypedArray.prototype, "BYTES_PER_ELEMENT", {__proto__: null, value: baseConstructor.BYTES_PER_ELEMENT}); // Share the same name with the base constructor to avoid calling // isSharedConstructor() in multiple places. Object.defineProperty(SharedTypedArray, "name", {__proto__: null, value: baseConstructor.name}); sharedConstructors.set(SharedTypedArray, baseConstructor); return SharedTypedArray; } /** * All TypedArray constructors for unshared memory. */ const typedArrayConstructors = Object.freeze([ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, ]); /** * All TypedArray constructors for shared memory. */ const sharedTypedArrayConstructors = Object.freeze( typeof SharedArrayBuffer === "function" ? typedArrayConstructors.map(sharedConstructor) : [] ); /** * All TypedArray constructors for unshared and shared memory. */ const anyTypedArrayConstructors = Object.freeze([ ...typedArrayConstructors, ...sharedTypedArrayConstructors, ]); /** * Returns `true` if `constructor` is a TypedArray constructor for shared * memory. */ function isSharedConstructor(constructor) { return Reflect_apply(WeakMap_prototype_has, sharedConstructors, [constructor]); } /** * Returns `true` if `constructor` is a TypedArray constructor for shared * or unshared memory, with an underlying element type of either Float32 or * Float64. */ function isFloatConstructor(constructor) { if (isSharedConstructor(constructor)) constructor = Reflect_apply(WeakMap_prototype_get, sharedConstructors, [constructor]); return constructor == Float32Array || constructor == Float64Array; } global.typedArrayConstructors = typedArrayConstructors; global.sharedTypedArrayConstructors = sharedTypedArrayConstructors; global.anyTypedArrayConstructors = anyTypedArrayConstructors; global.isSharedConstructor = isSharedConstructor; global.isFloatConstructor = isFloatConstructor; })(this);
Yukarumya/Yukarum-Redfoxes
js/src/tests/ecma_7/TypedArray/shell.js
JavaScript
mpl-2.0
4,240
(function() { var namespace = WEBLAB.namespace("WEBLAB.utils.data"); var ArrayFunctions = namespace.ArrayFunctions; var Utils = WEBLAB.namespace("WEBLAB.utils").Utils; if (namespace.MultidimensionalArrayHolder === undefined) { var MultidimensionalArrayHolder = function MultidimensionalArrayHolder() { this._init(); }; namespace.MultidimensionalArrayHolder = MultidimensionalArrayHolder; var p = MultidimensionalArrayHolder.prototype; p._init = function() { this._array = null; this._lengths = null; return this; }; p.getDimesionLength = function(aDimension) { return this._lengths[aDimension]; } p._getArrayPosition = function(aPositions) { var returnValue = 0; var multiplier = 1; var currentArray = this._lengths; var currentArrayLength = currentArray.length; for (var i = currentArrayLength; --i >= 0;) { //MENOTE: loop from end to start returnValue += multiplier * aPositions[i]; multiplier *= currentArray[i]; } return returnValue; } p.getValue = function( /* ... aPositions */ ) { aPositions = arguments; if (aPositions.length != this._lengths.length) { //METODO: error message return null; } var arrayPosition = this._getArrayPosition(aPositions); return this._array[arrayPosition]; }; p.setValue = function( /* ... aPositions, aValue */ ) { if (arguments.length != this._lengths.length + 1) { //METODO: error message return; } var arrayPosition = this._getArrayPosition(arguments); this._array[arrayPosition] = arguments[arguments.length - 1]; }; p.setLengths = function(aLengths) { this._lengths = aLengths; var totalLength = 1; var currentArray = this._lengths; var currentArrayLength = currentArray.length; for (var i = 0; i < currentArrayLength; i++) { totalLength *= currentArray[i]; } this._array = new Array(totalLength); }; p.destroy = function() { Utils.destroyArrayIfExists(this._array); this._array = null; this._lengths = null; //WEBLAB.namespace("WEBLAB.utils.dev").DestroyVerification.verifyNoComplexObjects(this); }; MultidimensionalArrayHolder.create = function( /* ... aLengths */ ) { //trace("weblab.utils.data.MultidimensionalArrayHolder.create"); aLengths = arguments; var newMultidimensionalArrayHolder = (new MultidimensionalArrayHolder()); newMultidimensionalArrayHolder.setLengths(ArrayFunctions.copyArray(aLengths)); return newMultidimensionalArrayHolder; } //End function create } })();
r8o8s1e0/ChromeWebLab
Sketchbots/sw/ui/controller/libs/weblab/utils/data/MultidimensionalArrayHolder.js
JavaScript
apache-2.0
3,087
define(["require", "exports"], function(require, exports) { (function (Baz) { Baz.x = "hello"; })(exports.Baz || (exports.Baz = {})); var Baz = exports.Baz; Baz.x = "goodbye"; void 0; })
vcsjones/typescript
tests/baselines/reference/moduleCodegenTest4.amd.js
JavaScript
apache-2.0
214
/** * Install globals into the jsdom namespace. * @param {function} mapFunc This function will be called to get the list of * things to install into the namespace. Should return an object of keys * to values to install. */ export default function(mapFunc) { return function(options) { let map; global.beforeEach(() => { map = mapFunc(options); for (let key in map) { let val = map[key]; global[key] = val; if (global.window) { global.window[key] = val; } } }); global.afterEach(() => { for (let key in map) { delete global[key]; if (global.window) { delete global.window[key]; } } }); }; }
mythmon/kitsune
kitsune/sumo/static/sumo/js/tests/fixtures/mochaFixtureHelper.js
JavaScript
bsd-3-clause
732
'use strict'; // ############################################################################# // add a test for creating apphook and trying to copy a page with an apphook var casperjs = require('casper'); var helpers = require('djangocms-casper-helpers'); var globals = helpers.settings; var cms = helpers(casperjs); casper.test.setUp(function(done) { casper .start() .then(cms.login()) .then(cms.addPage({ title: 'Home' })) .then(cms.addPage({ title: 'apphook' })) .then( cms.addApphookToPage({ page: 'apphook', apphook: 'Example1App' }) ) .run(done); }); casper.test.tearDown(function(done) { casper.start().then(cms.removePage()).then(cms.removePage()).then(cms.logout()).run(done); }); casper.test.begin('copy page with apphook should not be copied', function(test) { casper .start() .thenOpen(globals.baseUrl) .then(cms.openSideframe()) .withFrame(0, function() { casper.waitUntilVisible('.cms-pagetree-jstree').wait(3000).then(cms.expandPageTree()); this.then(cms.triggerCopyPage({ page: cms.getPageNodeId('apphook') })); this.waitUntilVisible('.messagelist', function() { test.assertVisible('.error', 'Message appeared'); test.assertSelectorHasText( 'li.error', 'This page cannot be copied because an application is attached to it.' ); }); }) .run(function() { test.done(); }); });
rsalmaso/django-cms
cms/tests/frontend/integration/copy-apphook-page.js
JavaScript
bsd-3-clause
1,623
define(['./drop'], function(drop) { /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @alias tail * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] */ function rest(array) { return drop(array, 1); } return rest; });
tomek-f/shittets
require-js-amd/require-zepto-lodash/static/js/lib/lodash-amd/array/rest.js
JavaScript
mit
405
ace.define("ace/snippets/zeek",["require","exports","module"],function(e,t,n){"use strict";t.snippetText=undefined,t.scope=""}); (function() { ace.require(["ace/snippets/zeek"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
chrisJohn404/ljswitchboard-static_files
static/js/ace/snippets/zeek.js
JavaScript
mit
456
const set = require('regenerate')(0x3030, 0x30FB, 0x32FF); set.addRange(0x2E80, 0x2E99).addRange(0x2E9B, 0x2EF3).addRange(0x2F00, 0x2FD5).addRange(0x3001, 0x3003).addRange(0x3005, 0x3011).addRange(0x3013, 0x301F).addRange(0x3021, 0x302D).addRange(0x3037, 0x303F).addRange(0x3190, 0x319F).addRange(0x31C0, 0x31E3).addRange(0x3220, 0x3247).addRange(0x3280, 0x32B0).addRange(0x32C0, 0x32CB).addRange(0x3358, 0x3370).addRange(0x337B, 0x337F).addRange(0x33E0, 0x33FE).addRange(0x3400, 0x4DB5).addRange(0x4E00, 0x9FEF).addRange(0xF900, 0xFA6D).addRange(0xFA70, 0xFAD9).addRange(0xFE45, 0xFE46).addRange(0xFF61, 0xFF65).addRange(0x1D360, 0x1D371).addRange(0x1F250, 0x1F251).addRange(0x20000, 0x2A6D6).addRange(0x2A700, 0x2B734).addRange(0x2B740, 0x2B81D).addRange(0x2B820, 0x2CEA1).addRange(0x2CEB0, 0x2EBE0).addRange(0x2F800, 0x2FA1D); module.exports = set;
gusortiz/code_challenges
node_modules/regenerate-unicode-properties/Script_Extensions/Han.js
JavaScript
mit
852
/** * @file * Javascript behaviors for jquery.inputmask integration. */ (function ($, Drupal) { 'use strict'; /** * Initialize input masks. * * @type {Drupal~behavior} */ Drupal.behaviors.yamlFormElementMask = { attach: function (context) { $(context).find('input.js-yamlform-element-mask').once('yamlform-element-mask').inputmask(); } }; })(jQuery, Drupal);
akorkot/copieubl
modules/yamlform/js/yamlform.element.inputmask.js
JavaScript
gpl-2.0
400
// This should give CORRECT on the default problem 'hello'. // // @EXPECTED_RESULTS@: CORRECT if ( process.env.DOMJUDGE ) { console.log('Hello world!'); } else { console.log('DOMJUDGE not defined'); process.exit(1); }
Lekssays/brackets
web/tests/test-hello.js
JavaScript
gpl-3.0
225
function scutils_PreInit() { if(g_scormEnabled && g_scormLoaded ) { scutils_checkResumeSupported(); // if(g_LMSResumeSupported && g_hasTesting == true) // { // doLMSSetValue( "cmi.score.min", g_nTotalMinAchievablePoints ) ; // doLMSSetValue( "cmi.score.max", g_nTotalMaxAchievablePoints ) ; // } scutils_setMinMaxScores(); if (doLMSGetValue( "cmi.entry") == "resume") { var pos = doLMSGetValue("cmi.location"); g_returnPosition = parseInt(pos); if(g_LMSResumeSupported) { scutils_loadAchiveScore(); scutils_loadSuspendData(); } } else { if(g_LMSResumeSupported && g_hasTesting == true && checkSuccessStatus() != null) doLMSSetValue( "cmi.score.raw", g_nTotalCurrentlyAchievePoints ) ; if(g_hasTesting == true && checkSuccessStatus() != null) scutils_updateSuccessStatus(); scutils_updateCompletionStatus(); } if(g_hasTesting == false) window.setInterval("g_sessionTime++", 1000) } } function delayedSeekTime(msTime) { if (InitImageStyle.visibility == 'hidden') { g_returnPosition = msTime; setTimeout("control_play()", 0); setTimeout("control_pause()", 50); g_returnPlay = g_isAutostartMode; if(g_isAutostartMode == true) setTimeout("layout_onGotoTimestamp(g_returnPosition, 'play')", 500); else setTimeout("layout_onGotoTimestamp(g_returnPosition, 'pause')", 500); setTimeout("control_stop()", 520); } else setTimeout("delayedSeekTime(g_returnPosition)", 500); } function scutils_PostInit() { if(g_scormEnabled && g_scormLoaded ) { if (doLMSGetValue( "cmi.entry") == "resume") { if(g_LMSResumeSupported) { scutils_loadLearnerData(); } //if (control_getType() == "RM") delayedSeekTime(g_returnPosition); //else //setTimeout("layout_onGotoTimestamp(g_returnPosition, 'pause')", 500); } } } function scutils_Finish() { if(g_scormEnabled && g_scormLoaded ) { if(g_LMSResumeSupported) scutils_saveSuspendData(); var time = getPlayTime(); doLMSSetValue("cmi.session_time", time); if(g_hasTesting == true && checkSuccessStatus() != null) var a_successStatus = scutils_updateSuccessStatus(); var a_completionStatus = scutils_updateCompletionStatus(); doLMSSetValue( "cmi.location", g_location ) ; if (a_successStatus && a_completionStatus ) { // should be doLMSSetValue("cmi.exit", "normal"); but are some problems with status reporting in CLIX doLMSSetValue("cmi.exit", "suspend"); } else { doLMSSetValue("cmi.exit", "suspend"); } } } function checkSuccessStatus() { var t_crtCout = doLMSGetValue("cmi.interactions._count"); var t_InteractionID; var result; for (var qIdx = 0; qIdx < g_questionEntries.length; qIdx++) { var n = scutils_getInteractionIndex(g_questionEntries[qIdx].strId); if( n != null) { result = doLMSGetValue("cmi.interactions."+n+".result"); if(result != null) break; } } return result; } function getPlayTime() { var hours = parseInt(g_sessionTime / 3600); var minutes = parseInt((g_sessionTime % 3600) / 60); var seconds = (g_sessionTime % 3600) % 60; var retVal = "PT"+ hours+"H"+minutes+"M"+seconds+"S"; return retVal; } function scutils_setMinMaxScores() { if(g_LMSResumeSupported && g_hasTesting == true) { doLMSSetValue( "cmi.score.min", g_nTotalMinAchievablePoints ) ; doLMSSetValue( "cmi.score.max", g_nTotalMaxAchievablePoints ) ; } } function scutils_setLocation(a_scormLocation) { if (g_scormEnabled && g_scormLoaded ) { //doLMSSetValue( "cmi.location", a_scormLocation ) ; g_location = a_scormLocation ; } } function scutils_addInteraction(a_InteractionID, a_InteractionType, a_InteractionTimeStamp, a_InteractionWeighting, a_interactionPattern) { if (g_scormEnabled && g_scormLoaded ) { var t_InteractionTimeStamp = scutils_GMTtoLMStime(a_InteractionTimeStamp); var crtCout = doLMSGetValue("cmi.interactions._count"); doLMSSetValue( "cmi.interactions."+crtCout+".id", "urn:IMC:interaction_"+a_InteractionID) ; //doLMSCommit(); doLMSSetValue( "cmi.interactions."+crtCout+".type", a_InteractionType) ; //doLMSCommit(); doLMSSetValue( "cmi.interactions."+crtCout+".timestamp", t_InteractionTimeStamp ); //doLMSCommit(); doLMSSetValue( "cmi.interactions."+crtCout+".weighting", a_InteractionWeighting ); //doLMSCommit(); if(a_InteractionType == "fill-in") { var i=0; var j=0; var k=0; var str = ""; var fill = new Array(); while(i < a_interactionPattern.length) { fill[j] = new Array(); while(a_interactionPattern.charAt(i) != '[' && i < a_interactionPattern.length) { if(a_interactionPattern.charAt(i) != ';' && a_interactionPattern.charAt(i) != '[') str += a_interactionPattern.charAt(i); else { fill[j][k] = str; str = ""; k ++; } i ++; } fill[j][k] = str; str = ""; k = 0; i += 3; j ++; } k = 0; var index = 0; var as = false; var st = new Array(); st[k] = -1; while(k > -1) { if(st[k] < fill[k].length-1) { st[k] = st[k] + 1; as = true; } else as = false; if(as) { if(k == fill.length-1) { a_interactionPattern = ""; for(i=0; i < st.length; i++) { if(i != st.length-1) a_interactionPattern += fill[i][st[i]] + "[,]"; else a_interactionPattern += fill[i][st[i]]; } doLMSSetValue( "cmi.interactions."+crtCout+".correct_responses."+index+".pattern", a_interactionPattern ) ; index ++; } else { k ++; st[k] = -1; } } else k --; } } else doLMSSetValue( "cmi.interactions."+crtCout+".correct_responses.0.pattern", a_interactionPattern ) ; doLMSCommit(); } } function scutils_setInteractionResult(a_InteractionID , a_InteractionResult, a_InteractionLearnerResponse, a_InteractionTimeLatency) { if (g_scormEnabled && g_scormLoaded ) { var t_index = scutils_getInteractionIndex(a_InteractionID) if(t_index != null) { doLMSSetValue( "cmi.interactions."+t_index+".result", a_InteractionResult ) ; doLMSSetValue( "cmi.interactions."+t_index+".learner_response", a_InteractionLearnerResponse) ; var t_timeStamp = doLMSGetValue( "cmi.interactions."+t_index+".timestamp"); var t_TimeStampGMT = scutils_LMStoGMTtime(t_timeStamp); var t_InteractionTimeLatencyGMT = new Date(a_InteractionTimeLatency.toUTCString()); var t_TimeLatencyGMT = t_InteractionTimeLatencyGMT-t_TimeStampGMT; var t_TimeLatencyLMS = scutils_GMTtoLMS_TimeInterval(t_TimeLatencyGMT); doLMSSetValue( "cmi.interactions."+t_index+".latency", t_TimeLatencyLMS ) ; doLMSCommit(); } } } function scutils_getInteractionIndex(a_InteractionID) { if (g_scormEnabled && g_scormLoaded ) { var t_crtCout = doLMSGetValue("cmi.interactions._count"); var t_InteractionID; for (var i = 0; i < t_crtCout; ++i) { t_InteractionID = doLMSGetValue("cmi.interactions."+i+".id"); if(("urn:IMC:interaction_"+a_InteractionID) == t_InteractionID) { return i; } } return null; } return null; } function scutils_setAchiveScore(a_AchiveScore) { if (g_scormEnabled && g_scormLoaded ) { doLMSSetValue( "cmi.score.raw", a_AchiveScore ) ; } } function scutils_loadAchiveScore() { if (g_scormEnabled && g_scormLoaded) { var a_crtAchiveScore = doLMSGetValue( "cmi.score.raw" ) ; if(a_crtAchiveScore != null) g_nTotalCurrentlyAchievePoints = parseInt(a_crtAchiveScore); } return; } function scutils_updateSuccessStatus() { if (g_scormEnabled && g_scormLoaded ) { if(g_nTotalCurrentlyAchievePoints >= g_nTotalPassAchievablePoints) { doLMSSetValue( "cmi.success_status", "passed" ) ; return true; } else { doLMSSetValue( "cmi.success_status", "failed" ) ; return false; } } } function scutils_updateCompletionStatus() { if (g_scormEnabled && g_scormLoaded ) { var a_visitedCount = 0; for ( var i = 0; i < g_visitedPages.length; i++) if(g_visitedPages[i] == "true") a_visitedCount++; var nNumberOfCopletionPages = g_thumbCount; if(g_isRandomTest) { var nFirstQPage = g_questionEntries[0].nPage; var nLastQPage = g_questionEntries[g_questionEntries.length - 1].nPage; nNumberOfCopletionPages = g_thumbCount -(nLastQPage - nFirstQPage) + 1 + g_nrOfRandomQuestions; } if(a_visitedCount < nNumberOfCopletionPages)//g_thumbCount) { doLMSSetValue( "cmi.completion_status", "incomplete" ) ; return false; } else { doLMSSetValue( "cmi.completion_status", "completed" ) ; return true; } } } function scutils_getSuccessStatus() { if (g_scormEnabled && g_scormLoaded ) { return doLMSGetValue("cmi.success_status" ) ; } return; } function scutils_saveSuspendData() { if (g_scormEnabled && g_scormLoaded ) { // wil contain comma separated information for every question and every data information // comma separated for all questions // Question1 -> QuestionnaireIndex [,]QuestionEntryIndex[,]QuestionAddedLMS[,]QuestionActivatedStatus[,]QuestionTakenAttempts[,]QuestionViewedSec // Question2 -> QuestionnaireIndex[,]QuestionEntryIndex[,]QuestionAddedLMS[,]QuestionActivatedStatus[,]QuestionTakenAttempts[,]QuestionViewedSec // Question1{,}Question2[,]Question3 //DataInfo1<,>DataInfo2<,>DataInfo3 var a_suspendData = ""; if(g_hasTesting == true) { var qLooping = false; for(var j = 0; j < g_questionEntries.length; ++j ) { if(qLooping) a_suspendData+=g_MajorStrSeparator; else qLooping = true; a_suspendData += j + g_MinorStrSeparator + g_questionEntries[j].nQuestionAddedLMS + g_MinorStrSeparator + g_questionEntries[j].bIsDeactivated + g_MinorStrSeparator + g_questionEntries[j].nTakenAttempts + g_MinorStrSeparator + g_questionEntries[j].nViewedSec ; } } a_suspendData += g_ScopeStrSeparator; for(var i = 0; i < g_visitedPages.length-1; i++) a_suspendData += g_visitedPages[i] + g_MinorStrSeparator; if(g_visitedPages.length >= 1) a_suspendData += g_visitedPages[g_visitedPages.length-1]; if(g_isRandomTest) { a_suspendData += g_ScopeStrSeparator; for( var k = 0 ; k < g_randomQuestionOrder.length - 1; k++) { a_suspendData += g_randomQuestionOrder[k] + g_MinorStrSeparator; } if(g_randomQuestionOrder.length >= 1) a_suspendData += g_randomQuestionOrder[g_randomQuestionOrder.length - 1]; } doLMSSetValue( "cmi.suspend_data", a_suspendData) ; } } function scutils_loadSuspendData() { if (g_scormEnabled && g_scormLoaded ) { // wil contain comma separated information for every question // comma separated for all questions // Question1 -> QuestionEntryIndex, QuestionAddedLMS, QuestionActivatedStatus, QuestionTakenAttempts, QuestionViewedSec // Question2 -> QuestionEntryIndex, QuestionAddedLMS, QuestionActivatedStatus, QuestionTakenAttempts, QuestionViewedSec // Question3 -> QuestionEntryIndex, QuestionAddedLMS, QuestionActivatedStatus, QuestionTakenAttempts, QuestionViewedSec // Question1, Question2, Question3 var a_suspendDataInformation = doLMSGetValue("cmi.suspend_data" ) ; if (a_suspendDataInformation != null) { var a_suspendData = new Array(); a_suspendData = a_suspendDataInformation.split(g_ScopeStrSeparator); // recompose g_questionEntries data if(g_hasTesting == true) { var a_QuestionData = new Array(); a_QuestionData = a_suspendData[0].split(g_MajorStrSeparator); var a_QuestionValue; for ( var j = 0; j < a_QuestionData.length; j++) { a_QuestionValue = new Array(); a_QuestionValue = a_QuestionData[j].split(g_MinorStrSeparator); var a_QuestionIndex = a_QuestionValue[0]; g_questionEntries[a_QuestionIndex] .nQuestionAddedLMS = a_QuestionValue[1]; g_questionEntries[a_QuestionIndex] .nTakenAttempts = parseInt(a_QuestionValue[3]); g_questionEntries[a_QuestionIndex] .nViewedSec = parseInt(a_QuestionValue[4]); if(a_QuestionValue[2] == "true") { deactivateQuestion(g_questionEntries[a_QuestionIndex].nPage); updateTimerFromQuestionIndex(a_QuestionIndex); } } } // recompose g_visitedPages data var a_visitedPages = new Array() ; a_visitedPages = a_suspendData[1].split(g_MinorStrSeparator); for ( var i = 0; i < a_visitedPages.length; i++) g_visitedPages[i] = a_visitedPages[i]; // recompose g_randomQuestionOrder data if needed if(g_isRandomTest) { var a_randomQuestionOrder = new Array(); a_randomQuestionOrder = a_suspendData[2].split(g_MinorStrSeparator); for (var k = 0 ; k < a_randomQuestionOrder.length; k ++) { g_randomQuestionOrder[k] = parseInt(a_randomQuestionOrder[k]); } g_isRandomQuestionOrderInitialized = true; } } } } function scutils_loadLearnerData() { if (g_scormEnabled && g_scormLoaded ) { var t_crtCout = doLMSGetValue("cmi.interactions._count"); var t_InteractionID; for (var qIdx = 0; qIdx < g_questionEntries.length; qIdx++) { var n = scutils_getInteractionIndex(g_questionEntries[qIdx].strId); if( n != null) { var result = doLMSGetValue("cmi.interactions."+n+".result"); if(result == "correct") g_questionEntries[qIdx].bSuccessfullyAnswered = true; else g_questionEntries[qIdx].bSuccessfullyAnswered = false; var response = doLMSGetValue("cmi.interactions."+n+".learner_response"); if(response != null) { var type = doLMSGetValue("cmi.interactions."+n+".type"); if(type == "choice") { var radioGroup = eval("document.TestingForm.Radio" + g_questionEntries[qIdx].nPage); if(!radioGroup) radioGroup = eval("document.TestingForm.Check" + g_questionEntries[qIdx].nPage); var j = 0; while(j < response.length) { radioGroup[g_Responses.indexOf(response.charAt(j))].checked = true; j += 4; } } else if(type == "fill-in") { var str = ""; var j = 0; while(j<response.length) { while (response.charAt(j)!='[' && j<response.length) { str += response.charAt(j); j ++; } var textFieldObj = eval("document.TestingForm." + g_textFieldEntries[g_questionFillIndex].strId); textFieldObj.value = str; g_questionFillIndex ++; str = ""; j += 3; } } else if(type == "matching") { // remember initial moveLayer positions if (originalX == null) { var count = g_targetPointEntries.length; originalX = new Array(count); originalY = new Array(count); for (i = 0; i < count; i++) { var strId = "" + g_targetPointEntries[i].strObjectId + "Layer"; originalX[i] = posX(document.getElementById(strId)); originalY[i] = posY(document.getElementById(strId)); } } var count = g_questionDragIndex; var startMs = g_targetPointEntries[count].nStartMs; while(count < g_targetPointEntries.length && g_targetPointEntries[count].nStartMs == startMs) count ++; var vector = new Array(); for(var k = g_questionDragIndex; k < count; k++) vector[k] = parseInt(g_targetPointEntries[k].nX); for(var k = g_questionDragIndex; k < count-1; k++) for(var l = k+1; l < count; l++) if(vector[l] < vector[k]) { var temp = vector[l]; vector[l] = vector[k] vector[k] = temp; } var j=0; var index = g_questionDragIndex; while(j < response.length) { var strId = "" + g_targetPointEntries[g_questionDragIndex].strObjectId + "Layer"; var imgObject = document.getElementById(strId); j += 4; var str = response.charAt(j); var k = index; while(k < count && !(str.length==1 && str.charAt(0)=='-')) { if(g_targetPointEntries[k].nX == vector[g_Responses.indexOf(str)]) { imgObject.style.left = g_targetPointEntries[k].nX + layout_getSlidesLeft(); imgObject.style.top = g_targetPointEntries[k].nY + layout_getSlidesTop(); arrangeLayer(imgObject, g_targetPointEntries[k]); // BUGFIX : position of moved image must be stored - otherwise it is moved back to // its origin position when resizing the browser window (see layout.js) var currentDndObject = null; for (i = 0; i < g_interactionEntries.length; ++i) { if(g_interactionEntries[i].strId == g_targetPointEntries[g_questionDragIndex].strObjectId) { currentDndObject = g_interactionEntries[i]; break; } } if (currentDndObject != null) { currentDndObject.x = parseInt(imgObject.style.left) - layout_getSlidesLeft(); currentDndObject.y = parseInt(imgObject.style.top) - layout_getSlidesTop(); } break; } else k++; } j += 4; g_questionDragIndex ++; } } } } } } } function scutils_GMTtoLMStime(a_TimeStamp) { var a_Year = a_TimeStamp.getFullYear(); var a_Month = a_TimeStamp.getUTCMonth()+1; if(a_Month<10) a_Month = "0"+a_Month; var a_Date = a_TimeStamp.getUTCDate(); if(a_Date<10) a_Date = "0"+a_Date; var a_Hour = a_TimeStamp.getUTCHours(); if(a_Hour<10) a_Hour = "0"+a_Hour; var a_Minute= a_TimeStamp.getUTCMinutes(); if(a_Minute<10) a_Minute = "0"+a_Minute; var a_Second= a_TimeStamp.getUTCSeconds(); if(a_Second<10) a_Second = "0"+a_Second; var timeLMS = a_Year+"-"+a_Month+"-"+a_Date+"T"+a_Hour+":"+a_Minute+":"+a_Second; return timeLMS; } function scutils_LMStoGMTtime(a_TimeStamp) { var a_DateTime = new Array(); a_DateTime = a_TimeStamp.split("T"); var a_Date = new Array(); a_Date = a_DateTime[0].split("-"); var a_Time = new Array(); a_Time = a_DateTime[1].split(":"); var t_DateTimeGMT = new Date(); var a_Year = parseInt(a_Date[0]); t_DateTimeGMT.setYear(a_Year); var a_Month = parseInt(a_Date[1])-1; t_DateTimeGMT.setUTCMonth(a_Month); var a_Date = parseInt(a_Date[2]); t_DateTimeGMT.setUTCDate(a_Date); var a_Hour = parseInt(a_Time[0]); t_DateTimeGMT.setUTCHours(a_Hour); var a_Minute = parseInt(a_Time[1]); t_DateTimeGMT.setUTCMinutes(a_Minute); var a_Second = parseInt(a_Time[2]); t_DateTimeGMT.setUTCSeconds(a_Second); return new Date(t_DateTimeGMT.toUTCString()); } function scutils_GMTtoLMS_TimeInterval(a_TimeInterval) { var a_DateTimeGMT = new Date(a_TimeInterval); var a_Year; if(a_DateTimeGMT.getTimezoneOffset()>=0) a_Year = a_DateTimeGMT.getFullYear()-1969; else a_Year = a_DateTimeGMT.getFullYear()-1970; var a_Date = a_DateTimeGMT.getUTCDate()-1; var retDateTime = "P"+a_Year+"Y"+a_DateTimeGMT.getUTCMonth()+"M"+a_Date+"DT" +a_DateTimeGMT.getUTCHours()+"H"+a_DateTimeGMT.getUTCMinutes()+"M"+a_DateTimeGMT.getUTCSeconds()+"S"; return retDateTime; } function scutils_makeLearnerResponse(a_pageNumber, a_interactionType) { var t_interactionLearnerResponse = ""; if(a_interactionType == "choice") { var commaResponse = 0; for (var i = 0; i < g_radioDynamicEntries.length; ++i) { var pageNr = g_radioDynamicEntries[i].nPage; if (pageNr == a_pageNumber) { var idx = g_radioDynamicEntries[i].nIdx; var choiceChecked = eval("document.TestingForm.Radio" + a_pageNumber); if(!choiceChecked) choiceChecked = eval("document.TestingForm.Check" + a_pageNumber); if (choiceChecked[idx].checked && commaResponse == 0) { t_interactionLearnerResponse += g_Responses.charAt(g_radioDynamicEntries[i].nIdx); commaResponse = 1; } else if(choiceChecked[idx].checked && commaResponse==1) t_interactionLearnerResponse += "[,]" + g_Responses.charAt(g_radioDynamicEntries[i].nIdx); } } } else if(a_interactionType == "fill-in") { var commaResponse = 0; for (var i = 0; i < g_textFieldEntries.length; ++i) { var pageNr = g_textFieldEntries[i].nPage; if (pageNr == a_pageNumber) { var textFieldObj = eval("document.TestingForm." + g_textFieldEntries[i].strId); if(commaResponse == 0) { t_interactionLearnerResponse += textFieldObj.value; commaResponse =1; } else t_interactionLearnerResponse += "[,]" + textFieldObj.value; } } } else if(a_interactionType == "matching") { var commaResponse = 0; var index = 0; while(index < g_targetPointEntries.length && g_targetPointEntries[index].nPage != a_pageNumber) index++; var count = index; while(count < g_targetPointEntries.length && g_targetPointEntries[count].nPage == a_pageNumber) count++; var vector = new Array(); for(var k = index; k < count; k++) vector[k] = parseInt(g_targetPointEntries[k].nX); for(var k = index; k < count-1; k++) for(var l = k+1; l < count; l++) if(vector[l] < vector[k]) { var temp = vector[l]; vector[l] = vector[k] vector[k] = temp; } for (var i = 0; i < g_targetPointEntries.length; ++i) { var pageNr = g_targetPointEntries[i].nPage; if (pageNr == a_pageNumber) { var strLayer1 = "" + g_targetPointEntries[i].strObjectId + "Layer"; var layer1 = document.getElementById(strLayer1); var startX1 = posX(layer1); var startY1 = posY(layer1); var endX1 = startX1 + layer1.clientWidth-1; var endY1 = startY1+ layer1.clientHeight-1; var j=0; var k=0; var bIsInside = false; while(j < g_targetPointEntries.length) { var tpX = g_targetPointEntries[j].nCenterX + layout_getSlidesLeft(); var tpY = g_targetPointEntries[j].nCenterY + layout_getSlidesTop(); bIsInside = tpX >= startX1 && tpX <= endX1 && tpY >= startY1 && tpY <= endY1; if(bIsInside && commaResponse == 0) { while(k < count && g_targetPointEntries[j].nX != vector[k]) k ++; t_interactionLearnerResponse += "" + i +'[.]' + g_Responses.charAt(k);//g_targetPointEntries[j].strObjectId; commaResponse =1; break; } else if(bIsInside && commaResponse == 1) { while(k < count && g_targetPointEntries[j].nX != vector[k]) k ++; t_interactionLearnerResponse += "[,]" + i +'[.]' + g_Responses.charAt(k);//g_targetPointEntries[j].strObjectId; break; } else j++; } if(!bIsInside && commaResponse == 0) { t_interactionLearnerResponse += "" + i +'[.]'+ '-'; commaResponse =1; } else if(!bIsInside && commaResponse == 1) t_interactionLearnerResponse += "[,]" + i +'[.]'+ '-'; } } } return t_interactionLearnerResponse; } function scutils_makeInteractionPattern(a_pageNumber, a_interactionType) { var t_interactionPattern = ""; if(g_interactionType == "choice") { var commaPattern = 0; for (var i = 0; i < g_radioDynamicEntries.length; ++i) { var pageNr = g_radioDynamicEntries[i].nPage; if (pageNr == a_pageNumber) { if(g_radioDynamicEntries[i].bIsChecked && commaPattern == 0) { var idx = g_radioDynamicEntries[i].nIdx; t_interactionPattern += "" + g_Responses.charAt(idx); commaPattern = 1; } else if(g_radioDynamicEntries[i].bIsChecked && commaPattern == 1) { var idx = g_radioDynamicEntries[i].nIdx; t_interactionPattern += "[,]" + g_Responses.charAt(idx); } } } } else if(g_interactionType == "fill-in") { var commaPattern = 0; for (var i = 0; i < g_textFieldEntries.length; ++i) { var pageNr = g_textFieldEntries[i].nPage; if (pageNr == a_pageNumber) { if(commaPattern == 0) { var str = g_textFieldEntries[i].strText; t_interactionPattern += g_textFieldEntries[i].strText; commaPattern = 1; } else t_interactionPattern += "[,]" + g_textFieldEntries[i].strText; } } } else if(g_interactionType == "matching") { var commaPattern = 0; var index = 0; while(index < g_targetPointEntries.length && g_targetPointEntries[index].nPage != a_pageNumber) index++; var count = index; while(count < g_targetPointEntries.length && g_targetPointEntries[count].nPage == a_pageNumber) count++; var vector = new Array(); for(var k = index; k < count; k++) vector[k] = parseInt(g_targetPointEntries[k].nX); for(var k = index; k < count-1; k++) for(var l = k+1; l < count; l++) if(vector[l] < vector[k]) { var temp = vector[l]; vector[l] = vector[k] vector[k] = temp; } for (var i = 0; i < g_targetPointEntries.length; ++i) { var pageNr = g_targetPointEntries[i].nPage; if (pageNr == a_pageNumber) { var j=0; while(j < count && g_targetPointEntries[i].nX != vector[j]) j ++; if(commaPattern == 0) { t_interactionPattern += "" + i +'[.]'+ g_Responses.charAt(j); commaPattern = 1; } else t_interactionPattern += "[,]" + i +'[.]'+ g_Responses.charAt(j); } } } return t_interactionPattern; } function scutils_checkResumeSupported() { // sets the g_LMSResumeSupported if(g_scormEnabled && g_scormLoaded ) { var supportedInteractionsDM = doLMSGetValue("cmi.interactions._children"); var supportedScoreDM = doLMSGetValue("cmi.score._children"); if((supportedInteractionsDM != null)&&(supportedScoreDM != null)) if((supportedInteractionsDM.search("id") != -1) && (supportedInteractionsDM.search("type") != -1) && (supportedInteractionsDM.search("learner_response") != -1) && (supportedInteractionsDM.search("result") != -1) && (supportedScoreDM.search("raw") != -1 )) g_LMSResumeSupported = true; else alert(" Warning!\nYour Learning Management System dose not support course resuming.\n\nIf lesson is closed before finish all progress will be lost!"); } }
openlecturnity/os45
lecturnity/publisher/templates/era/era-B/js/scorm_utils.js
JavaScript
lgpl-3.0
26,508
// Copyright 2012 the V8 project authors. 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Flags: --allow-natives-syntax --opt var foo = (function() { return eval("(function bar() { return 1; })"); })(); foo(); foo(); %OptimizeFunctionOnNextCall(foo); foo(); assertOptimized(foo);
weolar/miniblink49
v8_7_5/test/mjsunit/regress/regress-2315.js
JavaScript
apache-2.0
1,796
__zl([{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"97":0,"98":0,"99":0},["Cedar Rapids"],["IA|Iowa"]]);
andrefyg/ziplookup
public/ziplookup/db/us/524.js
JavaScript
apache-2.0
128
/// <reference path="qunit.d.ts" /> /// <reference path="../src/code.ts" /> QUnit.module("stringLib"); test("will get vowel count", function () { var stringPlus = new StringPlus("hello"); var count = stringPlus.countVowels(); equal(count, 2, "We expect 2 vowels in hello"); }); QUnit.module("mathLib"); test("will add 5 to number", function () { var res = mathLib.add5(10); equal(res, 15, "should add 5"); }); //# sourceMappingURL=test.js.map
mukulikadey/SOEN341-Group1
chutzpah/Samples/Compilation/ExternalCompile/test/test.js
JavaScript
mit
472
/* vim: set expandtab sw=4 ts=4 sts=4: */ /** * function used in or for navigation panel * * @package phpMyAdmin-Navigation */ /** * Executed on page load */ $(function () { if (! $('#pma_navigation').length) { // Don't bother running any code if the navigation is not even on the page return; } // Do not let the page reload on submitting the fast filter $(document).on('submit', '.fast_filter', function (event) { event.preventDefault(); }); // Fire up the resize handlers new ResizeHandler(); /** * opens/closes (hides/shows) tree elements * loads data via ajax */ $('#pma_navigation_tree a.expander').live('click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); var $icon = $(this).find('img'); if ($icon.is('.ic_b_plus')) { expandTreeNode($(this)); } else { collapseTreeNode($(this)); } }); /** * Register event handler for click on the reload * navigation icon at the top of the panel */ $('#pma_navigation_reload').live('click', function (event) { event.preventDefault(); // reload icon object var $icon = $(this).find('img'); // source of the hidden throbber icon var icon_throbber_src = $('#pma_navigation .throbber').attr('src'); // source of the reload icon var icon_reload_src = $icon.attr('src'); // replace the source of the reload icon with the one for throbber $icon.attr('src', icon_throbber_src); PMA_reloadNavigation(); // after one second, put back the reload icon setTimeout(function () { $icon.attr('src', icon_reload_src); }, 1000); }); /** * Bind all "fast filter" events */ $('#pma_navigation_tree li.fast_filter span') .live('click', PMA_fastFilter.events.clear); $('#pma_navigation_tree li.fast_filter input.searchClause') .live('focus', PMA_fastFilter.events.focus) .live('blur', PMA_fastFilter.events.blur) .live('keyup', PMA_fastFilter.events.keyup); /** * Ajax handler for pagination */ $('#pma_navigation_tree div.pageselector a.ajax').live('click', function (event) { event.preventDefault(); PMA_navigationTreePagination($(this)); }); /** * Node highlighting */ $('#pma_navigation_tree.highlight li:not(.fast_filter)').live( 'mouseover', function () { if ($('li:visible', this).length === 0) { $(this).addClass('activePointer'); } } ); $('#pma_navigation_tree.highlight li:not(.fast_filter)').live( 'mouseout', function () { $(this).removeClass('activePointer'); } ); /** Create a Routine, Trigger or Event */ $('li.new_procedure a.ajax, li.new_function a.ajax').live('click', function (event) { event.preventDefault(); var dialog = new RTE.object('routine'); dialog.editorDialog(1, $(this)); }); $('li.new_trigger a.ajax').live('click', function (event) { event.preventDefault(); var dialog = new RTE.object('trigger'); dialog.editorDialog(1, $(this)); }); $('li.new_event a.ajax').live('click', function (event) { event.preventDefault(); var dialog = new RTE.object('event'); dialog.editorDialog(1, $(this)); }); /** Execute Routines */ $('li.procedure > a.ajax, li.function > a.ajax').live('click', function (event) { event.preventDefault(); var dialog = new RTE.object('routine'); dialog.executeDialog($(this)); }); /** Edit Triggers and Events */ $('li.trigger > a.ajax').live('click', function (event) { event.preventDefault(); var dialog = new RTE.object('trigger'); dialog.editorDialog(0, $(this)); }); $('li.event > a.ajax').live('click', function (event) { event.preventDefault(); var dialog = new RTE.object('event'); dialog.editorDialog(0, $(this)); }); /** Edit Routines */ $('li.procedure div a.ajax img,' + ' li.function div a.ajax img').live('click', function (event) { event.preventDefault(); var dialog = new RTE.object('routine'); dialog.editorDialog(0, $(this).parent()); }); /** Export Triggers and Events */ $('li.trigger div:eq(1) a.ajax img,' + ' li.event div:eq(1) a.ajax img' ).live('click', function (event) { event.preventDefault(); var dialog = new RTE.object(); dialog.exportDialog($(this).parent()); }); /** New index */ $('#pma_navigation_tree li.new_index a.ajax').live('click', function (event) { event.preventDefault(); var url = $(this).attr('href').substr( $(this).attr('href').indexOf('?') + 1 ) + '&ajax_request=true'; var title = PMA_messages.strAddIndex; indexEditorDialog(url, title); }); /** Edit index */ $('li.index a.ajax').live('click', function (event) { event.preventDefault(); var url = $(this).attr('href').substr( $(this).attr('href').indexOf('?') + 1 ) + '&ajax_request=true'; var title = PMA_messages.strEditIndex; indexEditorDialog(url, title); }); /** New view */ $('li.new_view a.ajax').live('click', function (event) { event.preventDefault(); PMA_createViewDialog($(this)); }); /** Hide navigation tree item */ $('a.hideNavItem.ajax').live('click', function (event) { event.preventDefault(); $.ajax({ url: $(this).attr('href') + '&ajax_request=true', success: function (data) { if (typeof data !== 'undefined' && data.success === true) { PMA_reloadNavigation(); } else { PMA_ajaxShowMessage(data.error); } } }); }); /** Display a dialog to choose hidden navigation items to show */ $('a.showUnhide.ajax').live('click', function (event) { event.preventDefault(); var $msg = PMA_ajaxShowMessage(); $.get($(this).attr('href') + '&ajax_request=1', function (data) { if (typeof data !== 'undefined' && data.success === true) { PMA_ajaxRemoveMessage($msg); var buttonOptions = {}; buttonOptions[PMA_messages.strClose] = function () { $(this).dialog("close"); }; $('<div/>') .attr('id', 'unhideNavItemDialog') .append(data.message) .dialog({ width: 400, minWidth: 200, modal: true, buttons: buttonOptions, title: PMA_messages.strUnhideNavItem, close: function () { $(this).remove(); } }); } else { PMA_ajaxShowMessage(data.error); } }); }); /** Show a hidden navigation tree item */ $('a.unhideNavItem.ajax').live('click', function (event) { event.preventDefault(); var $tr = $(this).parents('tr'); var $msg = PMA_ajaxShowMessage(); $.ajax({ url: $(this).attr('href') + '&ajax_request=true', success: function (data) { PMA_ajaxRemoveMessage($msg); if (typeof data !== 'undefined' && data.success === true) { $tr.remove(); PMA_reloadNavigation(); } else { PMA_ajaxShowMessage(data.error); } } }); }); // Add/Remove favorite table using Ajax. $(".favorite_table_anchor").live("click", function (event) { event.preventDefault(); $self = $(this); var anchor_id = $self.attr("id"); if($self.data("favtargetn") != null) if($('a[data-favtargets="' + $self.data("favtargetn") + '"]').length > 0) { $('a[data-favtargets="' + $self.data("favtargetn") + '"]').trigger('click'); return; } $.ajax({ url: $self.attr('href'), cache: false, type: 'POST', data: { favorite_tables: (window.localStorage && window.localStorage['favorite_tables'] !== undefined) ? window.localStorage['favorite_tables'] : '' }, success: function (data) { if (data.changes) { $('#pma_favorite_list').html(data.list); $('#' + anchor_id).parent().html(data.anchor); PMA_tooltip( $('#' + anchor_id), 'a', $('#' + anchor_id).attr("title") ); // Update localStorage. if (window.localStorage && window.localStorage !== undefined) { window.localStorage['favorite_tables'] = data.favorite_tables; } } else { PMA_ajaxShowMessage(data.message); } } }); }); PMA_showCurrentNavigation(); }); /** * Expands a node in navigation tree. * * @param $expandElem expander * @param callback callback function * * @returns void */ function expandTreeNode($expandElem, callback) { var $children = $expandElem.closest('li').children('div.list_container'); var $icon = $expandElem.find('img'); if ($expandElem.hasClass('loaded')) { if ($icon.is('.ic_b_plus')) { $icon.removeClass('ic_b_plus').addClass('ic_b_minus'); $children.slideDown('fast'); } if (callback && typeof callback == 'function') { callback.call(); } } else { var $throbber = $('#pma_navigation .throbber') .first() .clone() .css({visibility: 'visible', display: 'block'}) .click(false); $icon.hide(); $throbber.insertBefore($icon); loadChildNodes($expandElem, function (data) { if (typeof data !== 'undefined' && data.success === true) { var $destination = $expandElem.closest('li'); $icon.removeClass('ic_b_plus').addClass('ic_b_minus'); $destination .children('div.list_container') .slideDown('fast'); if ($destination.find('ul > li').length == 1) { $destination.find('ul > li') .find('a.expander.container') .click(); } if (callback && typeof callback == 'function') { callback.call(); } PMA_showFullName($destination); } else { PMA_ajaxShowMessage(data.error, false); } $icon.show(); $throbber.remove(); }); } $expandElem.blur(); } /** * Auto-scrolls the newly chosen database * * @param object $element The element to set to view * @param boolean $forceToTop Whether to force scroll to top * */ function scrollToView($element, $forceToTop) { var $container = $('#pma_navigation_tree_content'); var elemTop = $element.offset().top - $container.offset().top; var textHeight = 20; var scrollPadding = 20; // extra padding from top of bottom when scrolling to view if (elemTop < 0 || $forceToTop) { $container.stop().animate({ scrollTop: elemTop + $container.scrollTop() - scrollPadding }); } else if (elemTop + textHeight > $container.height()) { $container.stop().animate({ scrollTop: elemTop + textHeight - $container.height() + $container.scrollTop() + scrollPadding }); } } /** * Collapses a node in navigation tree. * * @param $expandElem expander * * @returns void */ function collapseTreeNode($expandElem) { var $children = $expandElem.closest('li').children('div.list_container'); var $icon = $expandElem.find('img'); if ($expandElem.hasClass('loaded')) { if ($icon.is('.ic_b_minus')) { $icon.removeClass('ic_b_minus').addClass('ic_b_plus'); $children.slideUp('fast'); } } $expandElem.blur(); } /** * Loads child items of a node and executes a given callback * * @param $expandElem expander * @param callback callback function * * @returns void */ function loadChildNodes($expandElem, callback) { if (!$expandElem.hasClass('expander')) { return; } var $destination = $expandElem.closest('li'); var searchClause = PMA_fastFilter.getSearchClause(); var searchClause2 = PMA_fastFilter.getSearchClause2($expandElem); var params = { aPath: $expandElem.find('span.aPath').text(), vPath: $expandElem.find('span.vPath').text(), pos: $expandElem.find('span.pos').text(), pos2_name: $expandElem.find('span.pos2_name').text(), pos2_value: $expandElem.find('span.pos2_value').text(), searchClause: searchClause, searchClause2: searchClause2 }; var url = $('#pma_navigation').find('a.navigation_url').attr('href'); $.get(url, params, function (data) { if (typeof data !== 'undefined' && data.success === true) { $expandElem.addClass('loaded'); $destination.find('div.list_container').remove(); // FIXME: Hack, there shouldn't be a list container there $destination.append(data.message); if (callback && typeof callback == 'function') { callback(data); } } else if(data.redirect_flag == "1") { window.location.href += '&session_expired=1'; window.location.reload(); } else { var $throbber = $expandElem.find('img.throbber'); $throbber.hide(); $icon = $expandElem.find('img.ic_b_plus'); $icon.show(); PMA_ajaxShowMessage(data.error, false); } }); } /** * Expand the navigation and highlight the current database or table/view * * @returns void */ function PMA_showCurrentNavigation() { var db = PMA_commonParams.get('db'); var table = PMA_commonParams.get('table'); $('#pma_navigation_tree') .find('li.selected') .removeClass('selected'); if (db) { var $dbItem = findLoadedItem( $('#pma_navigation_tree > div'), db, 'database', !table ); if ($dbItem) { var $expander = $dbItem.children('div:first').children('a.expander'); // if not loaded or loaded but collapsed if (! $expander.hasClass('loaded') || $expander.find('img').is('.ic_b_plus') ) { expandTreeNode($expander, function () { handleTableOrDb(table, $dbItem); }); } else { handleTableOrDb(table, $dbItem); } } } PMA_showFullName($('#pma_navigation_tree')); function handleTableOrDb(table, $dbItem) { if (table) { loadAndHighlightTableOrView($dbItem, table); } else { var $container = $dbItem.children('div.list_container'); var $tableContainer = $container.children('ul').children('li.tableContainer'); if ($tableContainer.length > 0) { var $expander = $tableContainer.children('div:first').children('a.expander'); expandTreeNode($expander, function () { scrollToView($dbItem, true); }); } else { scrollToView($dbItem, true); } } } function findLoadedItem($container, name, clazz, doSelect) { var ret = false; $container.children('ul').children('li').each(function () { var $li = $(this); // this is a navigation group, recurse if ($li.is('.navGroup')) { var $container = $li.children('div.list_container'); var $childRet = findLoadedItem( $container, name, clazz, doSelect ); if ($childRet) { ret = $childRet; return false; } } else { // this is a real navigation item // name and class matches if (((clazz && $li.is('.' + clazz)) || ! clazz) && $li.children('a').text() == name) { if (doSelect) { $li.addClass('selected'); } // taverse up and expand and parent navigation groups $li.parents('.navGroup').each(function () { $cont = $(this).children('div.list_container'); if (! $cont.is(':visible')) { $(this) .children('div:first') .children('a.expander') .click(); } }); ret = $li; return false; } } }); return ret; } function loadAndHighlightTableOrView($dbItem, itemName) { var $container = $dbItem.children('div.list_container'); var $expander; var $whichItem = isItemInContainer($container, itemName, 'li.table, li.view'); //If item already there in some container if ($whichItem) { //get the relevant container while may also be a subcontainer var $relatedContainer = $whichItem.closest('li.subContainer').length ? $whichItem.closest('li.subContainer') : $dbItem; $whichItem = findLoadedItem( $relatedContainer.children('div.list_container'), itemName, null, true ); //Show directly showTableOrView($whichItem, $relatedContainer.children('div:first').children('a.expander')); //else if item not there, try loading once } else { var $sub_containers = $dbItem.find('.subContainer'); //If there are subContainers i.e. tableContainer or viewContainer if($sub_containers.length > 0) { var $containers = new Array(); $sub_containers.each(function (index) { $containers[index] = $(this); $expander = $containers[index] .children('div:first') .children('a.expander'); collapseTreeNode($expander); loadAndShowTableOrView($expander, $containers[index], itemName); }); // else if no subContainers } else { $expander = $dbItem .children('div:first') .children('a.expander'); collapseTreeNode($expander); loadAndShowTableOrView($expander, $dbItem, itemName); } } } function loadAndShowTableOrView($expander, $relatedContainer, itemName) { loadChildNodes($expander, function (data) { var $whichItem = findLoadedItem( $relatedContainer.children('div.list_container'), itemName, null, true ); if ($whichItem) { showTableOrView($whichItem, $expander); } }); } function showTableOrView($whichItem, $expander) { expandTreeNode($expander, function (data) { if ($whichItem) { scrollToView($whichItem, false); } }); } function isItemInContainer($container, name, clazz) { var $whichItem = null; $items = $container.find(clazz); var found = false; $items.each(function () { if ($(this).children('a').text() == name) { $whichItem = $(this); return false; } }); return $whichItem; } } /** * Reloads the whole navigation tree while preserving its state * * @param function the callback function * @return void */ function PMA_reloadNavigation(callback) { var params = { reload: true, pos: $('#pma_navigation_tree').find('a.expander:first > span.pos').text() }; // Traverse the navigation tree backwards to generate all the actual // and virtual paths, as well as the positions in the pagination at // various levels, if necessary. var count = 0; $('#pma_navigation_tree').find('a.expander:visible').each(function () { if ($(this).find('img').is('.ic_b_minus') && $(this).closest('li').find('div.list_container .ic_b_minus').length === 0 ) { params['n' + count + '_aPath'] = $(this).find('span.aPath').text(); params['n' + count + '_vPath'] = $(this).find('span.vPath').text(); var pos2_name = $(this).find('span.pos2_name').text(); if (! pos2_name) { pos2_name = $(this) .parent() .parent() .find('span.pos2_name:last') .text(); } var pos2_value = $(this).find('span.pos2_value').text(); if (! pos2_value) { pos2_value = $(this) .parent() .parent() .find('span.pos2_value:last') .text(); } params['n' + count + '_pos2_name'] = pos2_name; params['n' + count + '_pos2_value'] = pos2_value; params['n' + count + '_pos3_name'] = $(this).find('span.pos3_name').text(); params['n' + count + '_pos3_value'] = $(this).find('span.pos3_value').text(); count++; } }); var url = $('#pma_navigation').find('a.navigation_url').attr('href'); $.post(url, params, function (data) { if (typeof data !== 'undefined' && data.success) { $('#pma_navigation_tree').html(data.message).children('div').show(); PMA_showCurrentNavigation(); // Fire the callback, if any if (typeof callback === 'function') { callback.call(); } } else { PMA_ajaxShowMessage(data.error); } }); } /** * Handles any requests to change the page in a branch of a tree * * This can be called from link click or select change event handlers * * @param object $this A jQuery object that points to the element that * initiated the action of changing the page * * @return void */ function PMA_navigationTreePagination($this) { var $msgbox = PMA_ajaxShowMessage(); var isDbSelector = $this.closest('div.pageselector').is('.dbselector'); var url, params; if ($this[0].tagName == 'A') { url = $this.attr('href'); params = 'ajax_request=true'; } else { // tagName == 'SELECT' url = 'navigation.php'; params = $this.closest("form").serialize() + '&ajax_request=true'; } var searchClause = PMA_fastFilter.getSearchClause(); if (searchClause) { params += '&searchClause=' + encodeURIComponent(searchClause); } if (isDbSelector) { params += '&full=true'; } else { var searchClause2 = PMA_fastFilter.getSearchClause2($this); if (searchClause2) { params += '&searchClause2=' + encodeURIComponent(searchClause2); } } $.post(url, params, function (data) { PMA_ajaxRemoveMessage($msgbox); if (typeof data !== 'undefined' && data.success) { if (isDbSelector) { var val = PMA_fastFilter.getSearchClause(); $('#pma_navigation_tree') .html(data.message) .children('div') .show(); if (val) { $('#pma_navigation_tree') .find('li.fast_filter input.searchClause') .val(val); } } else { var $parent = $this.closest('div.list_container').parent(); var val = PMA_fastFilter.getSearchClause2($this); $this.closest('div.list_container').html( $(data.message).children().show() ); if (val) { $parent.find('li.fast_filter input.searchClause').val(val); } $parent.find('span.pos2_value:first').text( $parent.find('span.pos2_value:last').text() ); $parent.find('span.pos3_value:first').text( $parent.find('span.pos3_value:last').text() ); } } else { PMA_ajaxShowMessage(data.error); } }); } /** * @var ResizeHandler Custom object that manages the resizing of the navigation * * XXX: Must only be ever instanciated once * XXX: Inside event handlers the 'this' object is accessed as 'event.data.resize_handler' */ var ResizeHandler = function () { /** * Whether the user has initiated a resize operation */ this.active = false; /** * @var int panel_width Used by the collapser to know where to go * back to when uncollapsing the panel */ this.panel_width = 0; /** * @var string left Used to provide support for RTL languages */ this.left = $('html').attr('dir') == 'ltr' ? 'left' : 'right'; /** * Adjusts the width of the navigation panel to the specified value * * @param int pos Navigation width in pixels * * @return void */ this.setWidth = function (pos) { var $resizer = $('#pma_navigation_resizer'); var resizer_width = $resizer.width(); var $collapser = $('#pma_navigation_collapser'); $('#pma_navigation').width(pos); $('body').css('margin-' + this.left, pos + 'px'); $("#floating_menubar") .css('margin-' + this.left, (pos + resizer_width) + 'px'); $resizer.css(this.left, pos + 'px'); if (pos === 0) { $collapser .css(this.left, pos + resizer_width) .html(this.getSymbol(pos)) .prop('title', PMA_messages.strShowPanel); } else { $collapser .css(this.left, pos) .html(this.getSymbol(pos)) .prop('title', PMA_messages.strHidePanel); } setTimeout(function () { $(window).trigger('resize'); }, 4); }; /** * Returns the horizontal position of the mouse, * relative to the outer side of the navigation panel * * @param int pos Navigation width in pixels * * @return void */ this.getPos = function (event) { var pos = event.pageX; var windowWidth = $(window).width(); var windowScroll = $(window).scrollLeft(); pos = pos - windowScroll; if (this.left != 'left') { pos = windowWidth - event.pageX; } if (pos < 0) { pos = 0; } else if (pos + 100 >= windowWidth) { pos = windowWidth - 100; } else { this.panel_width = 0; } return pos; }; /** * Returns the HTML code for the arrow symbol used in the collapser * * @param int width The width of the panel * * @return string */ this.getSymbol = function (width) { if (this.left == 'left') { if (width === 0) { return '&rarr;'; } else { return '&larr;'; } } else { if (width === 0) { return '&larr;'; } else { return '&rarr;'; } } }; /** * Event handler for initiating a resize of the panel * * @param object e Event data (contains a reference to resizeHandler) * * @return void */ this.mousedown = function (event) { event.preventDefault(); event.data.resize_handler.active = true; $('body').css('cursor', 'col-resize'); }; /** * Event handler for terminating a resize of the panel * * @param object e Event data (contains a reference to resizeHandler) * * @return void */ this.mouseup = function (event) { if (event.data.resize_handler.active) { event.data.resize_handler.active = false; $('body').css('cursor', ''); $.cookie('pma_navi_width', event.data.resize_handler.getPos(event)); $('#topmenu').menuResizer('resize'); } }; /** * Event handler for updating the panel during a resize operation * * @param object e Event data (contains a reference to resizeHandler) * * @return void */ this.mousemove = function (event) { if (event.data && event.data.resize_handler && event.data.resize_handler.active) { event.preventDefault(); var pos = event.data.resize_handler.getPos(event); event.data.resize_handler.setWidth(pos); } if($('#sticky_columns').length !== 0) { handleStickyColumns(); } }; /** * Event handler for collapsing the panel * * @param object e Event data (contains a reference to resizeHandler) * * @return void */ this.collapse = function (event) { event.preventDefault(); event.data.active = false; var panel_width = event.data.resize_handler.panel_width; var width = $('#pma_navigation').width(); if (width === 0 && panel_width === 0) { panel_width = 240; } event.data.resize_handler.setWidth(panel_width); event.data.resize_handler.panel_width = width; }; /** * Event handler for resizing the navigation tree height on window resize * * @return void */ this.treeResize = function (event) { var $nav = $("#pma_navigation"), $nav_tree = $("#pma_navigation_tree"), $nav_header = $("#pma_navigation_header"), $nav_tree_content = $("#pma_navigation_tree_content"); $nav_tree.height($nav.height() - $nav_header.height()); if ($nav_tree_content.length > 0) { $nav_tree_content.height($nav_tree.height() - $nav_tree_content.position().top); } else { //TODO: in fast filter search response there is no #pma_navigation_tree_content, needs to be added in php $nav_tree.css({ 'overflow-y': 'auto' }); } }; /* Initialisation section begins here */ if ($.cookie('pma_navi_width')) { // If we have a cookie, set the width of the panel to its value var pos = Math.abs(parseInt($.cookie('pma_navi_width'), 10) || 0); this.setWidth(pos); $('#topmenu').menuResizer('resize'); } // Register the events for the resizer and the collapser $('#pma_navigation_resizer') .live('mousedown', {'resize_handler': this}, this.mousedown); $(document) .bind('mouseup', {'resize_handler': this}, this.mouseup) .bind('mousemove', {'resize_handler': this}, $.throttle(this.mousemove, 4)); var $collapser = $('#pma_navigation_collapser'); $collapser.live('click', {'resize_handler': this}, this.collapse); // Add the correct arrow symbol to the collapser $collapser.html(this.getSymbol($('#pma_navigation').width())); // Fix navigation tree height $(window).on('resize', this.treeResize); // need to call this now and then, browser might decide // to show/hide horizontal scrollbars depending on page content width setInterval(this.treeResize, 2000); this.treeResize(); }; // End of ResizeHandler /** * @var object PMA_fastFilter Handles the functionality that allows filtering * of the items in a branch of the navigation tree */ var PMA_fastFilter = { /** * Construct for the asynchronous fast filter functionality * * @param object $this A jQuery object pointing to the list container * which is the nearest parent of the fast filter * @param string searchClause The query string for the filter * * @return new PMA_fastFilter.filter object */ filter: function ($this, searchClause) { /** * @var object $this A jQuery object pointing to the list container * which is the nearest parent of the fast filter */ this.$this = $this; /** * @var bool searchClause The query string for the filter */ this.searchClause = searchClause; /** * @var object $clone A clone of the original contents * of the navigation branch before * the fast filter was applied */ this.$clone = $this.clone(); /** * @var bool swapped Whether the user clicked on the "N other results" link */ this.swapped = false; /** * @var object xhr A reference to the ajax request that is currently running */ this.xhr = null; /** * @var int timeout Used to delay the request for asynchronous search */ this.timeout = null; var $filterInput = $this.find('li.fast_filter input.searchClause'); if ($filterInput.length !== 0 && $filterInput.val() !== '' && $filterInput.val() != $filterInput[0].defaultValue ) { this.request(); } }, /** * Gets the query string from the database fast filter form * * @return string */ getSearchClause: function () { var retval = ''; var $input = $('#pma_navigation_tree') .find('li.fast_filter.db_fast_filter input.searchClause'); if ($input.length && $input.val() != $input[0].defaultValue) { retval = $input.val(); } return retval; }, /** * Gets the query string from a second level item's fast filter form * The retrieval is done by trasversing the navigation tree backwards * * @return string */ getSearchClause2: function ($this) { var $filterContainer = $this.closest('div.list_container'); var $filterInput = $([]); if ($filterContainer .children('li.fast_filter:not(.db_fast_filter) input.searchClause') .length !== 0) { $filterInput = $filterContainer .children('li.fast_filter:not(.db_fast_filter) input.searchClause'); } var searchClause2 = ''; if ($filterInput.length !== 0 && $filterInput.first().val() != $filterInput[0].defaultValue ) { searchClause2 = $filterInput.val(); } return searchClause2; }, /** * @var hash events A list of functions that are bound to DOM events * at the top of this file */ events: { focus: function (event) { var $obj = $(this).closest('div.list_container'); if (! $obj.data('fastFilter')) { $obj.data( 'fastFilter', new PMA_fastFilter.filter($obj, $(this).val()) ); } if ($(this).val() == this.defaultValue) { $(this).val(''); } else { $(this).select(); } }, blur: function (event) { if ($(this).val() === '') { $(this).val(this.defaultValue); } var $obj = $(this).closest('div.list_container'); if ($(this).val() == this.defaultValue && $obj.data('fastFilter')) { $obj.data('fastFilter').restore(); } }, keyup: function (event) { var $obj = $(this).closest('div.list_container'); var str = ''; if ($(this).val() != this.defaultValue && $(this).val() !== '') { $obj.find('div.pageselector').hide(); str = $(this).val(); } /** * FIXME at the server level a value match is done while on * the client side it is a regex match. These two should be aligned */ // regex used for filtering. var regex; try { regex = new RegExp(str, 'i'); } catch (err) { return; } // this is the div that houses the items to be filtered by this filter. var outerContainer; if ($(this).closest('li.fast_filter').is('.db_fast_filter')) { outerContainer = $('#pma_navigation_tree_content'); } else { outerContainer = $obj; } // filters items that are directly under the div as well as grouped in // groups. Does not filter child items (i.e. a database search does // not filter tables) var item_filter = function($curr) { $curr.children('ul').children('li.navGroup').each(function() { $(this).children('div.list_container').each(function() { item_filter($(this)); // recursive }); }); $curr.children('ul').children('li').children('a').not('.container').each(function() { if (regex.test($(this).text())) { $(this).parent().show().removeClass('hidden'); } else { $(this).parent().hide().addClass('hidden'); } }); }; item_filter(outerContainer); // hides containers that does not have any visible children var container_filter = function ($curr) { $curr.children('ul').children('li.navGroup').each(function() { var $group = $(this); $group.children('div.list_container').each(function() { container_filter($(this)); // recursive }); $group.show().removeClass('hidden'); if ($group.children('div.list_container').children('ul') .children('li').not('.hidden').length === 0) { $group.hide().addClass('hidden'); } }); }; container_filter(outerContainer); if ($(this).val() != this.defaultValue && $(this).val() !== '') { if (! $obj.data('fastFilter')) { $obj.data( 'fastFilter', new PMA_fastFilter.filter($obj, $(this).val()) ); } else { $obj.data('fastFilter').update($(this).val()); } } else if ($obj.data('fastFilter')) { $obj.data('fastFilter').restore(true); } }, clear: function (event) { event.stopPropagation(); // Clear the input and apply the fast filter with empty input var filter = $(this).closest('div.list_container').data('fastFilter'); if (filter) { filter.restore(); } var value = $(this).prev()[0].defaultValue; $(this).prev().val(value).trigger('keyup'); } } }; /** * Handles a change in the search clause * * @param string searchClause The query string for the filter * * @return void */ PMA_fastFilter.filter.prototype.update = function (searchClause) { if (this.searchClause != searchClause) { this.searchClause = searchClause; this.$this.find('.moreResults').remove(); this.request(); } }; /** * After a delay of 250mS, initiates a request to retrieve search results * Multiple calls to this function will always abort the previous request * * @return void */ PMA_fastFilter.filter.prototype.request = function () { var self = this; clearTimeout(self.timeout); if (self.$this.find('li.fast_filter').find('img.throbber').length === 0) { self.$this.find('li.fast_filter').append( $('<div class="throbber"></div>').append( $('#pma_navigation_content') .find('img.throbber') .clone() .css({visibility: 'visible', display: 'block'}) ) ); } self.timeout = setTimeout(function () { if (self.xhr) { self.xhr.abort(); } var url = $('#pma_navigation').find('a.navigation_url').attr('href'); var results = self.$this.find('li:not(.hidden):not(.fast_filter):not(.navGroup)').not('[class^=new]').not('[class^=warp_link]').length; var params = self.$this.find('> ul > li > form.fast_filter').first().serialize() + "&results=" + results; if (self.$this.find('> ul > li > form.fast_filter:first input[name=searchClause]').length === 0) { var $input = $('#pma_navigation_tree').find('li.fast_filter.db_fast_filter input.searchClause'); if ($input.length && $input.val() != $input[0].defaultValue) { params += '&searchClause=' + encodeURIComponent($input.val()); } } self.xhr = $.ajax({ url: url, type: 'post', dataType: 'json', data: params, complete: function (jqXHR) { var data = $.parseJSON(jqXHR.responseText); self.$this.find('li.fast_filter').find('div.throbber').remove(); if (data && data.results) { var $listItem = $('<li />', {'class': 'moreResults'}) .appendTo(self.$this.find('li.fast_filter')); $('<a />', {href: '#'}) .text(data.results) .appendTo($listItem) .click(function (event) { event.preventDefault(); self.swap.apply(self, [data.message]); }); } } }); }, 250); }; /** * Replaces the contents of the navigation branch with the search results * * @param string list The search results * * @return void */ PMA_fastFilter.filter.prototype.swap = function (list) { this.swapped = true; this.$this .html($(list).html()) .children() .show() .end() .find('li.fast_filter input.searchClause') .val(this.searchClause); this.$this.data('fastFilter', this); }; /** * Restores the navigation to the original state after the fast filter is cleared * * @param bool focus Whether to also focus the input box of the fast filter * * @return void */ PMA_fastFilter.filter.prototype.restore = function (focus) { if (this.swapped) { this.swapped = false; this.$this.html(this.$clone.html()).children().show(); this.$this.data('fastFilter', this); if (focus) { this.$this.find('li.fast_filter input.searchClause').focus(); } } this.searchClause = ''; this.$this.find('.moreResults').remove(); this.$this.find('div.pageselector').show(); this.$this.find('div.throbber').remove(); }; /** * Show full name when cursor hover and name not shown completely * * @param object $containerELem Container element * * @return void */ function PMA_showFullName($containerELem) { $containerELem.find('.hover_show_full').mouseenter(function() { /** mouseenter */ var $this = $(this); var thisOffset = $this.offset(); if($this.text() == '') return; var $parent = $this.parent(); if( ($parent.offset().left + $parent.outerWidth()) < (thisOffset.left + $this.outerWidth())) { var $fullNameLayer = $('#full_name_layer'); if($fullNameLayer.length == 0) { $('body').append('<div id="full_name_layer" class="hide"></div>'); $('#full_name_layer').mouseleave(function() { /** mouseleave */ $(this).addClass('hide') .removeClass('hovering'); }).mouseenter(function() { /** mouseenter */ $(this).addClass('hovering'); }); $fullNameLayer = $('#full_name_layer'); } $fullNameLayer.removeClass('hide'); $fullNameLayer.css({left: thisOffset.left, top: thisOffset.top}); $fullNameLayer.html($this.clone()); setTimeout(function() { if(! $fullNameLayer.hasClass('hovering')) { $fullNameLayer.trigger('mouseleave'); } }, 200); } }); }
Frostbit/frostbit.cz
web/phpmyadmin/js/navigation.js
JavaScript
mit
45,950
"use strict"; module.exports = function(redisClient, module) { module.setAdd = function(key, value, callback) { callback = callback || function() {}; redisClient.sadd(key, value, function(err) { callback(err); }); }; module.setsAdd = function(keys, value, callback) { callback = callback || function() {}; var multi = redisClient.multi(); for (var i=0; i<keys.length; ++i) { multi.sadd(keys[i], value); } multi.exec(function(err) { callback(err); }); }; module.setRemove = function(key, value, callback) { redisClient.srem(key, value, callback); }; module.setsRemove = function(keys, value, callback) { callback = callback || function() {}; var multi = redisClient.multi(); for(var i=0; i<keys.length; ++i) { multi.srem(keys[i], value); } multi.exec(function(err, res) { callback(err); }); }; module.isSetMember = function(key, value, callback) { redisClient.sismember(key, value, function(err, result) { if(err) { return callback(err); } callback(null, result === 1); }); }; module.isSetMembers = function(key, values, callback) { var multi = redisClient.multi(); for (var i=0; i<values.length; ++i) { multi.sismember(key, values[i]); } execSetMembers(multi, callback); }; module.isMemberOfSets = function(sets, value, callback) { var multi = redisClient.multi(); for (var i = 0; i < sets.length; ++i) { multi.sismember(sets[i], value); } execSetMembers(multi, callback); }; function execSetMembers(multi, callback) { multi.exec(function(err, results) { if (err) { return callback(err); } for (var i=0; i<results.length; ++i) { results[i] = results[i] === 1; } callback(null, results); }); } module.getSetMembers = function(key, callback) { redisClient.smembers(key, callback); }; module.getSetsMembers = function(keys, callback) { var multi = redisClient.multi(); for (var i=0; i<keys.length; ++i) { multi.smembers(keys[i]); } multi.exec(callback); }; module.setCount = function(key, callback) { redisClient.scard(key, callback); }; module.setRemoveRandom = function(key, callback) { redisClient.spop(key, callback); }; return module; };
cablelabs/dev-portal
src/database/redis/sets.js
JavaScript
mit
2,212
/** * Module requirements. */ require('should'); var Table = require('../'); /** * Tests. */ module.exports = { 'test complete table': function (){ var table = new Table({ head: ['Rel', 'Change', 'By', 'When'] , style: { 'padding-left': 1 , 'padding-right': 1 , head: [] , border: [] } , colWidths: [6, 21, 25, 17] }); table.push( ['v0.1', 'Testing something cool', '[email protected]', '7 minutes ago'] , ['v0.1', 'Testing something cool', '[email protected]', '8 minutes ago'] ); var expected = [ '┌──────┬─────────────────────┬─────────────────────────┬─────────────────┐' , '│ Rel │ Change │ By │ When │' , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤' , '│ v0.1 │ Testing something … │ [email protected] │ 7 minutes ago │' , '├──────┼─────────────────────┼─────────────────────────┼─────────────────┤' , '│ v0.1 │ Testing something … │ [email protected] │ 8 minutes ago │' , '└──────┴─────────────────────┴─────────────────────────┴─────────────────┘' ]; table.toString().should.eql(expected.join("\n")); }, 'test width property': function (){ var table = new Table({ head: ['Cool'], style: { head: [], border: [] } }); table.width.should.eql(8); }, 'test vertical table output': function() { var table = new Table({ style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); // clear styles to prevent color output table.push( {'v0.1': 'Testing something cool'} , {'v0.1': 'Testing something cool'} ); var expected = [ '┌────┬──────────────────────┐' , '│v0.1│Testing something cool│' , '├────┼──────────────────────┤' , '│v0.1│Testing something cool│' , '└────┴──────────────────────┘' ]; table.toString().should.eql(expected.join("\n")); }, 'test cross table output': function() { var table = new Table({ head: ["", "Header 1", "Header 2"], style: {'padding-left':0, 'padding-right':0, head:[], border:[]} }); // clear styles to prevent color output table.push( {"Header 3": ['v0.1', 'Testing something cool'] } , {"Header 4": ['v0.1', 'Testing something cool'] } ); var expected = [ '┌────────┬────────┬──────────────────────┐' , '│ │Header 1│Header 2 │' , '├────────┼────────┼──────────────────────┤' , '│Header 3│v0.1 │Testing something cool│' , '├────────┼────────┼──────────────────────┤' , '│Header 4│v0.1 │Testing something cool│' , '└────────┴────────┴──────────────────────┘' ]; table.toString().should.eql(expected.join("\n")); }, 'test table colors': function(){ var table = new Table({ head: ['Rel', 'By'], style: {head: ['red'], border: ['grey']} }); var off = '\u001b[39m' , red = '\u001b[31m' , orange = '\u001b[38;5;221m' , grey = '\u001b[90m' , c256s = orange + 'v0.1' + off; table.push( [c256s, '[email protected]'] ); var expected = [ grey + '┌──────┬──────────────────┐' + off , grey + '│' + off + red + ' Rel ' + off + grey + '│' + off + red + ' By ' + off + grey + '│' + off , grey + '├──────┼──────────────────┤' + off , grey + '│' + off + ' ' + c256s + ' ' + grey + '│' + off + ' [email protected] ' + grey + '│' + off , grey + '└──────┴──────────────────┘' + off ]; table.toString().should.eql(expected.join("\n")); }, 'test custom chars': function (){ var table = new Table({ chars: { 'top': '═' , 'top-mid': '╤' , 'top-left': '╔' , 'top-right': '╗' , 'bottom': '═' , 'bottom-mid': '╧' , 'bottom-left': '╚' , 'bottom-right': '╝' , 'left': '║' , 'left-mid': '╟' , 'right': '║' , 'right-mid': '╢' }, style: { head: [] , border: [] } }); table.push( ['foo', 'bar', 'baz'] , ['frob', 'bar', 'quuz'] ); var expected = [ '╔══════╤═════╤══════╗' , '║ foo │ bar │ baz ║' , '╟──────┼─────┼──────╢' , '║ frob │ bar │ quuz ║' , '╚══════╧═════╧══════╝' ]; table.toString().should.eql(expected.join("\n")); }, 'test compact shortand': function (){ var table = new Table({ style: { head: [] , border: [] , compact : true } }); table.push( ['foo', 'bar', 'baz'] , ['frob', 'bar', 'quuz'] ); var expected = [ '┌──────┬─────┬──────┐' , '│ foo │ bar │ baz │' , '│ frob │ bar │ quuz │' , '└──────┴─────┴──────┘' ]; table.toString().should.eql(expected.join("\n")); }, 'test compact empty mid line': function (){ var table = new Table({ chars: { 'mid': '' , 'left-mid': '' , 'mid-mid': '' , 'right-mid': '' }, style: { head: [] , border: [] } }); table.push( ['foo', 'bar', 'baz'] , ['frob', 'bar', 'quuz'] ); var expected = [ '┌──────┬─────┬──────┐' , '│ foo │ bar │ baz │' , '│ frob │ bar │ quuz │' , '└──────┴─────┴──────┘' ]; table.toString().should.eql(expected.join("\n")); }, 'test decoration lines disabled': function (){ var table = new Table({ chars: { 'top': '' , 'top-mid': '' , 'top-left': '' , 'top-right': '' , 'bottom': '' , 'bottom-mid': '' , 'bottom-left': '' , 'bottom-right': '' , 'left': '' , 'left-mid': '' , 'mid': '' , 'mid-mid': '' , 'right': '' , 'right-mid': '' , 'middle': ' ' // a single space }, style: { head: [] , border: [] , 'padding-left': 0 , 'padding-right': 0 } }); table.push( ['foo', 'bar', 'baz'] , ['frobnicate', 'bar', 'quuz'] ); var expected = [ 'foo bar baz ' , 'frobnicate bar quuz' ]; table.toString().should.eql(expected.join("\n")); }, };
portlandcodeschool/js-night
testing-lessons/mocha-node-assert/node_modules/qunit/node_modules/cli-table/test/index.test.js
JavaScript
mit
8,121
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.services' is found in services.js // 'starter.controllers' is found in controllers.js angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'auth0', 'angular-storage', 'angular-jwt', 'firebase']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if(window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }) .config(function($stateProvider, $urlRouterProvider, authProvider, $httpProvider, jwtInterceptorProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider // This is the Login state .state('login', { url: "/login", templateUrl: "templates/login.html", controller: "LoginCtrl" }) // setup an abstract state for the tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html", // The tab requires user login data: { requiresLogin: true } }) // Each tab has its own nav history stack: .state('tab.friends', { url: '/friends', views: { 'tab-friends': { templateUrl: 'templates/tab-friends.html', controller: 'FriendsCtrl' } } }) .state('tab.friend-detail', { url: '/friend/:friendId', views: { 'tab-friends': { templateUrl: 'templates/friend-detail.html', controller: 'FriendDetailCtrl' } } }) .state('tab.account', { url: '/account', views: { 'tab-account': { templateUrl: 'templates/tab-account.html', controller: 'AccountCtrl' } } }); // Configure Auth0 authProvider.init({ domain: AUTH0_DOMAIN, clientID: AUTH0_CLIENT_ID, loginState: 'login' }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/tab/friends'); jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) { var idToken = store.get('token'); var refreshToken = store.get('refreshToken'); if (!idToken || !refreshToken) { return null; } if (jwtHelper.isTokenExpired(idToken)) { return auth.refreshIdToken(refreshToken).then(function(idToken) { store.set('token', idToken); return idToken; }); } else { return idToken; } } $httpProvider.interceptors.push('jwtInterceptor'); }).run(function($rootScope, auth, store) { $rootScope.$on('$locationChangeStart', function() { if (!auth.isAuthenticated) { var token = store.get('token'); if (token) { auth.authenticate(store.get('profile'), token); } } }); });
jafarsidik/auth0-ionic
examples/firebase-sample/www/js/app.js
JavaScript
mit
3,452
'use strict'; require('../common'); module.exports = function tick(x, cb) { function ontick() { if (--x === 0) { if (typeof cb === 'function') cb(); } else { setImmediate(ontick); } } setImmediate(ontick); };
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/async-hooks/tick.js
JavaScript
mit
240
// flow-typed signature: 61bbfd78d3b71a2605614708a445823a // flow-typed version: <<STUB>>/eslint-plugin-promise_v^3.4.0/flow_v0.37.4 /** * This is an autogenerated libdef stub for: * * 'eslint-plugin-promise' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'eslint-plugin-promise' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'eslint-plugin-promise/rules/always-return' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/avoid-new' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/catch-or-return' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/has-promise-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-inside-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-inside-promise' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-named-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/lib/is-promise' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-callback-in-promise' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-native' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-nesting' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-promise-in-callback' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/no-return-wrap' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/param-names' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/prefer-await-to-callbacks' { declare module.exports: any; } declare module 'eslint-plugin-promise/rules/prefer-await-to-then' { declare module.exports: any; } // Filename aliases declare module 'eslint-plugin-promise/index' { declare module.exports: $Exports<'eslint-plugin-promise'>; } declare module 'eslint-plugin-promise/index.js' { declare module.exports: $Exports<'eslint-plugin-promise'>; } declare module 'eslint-plugin-promise/rules/always-return.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/always-return'>; } declare module 'eslint-plugin-promise/rules/avoid-new.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/avoid-new'>; } declare module 'eslint-plugin-promise/rules/catch-or-return.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/catch-or-return'>; } declare module 'eslint-plugin-promise/rules/lib/has-promise-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/has-promise-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-inside-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-inside-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-inside-promise.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-inside-promise'>; } declare module 'eslint-plugin-promise/rules/lib/is-named-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-named-callback'>; } declare module 'eslint-plugin-promise/rules/lib/is-promise.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/lib/is-promise'>; } declare module 'eslint-plugin-promise/rules/no-callback-in-promise.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-callback-in-promise'>; } declare module 'eslint-plugin-promise/rules/no-native.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-native'>; } declare module 'eslint-plugin-promise/rules/no-nesting.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-nesting'>; } declare module 'eslint-plugin-promise/rules/no-promise-in-callback.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-promise-in-callback'>; } declare module 'eslint-plugin-promise/rules/no-return-wrap.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/no-return-wrap'>; } declare module 'eslint-plugin-promise/rules/param-names.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/param-names'>; } declare module 'eslint-plugin-promise/rules/prefer-await-to-callbacks.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/prefer-await-to-callbacks'>; } declare module 'eslint-plugin-promise/rules/prefer-await-to-then.js' { declare module.exports: $Exports<'eslint-plugin-promise/rules/prefer-await-to-then'>; }
SiDevesh/Bootleg
flow-typed/npm/eslint-plugin-promise_vx.x.x.js
JavaScript
mit
5,236
PIXI.FireFilter = function(width, height, texture) { PIXI.AbstractFilter.call( this ); this.passes = [this]; var d = new Date(); var dates = [ d.getFullYear(), // the year (four digits) d.getMonth(), // the month (from 0-11) d.getDate(), // the day of the month (from 1-31) d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() ]; this.uniforms = { resolution: { type: 'f2', value: { x: width, y: height }}, mouse: { type: 'f2', value: { x: 0, y: 0 }}, time: { type: 'f', value: 1 } }; // http://glsl.heroku.com/e#11707.0 // Heroku shader conversion this.fragmentSrc = [ "#ifdef GL_ES", "precision mediump float;", "#endif", "uniform float time;", "uniform vec2 mouse;", "uniform vec2 resolution;", "vec3 iResolution = vec3(resolution.x,resolution.y,100.);", "vec4 iMouse = vec4(mouse.x,mouse.y,5.,5.);", "float iGlobalTime = time;", "uniform sampler2D iChannel0;", "// by @301z", "float rand(vec2 n) {", "return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);", "}", "// Genera ruido en función de las coordenadas del pixel", "float noise(vec2 n) {", "const vec2 d = vec2(0.0, 1.0);", "vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));", "return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);", "}", "// Fractional Brownian Amplitude. Suma varias capas de ruido.", "float fbm(vec2 n) {", "float total = 0.0, amplitude = 1.0;", "for (int i = 0; i < 4; i++) {", "total += noise(n) * amplitude;", "n += n;", "amplitude *= 0.5;", "}", "return total;", "}", "void main() {", "// Colores", "const vec3 c1 = vec3(0.5, 0.0, 0.1); // Rojo oscuro.", "const vec3 c2 = vec3(0.9, 0.0, 0.0); // Rojo claro.", "const vec3 c3 = vec3(0.2, 0.0, 0.0); // Rojo oscuro.", "const vec3 c4 = vec3(1.0, 0.9, 0.0); // Amarillo.", "const vec3 c5 = vec3(0.1); // Gris oscuro.", "const vec3 c6 = vec3(0.9); // Gris claro.", "vec2 p = gl_FragCoord.xy * 8.0 / iResolution.xx; // Desfasa las coordenadas para que haya más cambio de un resultado a los colindantes.", "float q = fbm(p - iGlobalTime * 0.1); // Ruido con offset para el movimiento.", "vec2 r = vec2(fbm(p + q + iGlobalTime * 0.7 - p.x - p.y), fbm(p + q - iGlobalTime * 0.4));", "vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);", "gl_FragColor = vec4(c *", "cos(1.57 * gl_FragCoord.y / iResolution.y), // Gradiente más ocuro arriba.", "1.0);", "}"]; } PIXI.FireFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); PIXI.FireFilter.prototype.constructor = PIXI.FireFilter; Object.defineProperty(PIXI.FireFilter.prototype, 'iGlobalTime', { get: function() { return this.uniforms.time.value; }, set: function(value) { this.uniforms.time.value = value; } });
boniatillo-com/PhaserEditor
source/phasereditor/phasereditor.resources.phaser.examples/phaser-examples-master/examples/wip/book/fire.js
JavaScript
epl-1.0
2,836
/* Copyright (c) 2007, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.3.0 */ /* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ /** * The animation module provides allows effects to be added to HTMLElements. * @module animation * @requires yahoo, event, dom */ /** * * Base animation class that provides the interface for building animated effects. * <p>Usage: var myAnim = new YAHOO.util.Anim(el, { width: { from: 10, to: 100 } }, 1, YAHOO.util.Easing.easeOut);</p> * @class Anim * @namespace YAHOO.util * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @requires YAHOO.util.CustomEvent * @constructor * @param {String | HTMLElement} el Reference to the element that will be animated * @param {Object} attributes The attribute(s) to be animated. * Each attribute is an object with at minimum a "to" or "by" member defined. * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). * All attribute names use camelCase. * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) */ YAHOO.util.Anim = function(el, attributes, duration, method) { if (!el) { YAHOO.log('element required to create Anim instance', 'error', 'Anim'); } this.init(el, attributes, duration, method); }; YAHOO.util.Anim.prototype = { /** * Provides a readable name for the Anim instance. * @method toString * @return {String} */ toString: function() { var el = this.getEl(); var id = el.id || el.tagName || el; return ("Anim " + id); }, patterns: { // cached for performance noNegatives: /width|height|opacity|padding/i, // keep at zero or above offsetAttribute: /^((width|height)|(top|left))$/, // use offsetValue as default defaultUnit: /width|height|top$|bottom$|left$|right$/i, // use 'px' by default offsetUnit: /\d+(em|%|en|ex|pt|in|cm|mm|pc)$/i // IE may return these, so convert these to offset }, /** * Returns the value computed by the animation's "method". * @method doMethod * @param {String} attr The name of the attribute. * @param {Number} start The value this attribute should start from for this animation. * @param {Number} end The value this attribute should end at for this animation. * @return {Number} The Value to be applied to the attribute. */ doMethod: function(attr, start, end) { return this.method(this.currentFrame, start, end - start, this.totalFrames); }, /** * Applies a value to an attribute. * @method setAttribute * @param {String} attr The name of the attribute. * @param {Number} val The value to be applied to the attribute. * @param {String} unit The unit ('px', '%', etc.) of the value. */ setAttribute: function(attr, val, unit) { if ( this.patterns.noNegatives.test(attr) ) { val = (val > 0) ? val : 0; } YAHOO.util.Dom.setStyle(this.getEl(), attr, val + unit); }, /** * Returns current value of the attribute. * @method getAttribute * @param {String} attr The name of the attribute. * @return {Number} val The current value of the attribute. */ getAttribute: function(attr) { var el = this.getEl(); var val = YAHOO.util.Dom.getStyle(el, attr); if (val !== 'auto' && !this.patterns.offsetUnit.test(val)) { return parseFloat(val); } var a = this.patterns.offsetAttribute.exec(attr) || []; var pos = !!( a[3] ); // top or left var box = !!( a[2] ); // width or height // use offsets for width/height and abs pos top/left if ( box || (YAHOO.util.Dom.getStyle(el, 'position') == 'absolute' && pos) ) { val = el['offset' + a[0].charAt(0).toUpperCase() + a[0].substr(1)]; } else { // default to zero for other 'auto' val = 0; } return val; }, /** * Returns the unit to use when none is supplied. * @method getDefaultUnit * @param {attr} attr The name of the attribute. * @return {String} The default unit to be used. */ getDefaultUnit: function(attr) { if ( this.patterns.defaultUnit.test(attr) ) { return 'px'; } return ''; }, /** * Sets the actual values to be used during the animation. Should only be needed for subclass use. * @method setRuntimeAttribute * @param {Object} attr The attribute object * @private */ setRuntimeAttribute: function(attr) { var start; var end; var attributes = this.attributes; this.runtimeAttributes[attr] = {}; var isset = function(prop) { return (typeof prop !== 'undefined'); }; if ( !isset(attributes[attr]['to']) && !isset(attributes[attr]['by']) ) { return false; // note return; nothing to animate to } start = ( isset(attributes[attr]['from']) ) ? attributes[attr]['from'] : this.getAttribute(attr); // To beats by, per SMIL 2.1 spec if ( isset(attributes[attr]['to']) ) { end = attributes[attr]['to']; } else if ( isset(attributes[attr]['by']) ) { if (start.constructor == Array) { end = []; for (var i = 0, len = start.length; i < len; ++i) { end[i] = start[i] + attributes[attr]['by'][i] * 1; // times 1 to cast "by" } } else { end = start + attributes[attr]['by'] * 1; } } this.runtimeAttributes[attr].start = start; this.runtimeAttributes[attr].end = end; // set units if needed this.runtimeAttributes[attr].unit = ( isset(attributes[attr].unit) ) ? attributes[attr]['unit'] : this.getDefaultUnit(attr); return true; }, /** * Constructor for Anim instance. * @method init * @param {String | HTMLElement} el Reference to the element that will be animated * @param {Object} attributes The attribute(s) to be animated. * Each attribute is an object with at minimum a "to" or "by" member defined. * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). * All attribute names use camelCase. * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) */ init: function(el, attributes, duration, method) { /** * Whether or not the animation is running. * @property isAnimated * @private * @type Boolean */ var isAnimated = false; /** * A Date object that is created when the animation begins. * @property startTime * @private * @type Date */ var startTime = null; /** * The number of frames this animation was able to execute. * @property actualFrames * @private * @type Int */ var actualFrames = 0; /** * The element to be animated. * @property el * @private * @type HTMLElement */ el = YAHOO.util.Dom.get(el); /** * The collection of attributes to be animated. * Each attribute must have at least a "to" or "by" defined in order to animate. * If "to" is supplied, the animation will end with the attribute at that value. * If "by" is supplied, the animation will end at that value plus its starting value. * If both are supplied, "to" is used, and "by" is ignored. * Optional additional member include "from" (the value the attribute should start animating from, defaults to current value), and "unit" (the units to apply to the values). * @property attributes * @type Object */ this.attributes = attributes || {}; /** * The length of the animation. Defaults to "1" (second). * @property duration * @type Number */ this.duration = !YAHOO.lang.isUndefined(duration) ? duration : 1; /** * The method that will provide values to the attribute(s) during the animation. * Defaults to "YAHOO.util.Easing.easeNone". * @property method * @type Function */ this.method = method || YAHOO.util.Easing.easeNone; /** * Whether or not the duration should be treated as seconds. * Defaults to true. * @property useSeconds * @type Boolean */ this.useSeconds = true; // default to seconds /** * The location of the current animation on the timeline. * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. * @property currentFrame * @type Int */ this.currentFrame = 0; /** * The total number of frames to be executed. * In time-based animations, this is used by AnimMgr to ensure the animation finishes on time. * @property totalFrames * @type Int */ this.totalFrames = YAHOO.util.AnimMgr.fps; /** * Changes the animated element * @method setEl */ this.setEl = function(element) { el = YAHOO.util.Dom.get(element); }; /** * Returns a reference to the animated element. * @method getEl * @return {HTMLElement} */ this.getEl = function() { return el; }; /** * Checks whether the element is currently animated. * @method isAnimated * @return {Boolean} current value of isAnimated. */ this.isAnimated = function() { return isAnimated; }; /** * Returns the animation start time. * @method getStartTime * @return {Date} current value of startTime. */ this.getStartTime = function() { return startTime; }; this.runtimeAttributes = {}; var logger = {}; logger.log = function() {YAHOO.log.apply(window, arguments)}; logger.log('creating new instance of ' + this); /** * Starts the animation by registering it with the animation manager. * @method animate */ this.animate = function() { if ( this.isAnimated() ) { return false; } this.currentFrame = 0; this.totalFrames = ( this.useSeconds ) ? Math.ceil(YAHOO.util.AnimMgr.fps * this.duration) : this.duration; if (this.duration === 0 && this.useSeconds) { this.totalFrames = 1; // jump to last frame if no duration } YAHOO.util.AnimMgr.registerElement(this); return true; }; /** * Stops the animation. Normally called by AnimMgr when animation completes. * @method stop * @param {Boolean} finish (optional) If true, animation will jump to final frame. */ this.stop = function(finish) { if (finish) { this.currentFrame = this.totalFrames; this._onTween.fire(); } YAHOO.util.AnimMgr.stop(this); }; var onStart = function() { this.onStart.fire(); this.runtimeAttributes = {}; for (var attr in this.attributes) { this.setRuntimeAttribute(attr); } isAnimated = true; actualFrames = 0; startTime = new Date(); }; /** * Feeds the starting and ending values for each animated attribute to doMethod once per frame, then applies the resulting value to the attribute(s). * @private */ var onTween = function() { var data = { duration: new Date() - this.getStartTime(), currentFrame: this.currentFrame }; data.toString = function() { return ( 'duration: ' + data.duration + ', currentFrame: ' + data.currentFrame ); }; this.onTween.fire(data); var runtimeAttributes = this.runtimeAttributes; for (var attr in runtimeAttributes) { this.setAttribute(attr, this.doMethod(attr, runtimeAttributes[attr].start, runtimeAttributes[attr].end), runtimeAttributes[attr].unit); } actualFrames += 1; }; var onComplete = function() { var actual_duration = (new Date() - startTime) / 1000 ; var data = { duration: actual_duration, frames: actualFrames, fps: actualFrames / actual_duration }; data.toString = function() { return ( 'duration: ' + data.duration + ', frames: ' + data.frames + ', fps: ' + data.fps ); }; isAnimated = false; actualFrames = 0; this.onComplete.fire(data); }; /** * Custom event that fires after onStart, useful in subclassing * @private */ this._onStart = new YAHOO.util.CustomEvent('_start', this, true); /** * Custom event that fires when animation begins * Listen via subscribe method (e.g. myAnim.onStart.subscribe(someFunction) * @event onStart */ this.onStart = new YAHOO.util.CustomEvent('start', this); /** * Custom event that fires between each frame * Listen via subscribe method (e.g. myAnim.onTween.subscribe(someFunction) * @event onTween */ this.onTween = new YAHOO.util.CustomEvent('tween', this); /** * Custom event that fires after onTween * @private */ this._onTween = new YAHOO.util.CustomEvent('_tween', this, true); /** * Custom event that fires when animation ends * Listen via subscribe method (e.g. myAnim.onComplete.subscribe(someFunction) * @event onComplete */ this.onComplete = new YAHOO.util.CustomEvent('complete', this); /** * Custom event that fires after onComplete * @private */ this._onComplete = new YAHOO.util.CustomEvent('_complete', this, true); this._onStart.subscribe(onStart); this._onTween.subscribe(onTween); this._onComplete.subscribe(onComplete); } }; /** * Handles animation queueing and threading. * Used by Anim and subclasses. * @class AnimMgr * @namespace YAHOO.util */ YAHOO.util.AnimMgr = new function() { /** * Reference to the animation Interval. * @property thread * @private * @type Int */ var thread = null; /** * The current queue of registered animation objects. * @property queue * @private * @type Array */ var queue = []; /** * The number of active animations. * @property tweenCount * @private * @type Int */ var tweenCount = 0; /** * Base frame rate (frames per second). * Arbitrarily high for better x-browser calibration (slower browsers drop more frames). * @property fps * @type Int * */ this.fps = 1000; /** * Interval delay in milliseconds, defaults to fastest possible. * @property delay * @type Int * */ this.delay = 1; /** * Adds an animation instance to the animation queue. * All animation instances must be registered in order to animate. * @method registerElement * @param {object} tween The Anim instance to be be registered */ this.registerElement = function(tween) { queue[queue.length] = tween; tweenCount += 1; tween._onStart.fire(); this.start(); }; /** * removes an animation instance from the animation queue. * All animation instances must be registered in order to animate. * @method unRegister * @param {object} tween The Anim instance to be be registered * @param {Int} index The index of the Anim instance * @private */ this.unRegister = function(tween, index) { tween._onComplete.fire(); index = index || getIndex(tween); if (index == -1) { return false; } queue.splice(index, 1); tweenCount -= 1; if (tweenCount <= 0) { this.stop(); } return true; }; /** * Starts the animation thread. * Only one thread can run at a time. * @method start */ this.start = function() { if (thread === null) { thread = setInterval(this.run, this.delay); } }; /** * Stops the animation thread or a specific animation instance. * @method stop * @param {object} tween A specific Anim instance to stop (optional) * If no instance given, Manager stops thread and all animations. */ this.stop = function(tween) { if (!tween) { clearInterval(thread); for (var i = 0, len = queue.length; i < len; ++i) { if ( queue[0].isAnimated() ) { this.unRegister(queue[0], 0); } } queue = []; thread = null; tweenCount = 0; } else { this.unRegister(tween); } }; /** * Called per Interval to handle each animation frame. * @method run */ this.run = function() { for (var i = 0, len = queue.length; i < len; ++i) { var tween = queue[i]; if ( !tween || !tween.isAnimated() ) { continue; } if (tween.currentFrame < tween.totalFrames || tween.totalFrames === null) { tween.currentFrame += 1; if (tween.useSeconds) { correctFrame(tween); } tween._onTween.fire(); } else { YAHOO.util.AnimMgr.stop(tween, i); } } }; var getIndex = function(anim) { for (var i = 0, len = queue.length; i < len; ++i) { if (queue[i] == anim) { return i; // note return; } } return -1; }; /** * On the fly frame correction to keep animation on time. * @method correctFrame * @private * @param {Object} tween The Anim instance being corrected. */ var correctFrame = function(tween) { var frames = tween.totalFrames; var frame = tween.currentFrame; var expected = (tween.currentFrame * tween.duration * 1000 / tween.totalFrames); var elapsed = (new Date() - tween.getStartTime()); var tweak = 0; if (elapsed < tween.duration * 1000) { // check if falling behind tweak = Math.round((elapsed / expected - 1) * tween.currentFrame); } else { // went over duration, so jump to end tweak = frames - (frame + 1); } if (tweak > 0 && isFinite(tweak)) { // adjust if needed if (tween.currentFrame + tweak >= frames) {// dont go past last frame tweak = frames - (frame + 1); } tween.currentFrame += tweak; } }; }; /** * Used to calculate Bezier splines for any number of control points. * @class Bezier * @namespace YAHOO.util * */ YAHOO.util.Bezier = new function() { /** * Get the current position of the animated element based on t. * Each point is an array of "x" and "y" values (0 = x, 1 = y) * At least 2 points are required (start and end). * First point is start. Last point is end. * Additional control points are optional. * @method getPosition * @param {Array} points An array containing Bezier points * @param {Number} t A number between 0 and 1 which is the basis for determining current position * @return {Array} An array containing int x and y member data */ this.getPosition = function(points, t) { var n = points.length; var tmp = []; for (var i = 0; i < n; ++i){ tmp[i] = [points[i][0], points[i][1]]; // save input } for (var j = 1; j < n; ++j) { for (i = 0; i < n - j; ++i) { tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; } } return [ tmp[0][0], tmp[0][1] ]; }; }; (function() { /** * Anim subclass for color transitions. * <p>Usage: <code>var myAnim = new Y.ColorAnim(el, { backgroundColor: { from: '#FF0000', to: '#FFFFFF' } }, 1, Y.Easing.easeOut);</code> Color values can be specified with either 112233, #112233, * [255,255,255], or rgb(255,255,255)</p> * @class ColorAnim * @namespace YAHOO.util * @requires YAHOO.util.Anim * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Bezier * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @constructor * @extends YAHOO.util.Anim * @param {HTMLElement | String} el Reference to the element that will be animated * @param {Object} attributes The attribute(s) to be animated. * Each attribute is an object with at minimum a "to" or "by" member defined. * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). * All attribute names use camelCase. * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) */ YAHOO.util.ColorAnim = function(el, attributes, duration, method) { YAHOO.util.ColorAnim.superclass.constructor.call(this, el, attributes, duration, method); }; YAHOO.extend(YAHOO.util.ColorAnim, YAHOO.util.Anim); // shorthand var Y = YAHOO.util; var superclass = Y.ColorAnim.superclass; var proto = Y.ColorAnim.prototype; proto.toString = function() { var el = this.getEl(); var id = el.id || el.tagName; return ("ColorAnim " + id); }; proto.patterns.color = /color$/i; proto.patterns.rgb = /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i; proto.patterns.hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i; proto.patterns.hex3 = /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i; proto.patterns.transparent = /^transparent|rgba\(0, 0, 0, 0\)$/; // need rgba for safari /** * Attempts to parse the given string and return a 3-tuple. * @method parseColor * @param {String} s The string to parse. * @return {Array} The 3-tuple of rgb values. */ proto.parseColor = function(s) { if (s.length == 3) { return s; } var c = this.patterns.hex.exec(s); if (c && c.length == 4) { return [ parseInt(c[1], 16), parseInt(c[2], 16), parseInt(c[3], 16) ]; } c = this.patterns.rgb.exec(s); if (c && c.length == 4) { return [ parseInt(c[1], 10), parseInt(c[2], 10), parseInt(c[3], 10) ]; } c = this.patterns.hex3.exec(s); if (c && c.length == 4) { return [ parseInt(c[1] + c[1], 16), parseInt(c[2] + c[2], 16), parseInt(c[3] + c[3], 16) ]; } return null; }; proto.getAttribute = function(attr) { var el = this.getEl(); if ( this.patterns.color.test(attr) ) { var val = YAHOO.util.Dom.getStyle(el, attr); if (this.patterns.transparent.test(val)) { // bgcolor default var parent = el.parentNode; // try and get from an ancestor val = Y.Dom.getStyle(parent, attr); while (parent && this.patterns.transparent.test(val)) { parent = parent.parentNode; val = Y.Dom.getStyle(parent, attr); if (parent.tagName.toUpperCase() == 'HTML') { val = '#fff'; } } } } else { val = superclass.getAttribute.call(this, attr); } return val; }; proto.doMethod = function(attr, start, end) { var val; if ( this.patterns.color.test(attr) ) { val = []; for (var i = 0, len = start.length; i < len; ++i) { val[i] = superclass.doMethod.call(this, attr, start[i], end[i]); } val = 'rgb('+Math.floor(val[0])+','+Math.floor(val[1])+','+Math.floor(val[2])+')'; } else { val = superclass.doMethod.call(this, attr, start, end); } return val; }; proto.setRuntimeAttribute = function(attr) { superclass.setRuntimeAttribute.call(this, attr); if ( this.patterns.color.test(attr) ) { var attributes = this.attributes; var start = this.parseColor(this.runtimeAttributes[attr].start); var end = this.parseColor(this.runtimeAttributes[attr].end); // fix colors if going "by" if ( typeof attributes[attr]['to'] === 'undefined' && typeof attributes[attr]['by'] !== 'undefined' ) { end = this.parseColor(attributes[attr].by); for (var i = 0, len = start.length; i < len; ++i) { end[i] = start[i] + end[i]; } } this.runtimeAttributes[attr].start = start; this.runtimeAttributes[attr].end = end; } }; })(); /* TERMS OF USE - EASING EQUATIONS Open source under the BSD License. Copyright 2001 Robert Penner 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 the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Singleton that determines how an animation proceeds from start to end. * @class Easing * @namespace YAHOO.util */ YAHOO.util.Easing = { /** * Uniform speed between points. * @method easeNone * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeNone: function (t, b, c, d) { return c*t/d + b; }, /** * Begins slowly and accelerates towards end. (quadratic) * @method easeIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeIn: function (t, b, c, d) { return c*(t/=d)*t + b; }, /** * Begins quickly and decelerates towards end. (quadratic) * @method easeOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeOut: function (t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, /** * Begins slowly and decelerates towards end. (quadratic) * @method easeBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeBoth: function (t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t + b; } return -c/2 * ((--t)*(t-2) - 1) + b; }, /** * Begins slowly and accelerates towards end. (quartic) * @method easeInStrong * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeInStrong: function (t, b, c, d) { return c*(t/=d)*t*t*t + b; }, /** * Begins quickly and decelerates towards end. (quartic) * @method easeOutStrong * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeOutStrong: function (t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, /** * Begins slowly and decelerates towards end. (quartic) * @method easeBothStrong * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeBothStrong: function (t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t*t + b; } return -c/2 * ((t-=2)*t*t*t - 2) + b; }, /** * Snap in elastic effect. * @method elasticIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticIn: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ( (t /= d) == 1 ) { return b+c; } if (!p) { p=d*.3; } if (!a || a < Math.abs(c)) { a = c; var s = p/4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, /** * Snap out elastic effect. * @method elasticOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticOut: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ( (t /= d) == 1 ) { return b+c; } if (!p) { p=d*.3; } if (!a || a < Math.abs(c)) { a = c; var s = p / 4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, /** * Snap both elastic effect. * @method elasticBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticBoth: function (t, b, c, d, a, p) { if (t == 0) { return b; } if ( (t /= d/2) == 2 ) { return b+c; } if (!p) { p = d*(.3*1.5); } if ( !a || a < Math.abs(c) ) { a = c; var s = p/4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } if (t < 1) { return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; } return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, /** * Backtracks slightly, then reverses direction and moves to end. * @method backIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backIn: function (t, b, c, d, s) { if (typeof s == 'undefined') { s = 1.70158; } return c*(t/=d)*t*((s+1)*t - s) + b; }, /** * Overshoots end, then reverses and comes back to end. * @method backOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backOut: function (t, b, c, d, s) { if (typeof s == 'undefined') { s = 1.70158; } return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, /** * Backtracks slightly, then reverses direction, overshoots end, * then reverses and comes back to end. * @method backBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backBoth: function (t, b, c, d, s) { if (typeof s == 'undefined') { s = 1.70158; } if ((t /= d/2 ) < 1) { return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; } return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, /** * Bounce off of start. * @method bounceIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceIn: function (t, b, c, d) { return c - YAHOO.util.Easing.bounceOut(d-t, 0, c, d) + b; }, /** * Bounces off end. * @method bounceOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceOut: function (t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; }, /** * Bounces off start and end. * @method bounceBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceBoth: function (t, b, c, d) { if (t < d/2) { return YAHOO.util.Easing.bounceIn(t*2, 0, c, d) * .5 + b; } return YAHOO.util.Easing.bounceOut(t*2-d, 0, c, d) * .5 + c*.5 + b; } }; (function() { /** * Anim subclass for moving elements along a path defined by the "points" * member of "attributes". All "points" are arrays with x, y coordinates. * <p>Usage: <code>var myAnim = new YAHOO.util.Motion(el, { points: { to: [800, 800] } }, 1, YAHOO.util.Easing.easeOut);</code></p> * @class Motion * @namespace YAHOO.util * @requires YAHOO.util.Anim * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Bezier * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @requires YAHOO.util.CustomEvent * @constructor * @extends YAHOO.util.Anim * @param {String | HTMLElement} el Reference to the element that will be animated * @param {Object} attributes The attribute(s) to be animated. * Each attribute is an object with at minimum a "to" or "by" member defined. * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). * All attribute names use camelCase. * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) */ YAHOO.util.Motion = function(el, attributes, duration, method) { if (el) { // dont break existing subclasses not using YAHOO.extend YAHOO.util.Motion.superclass.constructor.call(this, el, attributes, duration, method); } }; YAHOO.extend(YAHOO.util.Motion, YAHOO.util.ColorAnim); // shorthand var Y = YAHOO.util; var superclass = Y.Motion.superclass; var proto = Y.Motion.prototype; proto.toString = function() { var el = this.getEl(); var id = el.id || el.tagName; return ("Motion " + id); }; proto.patterns.points = /^points$/i; proto.setAttribute = function(attr, val, unit) { if ( this.patterns.points.test(attr) ) { unit = unit || 'px'; superclass.setAttribute.call(this, 'left', val[0], unit); superclass.setAttribute.call(this, 'top', val[1], unit); } else { superclass.setAttribute.call(this, attr, val, unit); } }; proto.getAttribute = function(attr) { if ( this.patterns.points.test(attr) ) { var val = [ superclass.getAttribute.call(this, 'left'), superclass.getAttribute.call(this, 'top') ]; } else { val = superclass.getAttribute.call(this, attr); } return val; }; proto.doMethod = function(attr, start, end) { var val = null; if ( this.patterns.points.test(attr) ) { var t = this.method(this.currentFrame, 0, 100, this.totalFrames) / 100; val = Y.Bezier.getPosition(this.runtimeAttributes[attr], t); } else { val = superclass.doMethod.call(this, attr, start, end); } return val; }; proto.setRuntimeAttribute = function(attr) { if ( this.patterns.points.test(attr) ) { var el = this.getEl(); var attributes = this.attributes; var start; var control = attributes['points']['control'] || []; var end; var i, len; if (control.length > 0 && !(control[0] instanceof Array) ) { // could be single point or array of points control = [control]; } else { // break reference to attributes.points.control var tmp = []; for (i = 0, len = control.length; i< len; ++i) { tmp[i] = control[i]; } control = tmp; } if (Y.Dom.getStyle(el, 'position') == 'static') { // default to relative Y.Dom.setStyle(el, 'position', 'relative'); } if ( isset(attributes['points']['from']) ) { Y.Dom.setXY(el, attributes['points']['from']); // set position to from point } else { Y.Dom.setXY( el, Y.Dom.getXY(el) ); } // set it to current position start = this.getAttribute('points'); // get actual top & left // TO beats BY, per SMIL 2.1 spec if ( isset(attributes['points']['to']) ) { end = translateValues.call(this, attributes['points']['to'], start); var pageXY = Y.Dom.getXY(this.getEl()); for (i = 0, len = control.length; i < len; ++i) { control[i] = translateValues.call(this, control[i], start); } } else if ( isset(attributes['points']['by']) ) { end = [ start[0] + attributes['points']['by'][0], start[1] + attributes['points']['by'][1] ]; for (i = 0, len = control.length; i < len; ++i) { control[i] = [ start[0] + control[i][0], start[1] + control[i][1] ]; } } this.runtimeAttributes[attr] = [start]; if (control.length > 0) { this.runtimeAttributes[attr] = this.runtimeAttributes[attr].concat(control); } this.runtimeAttributes[attr][this.runtimeAttributes[attr].length] = end; } else { superclass.setRuntimeAttribute.call(this, attr); } }; var translateValues = function(val, start) { var pageXY = Y.Dom.getXY(this.getEl()); val = [ val[0] - pageXY[0] + start[0], val[1] - pageXY[1] + start[1] ]; return val; }; var isset = function(prop) { return (typeof prop !== 'undefined'); }; })(); (function() { /** * Anim subclass for scrolling elements to a position defined by the "scroll" * member of "attributes". All "scroll" members are arrays with x, y scroll positions. * <p>Usage: <code>var myAnim = new YAHOO.util.Scroll(el, { scroll: { to: [0, 800] } }, 1, YAHOO.util.Easing.easeOut);</code></p> * @class Scroll * @namespace YAHOO.util * @requires YAHOO.util.Anim * @requires YAHOO.util.AnimMgr * @requires YAHOO.util.Easing * @requires YAHOO.util.Bezier * @requires YAHOO.util.Dom * @requires YAHOO.util.Event * @requires YAHOO.util.CustomEvent * @extends YAHOO.util.Anim * @constructor * @param {String or HTMLElement} el Reference to the element that will be animated * @param {Object} attributes The attribute(s) to be animated. * Each attribute is an object with at minimum a "to" or "by" member defined. * Additional optional members are "from" (defaults to current value), "units" (defaults to "px"). * All attribute names use camelCase. * @param {Number} duration (optional, defaults to 1 second) Length of animation (frames or seconds), defaults to time-based * @param {Function} method (optional, defaults to YAHOO.util.Easing.easeNone) Computes the values that are applied to the attributes per frame (generally a YAHOO.util.Easing method) */ YAHOO.util.Scroll = function(el, attributes, duration, method) { if (el) { // dont break existing subclasses not using YAHOO.extend YAHOO.util.Scroll.superclass.constructor.call(this, el, attributes, duration, method); } }; YAHOO.extend(YAHOO.util.Scroll, YAHOO.util.ColorAnim); // shorthand var Y = YAHOO.util; var superclass = Y.Scroll.superclass; var proto = Y.Scroll.prototype; proto.toString = function() { var el = this.getEl(); var id = el.id || el.tagName; return ("Scroll " + id); }; proto.doMethod = function(attr, start, end) { var val = null; if (attr == 'scroll') { val = [ this.method(this.currentFrame, start[0], end[0] - start[0], this.totalFrames), this.method(this.currentFrame, start[1], end[1] - start[1], this.totalFrames) ]; } else { val = superclass.doMethod.call(this, attr, start, end); } return val; }; proto.getAttribute = function(attr) { var val = null; var el = this.getEl(); if (attr == 'scroll') { val = [ el.scrollLeft, el.scrollTop ]; } else { val = superclass.getAttribute.call(this, attr); } return val; }; proto.setAttribute = function(attr, val, unit) { var el = this.getEl(); if (attr == 'scroll') { el.scrollLeft = val[0]; el.scrollTop = val[1]; } else { superclass.setAttribute.call(this, attr, val, unit); } }; })(); YAHOO.register("animation", YAHOO.util.Anim, {version: "2.3.0", build: "442"});
chisimba/modules
yahoolib/resources/animation/animation-debug.js
JavaScript
gpl-2.0
48,498
model.jsonModel = { services: [ { name: "alfresco/services/LoggingService", config: { loggingPreferences: { enabled: true, all: true, warn: true, error: true } } }, "alfresco/services/ErrorReporter" ], widgets: [ { id: "STFF1", name: "alfresco/forms/SingleTextFieldForm", config: { useHash: false, okButtonLabel: "Search", okButtonPublishTopic: "TEST_PUBLISH", okButtonPublishGlobal: true, okButtonIconClass: "alf-white-search-icon", okButtonClass: "call-to-action", textFieldName: "search", textBoxIconClass: "alf-search-icon", textBoxCssClasses: "long" } }, { id: "STFF2", name: "alfresco/forms/SingleTextFieldForm", config: { useHash: true, okButtonLabel: "Search", okButtonPublishTopic: "TEST_PUBLISH", okButtonPublishGlobal: true, okButtonIconClass: "alf-white-search-icon", okButtonClass: "call-to-action", textFieldName: "search", textBoxIconClass: "alf-search-icon", textBoxCssClasses: "long" } }, { name: "alfresco/logging/SubscriptionLog" }, { name: "aikauTesting/TestCoverageResults" } ] };
davidcognite/Aikau
aikau/src/test/resources/testApp/WEB-INF/classes/alfresco/site-webscripts/alfresco/forms/SingleTextFieldForm.get.js
JavaScript
lgpl-3.0
1,496
/** * Copyright 2020 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 {AmpA4A} from '../../amp-a4a/0.1/amp-a4a'; /** * Oblivki base URL * * @type {string} * @private */ const OBLIVKI_BASE_URL_ = 'https://oblivki.biz/amp/'; /** * Oblivki A4A base URL * * @type {string} * @private */ const OBLIVKI_BASE_A4A_URL_ = 'https://oblivki.biz/amp/a4a/'; export class AmpAdNetworkOblivkiImpl extends AmpA4A { /** @override */ getAdUrl(unusedConsentTuple, opt_rtcResponsesPromise) { return this.element .getAttribute('src') .replace(OBLIVKI_BASE_URL_, OBLIVKI_BASE_A4A_URL_); } /** @override */ getSigningServiceNames() { return ['cloudflare']; } /** @override */ isValidElement() { const src = this.element.getAttribute('src') || ''; return ( this.isAmpAdElement() && (src.startsWith(OBLIVKI_BASE_URL_) || src.startsWith(OBLIVKI_BASE_A4A_URL_)) ); } } AMP.extension('amp-ad-network-oblivki-impl', '0.1', (AMP) => { AMP.registerElement('amp-ad-network-oblivki-impl', AmpAdNetworkOblivkiImpl); });
prateekbh/amphtml
extensions/amp-ad-network-oblivki-impl/0.1/amp-ad-network-oblivki-impl.js
JavaScript
apache-2.0
1,640
/*! * Copyright 2014 Apereo Foundation (AF) Licensed under the * Educational Community 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://opensource.org/licenses/ECL-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. */ var assert = require('assert'); var MQ = require('oae-util/lib/mq'); var TaskQueue = require('oae-util/lib/taskqueue'); var PreviewConstants = require('oae-preview-processor/lib/constants'); /** * Purges all the events out of the previews queue * * @param {Function} callback Standard callback function * @throws {AssertionError} Thrown if an error occurs while purging the queue */ var purgePreviewsQueue = module.exports.purgePreviewsQueue = function(callback) { // Unbind the old listener (if any) and bind a new one, so we can purge the queue TaskQueue.unbind(PreviewConstants.MQ.TASK_GENERATE_PREVIEWS, function(err) { assert.ok(!err); TaskQueue.bind(PreviewConstants.MQ.TASK_GENERATE_PREVIEWS, function() {}, {'subscribe': {'subscribe': false}}, function(err) { assert.ok(!err); // Purge anything that is in the queue MQ.purge(PreviewConstants.MQ.TASK_GENERATE_PREVIEWS, function(err) { assert.ok(!err); // Unbind our dummy-handler from the queue TaskQueue.unbind(PreviewConstants.MQ.TASK_GENERATE_PREVIEWS, function(err) { assert.ok(!err); return callback(); }); }); }); }); }; /** * Purges all the messages out of the regenerate previews queue * * @param {Function} callback Standard callback function * @throws {AssertionError} Thrown if an error occurs while purging the queue */ var purgeRegeneratePreviewsQueue = module.exports.purgeRegeneratePreviewsQueue = function(callback) { // Unbind the old listener (if any) and bind a new one, so we can purge the queue TaskQueue.unbind(PreviewConstants.MQ.TASK_REGENERATE_PREVIEWS, function(err) { assert.ok(!err); TaskQueue.bind(PreviewConstants.MQ.TASK_REGENERATE_PREVIEWS, function() {}, {'subscribe': {'subscribe': false}}, function(err) { assert.ok(!err); // Purge anything that is in the queue MQ.purge(PreviewConstants.MQ.TASK_REGENERATE_PREVIEWS, function(err) { assert.ok(!err); // Unbind our dummy-handler from the queue TaskQueue.unbind(PreviewConstants.MQ.TASK_REGENERATE_PREVIEWS, function(err) { assert.ok(!err); return callback(); }); }); }); }); }; /** * Purges all the messages out of the generate folder previews queue * * @param {Function} callback Standard callback function * @throws {AssertionError} Thrown if an error occurs while purging the queue */ var purgeFoldersPreviewsQueue = module.exports.purgeFoldersPreviewsQueue = function(callback) { // Unbind the old listener (if any) and bind a new one, so we can purge the queue TaskQueue.unbind(PreviewConstants.MQ.TASK_GENERATE_FOLDER_PREVIEWS, function(err) { assert.ok(!err); TaskQueue.bind(PreviewConstants.MQ.TASK_GENERATE_FOLDER_PREVIEWS, function() {}, {'subscribe': {'subscribe': false}}, function(err) { assert.ok(!err); // Purge anything that is in the queue MQ.purge(PreviewConstants.MQ.TASK_GENERATE_FOLDER_PREVIEWS, function(err) { assert.ok(!err); // Unbind our dummy-handler from the queue TaskQueue.unbind(PreviewConstants.MQ.TASK_GENERATE_FOLDER_PREVIEWS, function(err) { assert.ok(!err); return callback(); }); }); }); }); };
simong/Hilary
node_modules/oae-preview-processor/lib/test/util.js
JavaScript
apache-2.0
4,276
// Copyright 2015 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. var sinon = sinon || {}; /** @type {Object} */ sinon.assert = {}; /** * @param {(sinon.Spy|Function)} f */ sinon.assert.called = function(f) {}; /** * @param {(sinon.Spy|Function)} f */ sinon.assert.calledOnce = function(f) {}; /** * @param {(sinon.Spy|Function)} f * @param {...} data */ sinon.assert.calledWith = function(f, data) {}; /** * @param {(sinon.Spy|Function)} f */ sinon.assert.notCalled = function(f) {}; /** @constructor */ sinon.Clock = function() {}; /** @param {number} ms */ sinon.Clock.prototype.tick = function(ms) {}; /** @return {void} */ sinon.Clock.prototype.restore = function() {}; /** * @param {number=} opt_now * @return {sinon.Clock} */ sinon.useFakeTimers = function(opt_now) {}; /** @constructor */ sinon.Expectation = function() {}; /** @return {sinon.Expectation} */ sinon.Expectation.prototype.once = function() {}; /** @return {sinon.Expectation} */ sinon.Expectation.prototype.never = function() {}; /** * @param {number} times * @return {sinon.Expectation} */ sinon.Expectation.prototype.exactly = function(times) {}; /** * @param {...} data * @return {sinon.Expectation} */ sinon.Expectation.prototype.withArgs = function(data) {}; /** @return {boolean} */ sinon.Expectation.prototype.verify = function() {}; /** @param {...} data */ sinon.Expectation.prototype.returns = function(data) {}; /** * @param {Object} obj * @return {sinon.Mock} */ sinon.mock = function(obj) {}; /** @constructor */ sinon.Mock = function() {}; /** * @param {string} method * @return {sinon.Expectation} */ sinon.Mock.prototype.expects = function(method) {}; /** * @return {void} */ sinon.Mock.prototype.restore = function() {}; /** * @return {boolean} */ sinon.Mock.prototype.verify = function() {}; /** @type {function(...):Function} */ sinon.spy = function() {}; /** * This is a jscompile type that can be OR'ed with the actual type to make * jscompile aware of the sinon.spy functions that are added to the base * type. * Example: Instead of specifying a type of * {function():void} * the following can be used to add the sinon.spy functions: * {(sinon.Spy|function():void)} * * @interface */ sinon.Spy = function() {}; /** @type {number} */ sinon.Spy.prototype.callCount; /** @type {boolean} */ sinon.Spy.prototype.called; /** @type {boolean} */ sinon.Spy.prototype.calledOnce; /** @type {boolean} */ sinon.Spy.prototype.calledTwice; /** @type {function(...):boolean} */ sinon.Spy.prototype.calledWith = function() {}; /** @type {function(number):{args:Array}} */ sinon.Spy.prototype.getCall = function(index) {}; sinon.Spy.prototype.reset = function() {}; sinon.Spy.prototype.restore = function() {}; /** @type {Array<Array<*>>} */ sinon.Spy.prototype.args; /** * @param {Object=} opt_obj * @param {string=} opt_method * @param {Function=} opt_stubFunction * @return {sinon.TestStub} */ sinon.stub = function(opt_obj, opt_method, opt_stubFunction) {}; /** * TODO(jrw): rename to |sinon.Stub| for consistency * @interface * @extends {sinon.Spy} */ sinon.TestStub = function() {}; /** @type {function(number):{args:Array}} */ sinon.TestStub.prototype.getCall = function(index) {}; sinon.TestStub.prototype.restore = function() {}; /** @param {*} a */ sinon.TestStub.prototype.returns = function(a) {}; /** @type {function(...):sinon.Expectation} */ sinon.TestStub.prototype.withArgs = function() {}; /** @type {function(...):sinon.Expectation} */ sinon.TestStub.prototype.onFirstCall = function() {}; /** @type {function(...):sinon.Expectation} */ sinon.TestStub.prototype.callsArgWith = function() {}; /** @returns {Object} */ sinon.createStubInstance = function (/** * */ constructor) {}; /** @interface */ sinon.FakeXhrCtrl = function() {}; /** * @type {?function(!sinon.FakeXhr)} */ sinon.FakeXhrCtrl.prototype.onCreate; /** * @type {function():void} */ sinon.FakeXhrCtrl.prototype.restore; /** @return {sinon.FakeXhrCtrl} */ sinon.useFakeXMLHttpRequest = function() {}; /** @interface */ sinon.FakeXhr = function() {}; /** @type {number} */ sinon.FakeXhr.prototype.readyState; /** @type {string} */ sinon.FakeXhr.prototype.method; /** @type {string} */ sinon.FakeXhr.prototype.url; /** @type {boolean} */ sinon.FakeXhr.prototype.withCredentials; /** @type {?string} */ sinon.FakeXhr.prototype.requestBody; /** @type {!Object<string>} */ sinon.FakeXhr.prototype.requestHeaders; /** * @param {number} status * @param {!Object<string>} headers * @param {?string} content */ sinon.FakeXhr.prototype.respond; /** * @param {string} event * @param {Function} handler */ sinon.FakeXhr.prototype.addEventListener;
hgl888/chromium-crosswalk
remoting/webapp/js_proto/sinon_proto.js
JavaScript
bsd-3-clause
4,812
// Copyright 2014 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. var $Document = require('safeMethods').SafeMethods.$Document; var $HTMLElement = require('safeMethods').SafeMethods.$HTMLElement; var $Node = require('safeMethods').SafeMethods.$Node; var GuestViewContainer = require('guestViewContainer').GuestViewContainer; function AppViewImpl(appviewElement) { $Function.call(GuestViewContainer, this, appviewElement, 'appview'); this.app = ''; this.data = ''; } AppViewImpl.prototype.__proto__ = GuestViewContainer.prototype; AppViewImpl.prototype.getErrorNode = function() { if (!this.errorNode) { this.errorNode = $Document.createElement(document, 'div'); $HTMLElement.innerText.set(this.errorNode, 'Unable to connect to app.'); var style = $HTMLElement.style.get(this.errorNode); $Object.defineProperty(style, 'position', {value: 'absolute'}); $Object.defineProperty(style, 'left', {value: '0px'}); $Object.defineProperty(style, 'top', {value: '0px'}); $Object.defineProperty(style, 'width', {value: '100%'}); $Object.defineProperty(style, 'height', {value: '100%'}); $Node.appendChild(this.shadowRoot, this.errorNode); } return this.errorNode; }; AppViewImpl.prototype.buildContainerParams = function() { var params = $Object.create(null); params.appId = this.app; params.data = this.data || {}; return params; }; AppViewImpl.prototype.connect = function(app, data, callback) { if (!this.elementAttached) { if (callback) { callback(false); } return; } this.app = app; this.data = data; this.guest.destroy($Function.bind(this.prepareForReattach, this)); this.guest.create(this.buildParams(), $Function.bind(function() { if (!this.guest.getId()) { var errorMsg = 'Unable to connect to app "' + app + '".'; window.console.warn(errorMsg); $HTMLElement.innerText.set(this.getErrorNode(), errorMsg); if (callback) { callback(false); } return; } this.attachWindow(); if (callback) { callback(true); } }, this)); }; // Exports. exports.$set('AppViewImpl', AppViewImpl);
scheib/chromium
extensions/renderer/resources/guest_view/app_view/app_view.js
JavaScript
bsd-3-clause
2,237
#!/usr/bin/env node 'use strict'; var Liftoff = require('liftoff'); var Promise = require('bluebird'); var interpret = require('interpret'); var path = require('path'); var chalk = require('chalk'); var tildify = require('tildify'); var commander = require('commander'); var cliPkg = require('../../package'); var argv = require('minimist')(process.argv.slice(2)); var fs = Promise.promisifyAll(require('fs')); function exit(text) { if (text instanceof Error) { chalk.red(console.error(text.stack)); } else { chalk.red(console.error(text)); } process.exit(1); } function success(text) { console.log(text); process.exit(0); } function checkLocalModule(env) { if (!env.modulePath) { console.log(chalk.red('No local knex install found in:'), chalk.magenta(tildify(env.cwd))); exit('Try running: npm install knex.'); } } function initKnex(env) { checkLocalModule(env); if (!env.configPath) { exit('No knexfile found in this directory. Specify a path with --knexfile'); } if (process.cwd() !== env.cwd) { process.chdir(env.cwd); console.log('Working directory changed to', chalk.magenta(tildify(env.cwd))); } var environment = commander.env || process.env.NODE_ENV; var defaultEnv = 'development'; var config = require(env.configPath); if (!environment && typeof config[defaultEnv] === 'object') { environment = defaultEnv; } if (environment) { console.log('Using environment:', chalk.magenta(environment)); config = config[environment]; } if (!config) { console.log(chalk.red('Warning: unable to read knexfile config')); process.exit(1); } if (argv.debug !== undefined) config.debug = argv.debug; var knex = require(env.modulePath); return knex(config); } function invoke(env) { var pending, filetypes = ['js', 'coffee', 'ls', 'eg']; commander.version(chalk.blue('Knex CLI version: ', chalk.green(cliPkg.version)) + '\n' + chalk.blue('Local Knex version: ', chalk.green(env.modulePackage.version)) + '\n').option('--debug', 'Run with debugging.').option('--knexfile [path]', 'Specify the knexfile path.').option('--cwd [path]', 'Specify the working directory.').option('--env [name]', 'environment, default: process.env.NODE_ENV || development'); commander.command('init').description(' Create a fresh knexfile.').option('-x [' + filetypes.join('|') + ']', 'Specify the knexfile extension (default js)').action(function () { var type = (argv.x || 'js').toLowerCase(); if (filetypes.indexOf(type) === -1) { exit('Invalid filetype specified: ' + type); } if (env.configPath) { exit('Error: ' + env.configPath + ' already exists'); } checkLocalModule(env); var stubPath = './knexfile.' + type; pending = fs.readFileAsync(path.dirname(env.modulePath) + '/lib/migrate/stub/knexfile-' + type + '.stub').then(function (code) { return fs.writeFileAsync(stubPath, code); }).then(function () { success(chalk.green('Created ' + stubPath)); })['catch'](exit); }); commander.command('migrate:make <name>').description(' Create a named migration file.').option('-x [' + filetypes.join('|') + ']', 'Specify the stub extension (default js)').action(function (name) { var ext = (argv.x || env.configPath.split('.').pop()).toLowerCase(); pending = initKnex(env).migrate.make(name, { extension: ext }).then(function (name) { success(chalk.green('Created Migration: ' + name)); })['catch'](exit); }); commander.command('migrate:latest').description(' Run all migrations that have not yet been run.').action(function () { pending = initKnex(env).migrate.latest().spread(function (batchNo, log) { if (log.length === 0) { success(chalk.cyan('Already up to date')); } success(chalk.green('Batch ' + batchNo + ' run: ' + log.length + ' migrations \n' + chalk.cyan(log.join('\n')))); })['catch'](exit); }); commander.command('migrate:rollback').description(' Rollback the last set of migrations performed.').action(function () { pending = initKnex(env).migrate.rollback().spread(function (batchNo, log) { if (log.length === 0) { success(chalk.cyan('Already at the base migration')); } success(chalk.green('Batch ' + batchNo + ' rolled back: ' + log.length + ' migrations \n') + chalk.cyan(log.join('\n'))); })['catch'](exit); }); commander.command('migrate:currentVersion').description(' View the current version for the migration.').action(function () { pending = initKnex(env).migrate.currentVersion().then(function (version) { success(chalk.green('Current Version: ') + chalk.blue(version)); })['catch'](exit); }); commander.command('seed:make <name>').description(' Create a named seed file.').option('-x [' + filetypes.join('|') + ']', 'Specify the stub extension (default js)').action(function (name) { var ext = (argv.x || env.configPath.split('.').pop()).toLowerCase(); pending = initKnex(env).seed.make(name, { extension: ext }).then(function (name) { success(chalk.green('Created seed file: ' + name)); })['catch'](exit); }); commander.command('seed:run').description(' Run seed files.').action(function () { pending = initKnex(env).seed.run().spread(function (log) { if (log.length === 0) { success(chalk.cyan('No seed files exist')); } success(chalk.green('Ran ' + log.length + ' seed files \n' + chalk.cyan(log.join('\n')))); })['catch'](exit); }); commander.parse(process.argv); Promise.resolve(pending).then(function () { commander.help(); }); } var cli = new Liftoff({ name: 'knex', extensions: interpret.jsVariants, v8flags: require('v8flags') }); cli.on('require', function (name) { console.log('Requiring external module', chalk.magenta(name)); }); cli.on('requireFail', function (name) { console.log(chalk.red('Failed to load external module'), chalk.magenta(name)); }); cli.launch({ cwd: argv.cwd, configPath: argv.knexfile, require: argv.require, completion: argv.completion }, invoke);
faradayio/knex
lib/bin/cli.js
JavaScript
mit
6,131
"use strict"; var _toolsProtectJs2 = require("./../../../tools/protect.js"); var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2); exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _types = require("../../../types"); var t = _interopRequireWildcard(_types); _toolsProtectJs3["default"](module); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function statementList(key, path) { var paths = path.get(key); for (var i = 0; i < paths.length; i++) { var _path = paths[i]; var func = _path.node; if (!t.isFunctionDeclaration(func)) continue; var declar = t.variableDeclaration("let", [t.variableDeclarator(func.id, t.toExpression(func))]); // hoist it up above everything else declar._blockHoist = 2; // todo: name this func.id = null; _path.replaceWith(declar); } } var visitor = { BlockStatement: function BlockStatement(node, parent) { if (t.isFunction(parent) && parent.body === node || t.isExportDeclaration(parent)) { return; } statementList("body", this); }, SwitchCase: function SwitchCase() { statementList("consequent", this); } }; exports.visitor = visitor;
waddedMeat/ember-proxy-example
test-app/node_modules/ember-cli-babel/node_modules/broccoli-babel-transpiler/node_modules/babel-core/lib/babel/transformation/transformers/spec/block-scoped-functions.js
JavaScript
mit
1,469
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * This class provides an abstract grid editing plugin on selected {@link Ext.grid.column.Column columns}. * The editable columns are specified by providing an {@link Ext.grid.column.Column#editor editor} * in the {@link Ext.grid.column.Column column configuration}. * * **Note:** This class should not be used directly. See {@link Ext.grid.plugin.CellEditing} and * {@link Ext.grid.plugin.RowEditing}. */ Ext.define('Ext.grid.plugin.Editing', { alias: 'editing.editing', extend: 'Ext.AbstractPlugin', requires: [ 'Ext.grid.column.Column', 'Ext.util.KeyNav' ], mixins: { observable: 'Ext.util.Observable' }, /** * @cfg {Number} clicksToEdit * The number of clicks on a grid required to display the editor. * The only accepted values are **1** and **2**. */ clicksToEdit: 2, /** * @cfg {String} triggerEvent * The event which triggers editing. Supercedes the {@link #clicksToEdit} configuration. Maybe one of: * * * cellclick * * celldblclick * * cellfocus * * rowfocus */ triggerEvent: undefined, relayedEvents: [ 'beforeedit', 'edit', 'validateedit', 'canceledit' ], // @private defaultFieldXType: 'textfield', // cell, row, form editStyle: '', constructor: function(config) { var me = this; me.addEvents( /** * @event beforeedit * Fires before editing is triggered. Return false from event handler to stop the editing. * * @param {Ext.grid.plugin.Editing} editor * @param {Object} context The editing context with the following properties: * @param {Ext.grid.Panel} context.grid The owning grid Panel. * @param {Ext.data.Model} context.record The record being edited. * @param {String} context.field The name of the field being edited. * @param {Mixed} context.value The field's current value. * @param {HTMLElement} context.row The grid row element. * @param {Ext.grid.column.Column} context.column The Column being edited. * @param {Number} context.rowIdx The index of the row being edited. * @param {Number} context.colIdx The index of the column being edited. * @param {Boolean} context.cancel Set this to `true` to cancel the edit or return false from your handler. * @param {Mixed} context.originalValue Alias for value (only when using {@link Ext.grid.plugin.CellEditing CellEditing}). */ 'beforeedit', /** * @event edit * Fires after a editing. Usage example: * * grid.on('edit', function(editor, e) { * // commit the changes right after editing finished * e.record.commit(); * }); * * @param {Ext.grid.plugin.Editing} editor * @param {Object} context The editing context with the following properties: * @param {Ext.grid.Panel} context.grid The owning grid Panel. * @param {Ext.data.Model} context.record The record being edited. * @param {String} context.field The name of the field being edited. * @param {Mixed} context.value The field's current value. * @param {HTMLElement} context.row The grid row element. * @param {Ext.grid.column.Column} context.column The Column being edited. * @param {Number} context.rowIdx The index of the row being edited. * @param {Number} context.colIdx The index of the column being edited. */ 'edit', /** * @event validateedit * Fires after editing, but before the value is set in the record. Return false from event handler to * cancel the change. * * Usage example showing how to remove the red triangle (dirty record indicator) from some records (not all). By * observing the grid's validateedit event, it can be cancelled if the edit occurs on a targeted row (for example) * and then setting the field's new value in the Record directly: * * grid.on('validateedit', function(editor, e) { * var myTargetRow = 6; * * if (e.rowIdx == myTargetRow) { * e.cancel = true; * e.record.data[e.field] = e.value; * } * }); * * @param {Ext.grid.plugin.Editing} editor * @param {Object} context The editing context with the following properties: * @param {Ext.grid.Panel} context.grid The owning grid Panel. * @param {Ext.data.Model} context.record The record being edited. * @param {String} context.field The name of the field being edited. * @param {Mixed} context.value The field's current value. * @param {HTMLElement} context.row The grid row element. * @param {Ext.grid.column.Column} context.column The Column being edited. * @param {Number} context.rowIdx The index of the row being edited. * @param {Number} context.colIdx The index of the column being edited. */ 'validateedit', /** * @event canceledit * Fires when the user started editing but then cancelled the edit. * @param {Ext.grid.plugin.Editing} editor * @param {Object} context The editing context with the following properties: * @param {Ext.grid.Panel} context.grid The owning grid Panel. * @param {Ext.data.Model} context.record The record being edited. * @param {String} context.field The name of the field being edited. * @param {Mixed} context.value The field's current value. * @param {HTMLElement} context.row The grid row element. * @param {Ext.grid.column.Column} context.column The Column being edited. * @param {Number} context.rowIdx The index of the row being edited. * @param {Number} context.colIdx The index of the column being edited. */ 'canceledit' ); me.callParent(arguments); me.mixins.observable.constructor.call(me); // TODO: Deprecated, remove in 5.0 me.on("edit", function(editor, e) { me.fireEvent("afteredit", editor, e); }); }, // @private init: function(grid) { var me = this; me.grid = grid; me.view = grid.view; me.initEvents(); // Set up fields at render and reconfigure time me.mon(grid, { reconfigure: me.onReconfigure, scope: me, beforerender: { fn: me.onReconfigure, single: true, scope: me } }); grid.relayEvents(me, me.relayedEvents); // If the editable grid is owned by a lockable, relay up another level. if (me.grid.ownerLockable) { me.grid.ownerLockable.relayEvents(me, me.relayedEvents); } // Marks the grid as editable, so that the SelectionModel // can make appropriate decisions during navigation grid.isEditable = true; grid.editingPlugin = grid.view.editingPlugin = me; }, /** * Fires after the grid is reconfigured * @private */ onReconfigure: function() { var grid = this.grid; // In a Lockable assembly, the owner's view aggregates all grid columns across both sides. // We grab all columns here. grid = grid.ownerLockable ? grid.ownerLockable : grid; this.initFieldAccessors(grid.getView().getGridColumns()); }, /** * @private * AbstractComponent calls destroy on all its plugins at destroy time. */ destroy: function() { var me = this, grid = me.grid; Ext.destroy(me.keyNav); // Clear all listeners from all our events, clear all managed listeners we added to other Observables me.clearListeners(); if (grid) { me.removeFieldAccessors(grid.columnManager.getColumns()); grid.editingPlugin = grid.view.editingPlugin = me.grid = me.view = me.editor = me.keyNav = null; } }, // @private getEditStyle: function() { return this.editStyle; }, // @private initFieldAccessors: function(columns) { // If we have been passed a group header, process its leaf headers if (columns.isGroupHeader) { columns = columns.getGridColumns(); } // Ensure we are processing an array else if (!Ext.isArray(columns)) { columns = [columns]; } var me = this, c, cLen = columns.length, column; for (c = 0; c < cLen; c++) { column = columns[c]; if (!column.getEditor) { column.getEditor = function(record, defaultField) { return me.getColumnField(this, defaultField); }; } if (!column.hasEditor) { column.hasEditor = function() { return me.hasColumnField(this); }; } if (!column.setEditor) { column.setEditor = function(field) { me.setColumnField(this, field); }; } } }, // @private removeFieldAccessors: function(columns) { // If we have been passed a group header, process its leaf headers if (columns.isGroupHeader) { columns = columns.getGridColumns(); } // Ensure we are processing an array else if (!Ext.isArray(columns)) { columns = [columns]; } var c, cLen = columns.length, column; for (c = 0; c < cLen; c++) { column = columns[c]; column.getEditor = column.hasEditor = column.setEditor = null; } }, // @private // remaps to the public API of Ext.grid.column.Column.getEditor getColumnField: function(columnHeader, defaultField) { var field = columnHeader.field; if (!(field && field.isFormField)) { field = columnHeader.field = this.createColumnField(columnHeader, defaultField); } return field; }, // @private // remaps to the public API of Ext.grid.column.Column.hasEditor hasColumnField: function(columnHeader) { return !!columnHeader.field; }, // @private // remaps to the public API of Ext.grid.column.Column.setEditor setColumnField: function(columnHeader, field) { columnHeader.field = field; columnHeader.field = this.createColumnField(columnHeader); }, createColumnField: function(columnHeader, defaultField) { var field = columnHeader.field; if (!field && columnHeader.editor) { field = columnHeader.editor; columnHeader.editor = null; } if (!field && defaultField) { field = defaultField; } if (field) { if (field.isFormField) { field.column = columnHeader; } else { if (Ext.isString(field)) { field = { name: columnHeader.dataIndex, xtype: field, column: columnHeader }; } else { field = Ext.apply({ name: columnHeader.dataIndex, column: columnHeader }, field); } field = Ext.ComponentManager.create(field, this.defaultFieldXType); } columnHeader.field = field; } return field; }, // @private initEvents: function() { var me = this; me.initEditTriggers(); me.initCancelTriggers(); }, // @abstract initCancelTriggers: Ext.emptyFn, // @private initEditTriggers: function() { var me = this, view = me.view; // Listen for the edit trigger event. if (me.triggerEvent == 'cellfocus') { me.mon(view, 'cellfocus', me.onCellFocus, me); } else if (me.triggerEvent == 'rowfocus') { me.mon(view, 'rowfocus', me.onRowFocus, me); } else { // Prevent the View from processing when the SelectionModel focuses. // This is because the SelectionModel processes the mousedown event, and // focusing causes a scroll which means that the subsequent mouseup might // take place at a different document XY position, and will therefore // not trigger a click. // This Editor must call the View's focusCell method directly when we recieve a request to edit if (view.getSelectionModel().isCellModel) { view.onCellFocus = Ext.Function.bind(me.beforeViewCellFocus, me); } // Listen for whichever click event we are configured to use me.mon(view, me.triggerEvent || ('cell' + (me.clicksToEdit === 1 ? 'click' : 'dblclick')), me.onCellClick, me); } // add/remove header event listeners need to be added immediately because // columns can be added/removed before render me.initAddRemoveHeaderEvents() // wait until render to initialize keynav events since they are attached to an element view.on('render', me.initKeyNavHeaderEvents, me, {single: true}); }, // Override of View's method so that we can pre-empt the View's processing if the view is being triggered by a mousedown beforeViewCellFocus: function(position) { // Pass call on to view if the navigation is from the keyboard, or we are not going to edit this cell. if (this.view.selModel.keyNavigation || !this.editing || !this.isCellEditable || !this.isCellEditable(position.row, position.columnHeader)) { this.view.focusCell.apply(this.view, arguments); } }, // @private Used if we are triggered by the rowfocus event onRowFocus: function(record, row, rowIdx) { this.startEdit(row, 0); }, // @private Used if we are triggered by the cellfocus event onCellFocus: function(record, cell, position) { this.startEdit(position.row, position.column); }, // @private Used if we are triggered by a cellclick event onCellClick: function(view, cell, colIdx, record, row, rowIdx, e) { // cancel editing if the element that was clicked was a tree expander if(!view.expanderSelector || !e.getTarget(view.expanderSelector)) { this.startEdit(record, view.ownerCt.columnManager.getHeaderAtIndex(colIdx)); } }, initAddRemoveHeaderEvents: function(){ var me = this; me.mon(me.grid.headerCt, { scope: me, add: me.onColumnAdd, remove: me.onColumnRemove, columnmove: me.onColumnMove }); }, initKeyNavHeaderEvents: function() { var me = this; me.keyNav = Ext.create('Ext.util.KeyNav', me.view.el, { enter: me.onEnterKey, esc: me.onEscKey, scope: me }); }, // @private onColumnAdd: function(ct, column) { this.initFieldAccessors(column); }, // @private onColumnRemove: function(ct, column) { this.removeFieldAccessors(column); }, // @private // Inject field accessors on move because if the move FROM the main headerCt and INTO a grouped header, // the accessors will have been deleted but not added. They are added conditionally. onColumnMove: function(headerCt, column, fromIdx, toIdx) { this.initFieldAccessors(column); }, // @private onEnterKey: function(e) { var me = this, grid = me.grid, selModel = grid.getSelectionModel(), record, pos, columnHeader; // Calculate editing start position from SelectionModel if there is a selection // Note that the condition below tests the result of an assignment to the "pos" variable. if (selModel.getCurrentPosition && (pos = selModel.getCurrentPosition())) { record = pos.record; columnHeader = pos.columnHeader; } // RowSelectionModel else { record = selModel.getLastSelected(); columnHeader = grid.columnManager.getHeaderAtIndex(0); } // If there was a selection to provide a starting context... if (record && columnHeader) { me.startEdit(record, columnHeader); } }, // @private onEscKey: function(e) { return this.cancelEdit(); }, /** * @private * @template * Template method called before editing begins. * @param {Object} context The current editing context * @return {Boolean} Return false to cancel the editing process */ beforeEdit: Ext.emptyFn, /** * Starts editing the specified record, using the specified Column definition to define which field is being edited. * @param {Ext.data.Model/Number} record The Store data record which backs the row to be edited, or index of the record in Store. * @param {Ext.grid.column.Column/Number} columnHeader The Column object defining the column to be edited, or index of the column. */ startEdit: function(record, columnHeader) { var me = this, context, layoutView = me.grid.lockable ? me.grid : me.view; // The view must have had a layout to show the editor correctly, defer until that time. // In case a grid's startup code invokes editing immediately. if (!layoutView.componentLayoutCounter) { layoutView.on({ boxready: Ext.Function.bind(me.startEdit, me, [record, columnHeader]), single: true }); return false; } // If grid collapsed, or view not truly visible, don't even calculate a context - we cannot edit if (me.grid.collapsed || !me.grid.view.isVisible(true)) { return false; } context = me.getEditingContext(record, columnHeader); if (context == null) { return false; } if (!me.preventBeforeCheck) { if (me.beforeEdit(context) === false || me.fireEvent('beforeedit', me, context) === false || context.cancel) { return false; } } /** * @property {Boolean} editing * Set to `true` while the editing plugin is active and an Editor is visible. */ me.editing = true; return context; }, // TODO: Have this use a new class Ext.grid.CellContext for use here, and in CellSelectionModel /** * @private * Collects all information necessary for any subclasses to perform their editing functions. * @param record * @param columnHeader * @returns {Object/undefined} The editing context based upon the passed record and column */ getEditingContext: function(record, columnHeader) { var me = this, grid = me.grid, view = me.view, gridRow = view.getNode(record, true), rowIdx, colIdx; // An intervening listener may have deleted the Record if (!gridRow) { return; } // Coerce the column index to the closest visible column columnHeader = grid.columnManager.getVisibleHeaderClosestToIndex(Ext.isNumber(columnHeader) ? columnHeader : columnHeader.getVisibleIndex()); // No corresponding column. Possible if all columns have been moved to the other side of a lockable grid pair if (!columnHeader) { return; } colIdx = columnHeader.getVisibleIndex(); if (Ext.isNumber(record)) { // look up record if numeric row index was passed rowIdx = record; record = view.getRecord(gridRow); } else { rowIdx = view.indexOf(gridRow); } // The record may be removed from the store but the view // not yet updated, so check it exists if (!record) { return; } return { grid : grid, view : view, store : view.dataSource, record : record, field : columnHeader.dataIndex, value : record.get(columnHeader.dataIndex), row : gridRow, column : columnHeader, rowIdx : rowIdx, colIdx : colIdx }; }, /** * Cancels any active edit that is in progress. */ cancelEdit: function() { var me = this; me.editing = false; me.fireEvent('canceledit', me, me.context); }, /** * Completes the edit if there is an active edit in progress. */ completeEdit: function() { var me = this; if (me.editing && me.validateEdit()) { me.fireEvent('edit', me, me.context); } me.context = null; me.editing = false; }, // @abstract validateEdit: function() { var me = this, context = me.context; return me.fireEvent('validateedit', me, context) !== false && !context.cancel; } });
ryancanulla/findMe
web/ext/src/grid/plugin/Editing.js
JavaScript
mit
22,953
'use strict'; var path = require('path'); var url = require('url'); module.exports = attr; function attr(content, block, blockLine, blockContent) { var re = new RegExp('(.*' + block.attr + '=[\'"])([^\'"]*)([\'"].*)', 'gi'); var replaced = false; // Only run attr replacer for the block content var replacedBlock = blockContent.replace(re, function (wholeMatch, start, asset, end) { // Check if only the path was provided to leave the original asset name intact asset = (!path.extname(block.asset) && /\//.test(block.asset)) ? url.resolve(block.asset, path.basename(asset)) : block.asset; replaced = true; return start + asset + end; }); // If the attribute doesn't exist, add it. if (!replaced) { replacedBlock = blockContent.replace(/>/, ' ' + block.attr + '="' + block.asset + '">'); } return content.replace(blockLine, replacedBlock); }
TheLaughingGod1986/web-enterprise-system
node_modules/htmlprocessor/lib/blocktypes/attr.js
JavaScript
mit
888
/** * 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 */ import type {Fiber} from 'react-reconciler/src/ReactFiber'; import { findCurrentHostFiber, findCurrentFiberUsingSlowPath, } from 'react-reconciler/reflection'; import getComponentName from 'shared/getComponentName'; import {HostComponent} from 'shared/ReactWorkTags'; import invariant from 'shared/invariant'; // Module provided by RN: import {UIManager} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface'; import {getClosestInstanceFromNode} from './ReactNativeComponentTree'; const emptyObject = {}; if (__DEV__) { Object.freeze(emptyObject); } let getInspectorDataForViewTag; if (__DEV__) { const traverseOwnerTreeUp = function(hierarchy, instance: any) { if (instance) { hierarchy.unshift(instance); traverseOwnerTreeUp(hierarchy, instance._debugOwner); } }; const getOwnerHierarchy = function(instance: any) { const hierarchy = []; traverseOwnerTreeUp(hierarchy, instance); return hierarchy; }; const lastNonHostInstance = function(hierarchy) { for (let i = hierarchy.length - 1; i > 1; i--) { const instance = hierarchy[i]; if (instance.tag !== HostComponent) { return instance; } } return hierarchy[0]; }; const getHostProps = function(fiber) { const host = findCurrentHostFiber(fiber); if (host) { return host.memoizedProps || emptyObject; } return emptyObject; }; const getHostNode = function(fiber: Fiber | null, findNodeHandle) { let hostNode; // look for children first for the hostNode // as composite fibers do not have a hostNode while (fiber) { if (fiber.stateNode !== null && fiber.tag === HostComponent) { hostNode = findNodeHandle(fiber.stateNode); } if (hostNode) { return hostNode; } fiber = fiber.child; } return null; }; const createHierarchy = function(fiberHierarchy) { return fiberHierarchy.map(fiber => ({ name: getComponentName(fiber.type), getInspectorData: findNodeHandle => ({ measure: callback => UIManager.measure(getHostNode(fiber, findNodeHandle), callback), props: getHostProps(fiber), source: fiber._debugSource, }), })); }; getInspectorDataForViewTag = function(viewTag: number): Object { const closestInstance = getClosestInstanceFromNode(viewTag); // Handle case where user clicks outside of ReactNative if (!closestInstance) { return { hierarchy: [], props: emptyObject, selection: null, source: null, }; } const fiber = findCurrentFiberUsingSlowPath(closestInstance); const fiberHierarchy = getOwnerHierarchy(fiber); const instance = lastNonHostInstance(fiberHierarchy); const hierarchy = createHierarchy(fiberHierarchy); const props = getHostProps(instance); const source = instance._debugSource; const selection = fiberHierarchy.indexOf(instance); return { hierarchy, props, selection, source, }; }; } else { getInspectorDataForViewTag = () => { invariant( false, 'getInspectorDataForViewTag() is not available in production', ); }; } export {getInspectorDataForViewTag};
VioletLife/react
packages/react-native-renderer/src/ReactNativeFiberInspector.js
JavaScript
mit
3,454
const runServer = require('./server'); runServer();
cryogen/throneteki
index.js
JavaScript
mit
53
'use strict'; var _invariant = require('fbjs/lib/invariant'); var _invariant2 = _interopRequireDefault(_invariant); var _React3ComponentFlags = require('./React3ComponentFlags'); var _React3ComponentFlags2 = _interopRequireDefault(_React3ComponentFlags); var _idPropertyName = require('./utils/idPropertyName'); var _idPropertyName2 = _interopRequireDefault(_idPropertyName); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var internalInstanceKey = '__react3InternalInstance$' + Math.random().toString(36).slice(2); /** * Drill down (through composites and empty components) until we get a host or * host text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ // see ReactDOMComponentTree function getRenderedHostOrTextFromComponent(component) { var result = component; var rendered = result._renderedComponent; while (rendered) { result = rendered; rendered = result._renderedComponent; } return result; } /** * Populate `_hostMarkup` on the rendered host/text component with the given * markup. The passed `instance` can be a composite. */ function precacheMarkup(instance, markup) { (0, _invariant2.default)(!!markup, 'Markup is null!'); var hostInstance = getRenderedHostOrTextFromComponent(instance); hostInstance._hostMarkup = markup; markup[internalInstanceKey] = hostInstance; } function uncacheMarkup(inst) { var markup = inst._hostMarkup; if (markup) { delete markup[internalInstanceKey]; inst._hostMarkup = null; } } /** * Populate `_hostMarkup` on each child of `inst`, assuming that the children * match up with the children of `markup`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a markup sequentially and have to walk from the start to our target * markup every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the markups we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child markups are always cached (until it unmounts). */ function precacheChildMarkups(instance, markup) { if ((instance._flags & _React3ComponentFlags2.default.hasCachedChildMarkups) !== 0) { return; } var renderedChildren = instance._renderedChildren; var childrenNames = Object.keys(renderedChildren); var childrenMarkup = markup.childrenMarkup; /* eslint-disable no-labels, no-unused-labels, no-restricted-syntax */ outer: for (var i = 0; i < childrenNames.length; ++i) { /* eslint-enable no-labels, no-unused-labels, no-restricted-syntax */ var childName = childrenNames[i]; var childInst = renderedChildren[childName]; // TODO implement _domID var childID = getRenderedHostOrTextFromComponent(childInst)._hostID; if (childID === 0) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } for (var j = 0; j < childrenMarkup.length; ++j) { var childMarkup = childrenMarkup[j]; if (childMarkup[_idPropertyName2.default] === childID) { precacheMarkup(childInst, childMarkup); continue outer; // eslint-disable-line no-labels } } // We reached the end of the DOM children without finding an ID match. if (process.env.NODE_ENV !== 'production') { (0, _invariant2.default)(false, 'Unable to find element with ID %s.', childID); } else { (0, _invariant2.default)(false); } /* original implementation: // We assume the child nodes are in the same order as the child instances. for (; childMarkup !== null; childMarkup = childMarkup.nextSibling) { if (childMarkup.nodeType === 1 && // Element.ELEMENT_NODE childMarkup.getAttribute(ATTR_NAME) === String(childID) || childMarkup.nodeType === 8 && childMarkup.nodeValue === ` react-text: ${childID} ` || childMarkup.nodeType === 8 && childMarkup.nodeValue === ` react-empty: ${childID} `) { precacheNode(childInst, childMarkup); continue outer; // eslint-disable-line no-labels } } */ } instance._flags |= _React3ComponentFlags2.default.hasCachedChildMarkups; } // see ReactDOMComponentTree:getClosestInstanceFromNode function getClosestInstanceFromMarkup(markup) { if (markup[internalInstanceKey]) { return markup[internalInstanceKey]; } var currentMarkup = markup; // Walk up the tree until we find an ancestor whose instance we have cached. var parentMarkupsWithoutInstanceKey = []; while (!currentMarkup[internalInstanceKey]) { parentMarkupsWithoutInstanceKey.push(currentMarkup); if (currentMarkup.parentMarkup) { currentMarkup = currentMarkup.parentMarkup; } else { // Top of the tree. This markup must not be part of a React tree (or is // unmounted, potentially). return null; } } // if we're here, then currentMarkup does have internalInstanceKey, otherwise // we would have reached the top of the tree and returned null. var closest = void 0; var instance = currentMarkup[internalInstanceKey]; // traversing from greatest ancestor (e.g. parent of all parents) downwards // e.g. walk down the tree now while (instance) { closest = instance; if (!parentMarkupsWithoutInstanceKey.length) { break; } // this will ensure that all children of the current greatest ancestor // have internalInstanceKey precacheChildMarkups(instance, currentMarkup); currentMarkup = parentMarkupsWithoutInstanceKey.pop(); instance = currentMarkup[internalInstanceKey]; } /* original impl of ^ for (; currentMarkup && (instance = currentMarkup[internalInstanceKey]); currentMarkup = parentMarkupsWithoutInstanceKey.pop()) { closest = instance; if (parentMarkupsWithoutInstanceKey.length) { this.precacheChildMarkups(instance, currentMarkup); } } */ return closest; } // see ReactDOMComponentTree:getInstanceFromNode function getInstanceFromMarkup(markup) { var inst = getClosestInstanceFromMarkup(markup); if (inst !== null && inst._hostMarkup === markup) { return inst; } return null; } /** * Given an InternalComponent, return the corresponding * host markup. */ function getMarkupFromInstance(inst) { // Without this first invariant, passing a non-React3-component triggers the next // invariant for a missing parent, which is super confusing. if (process.env.NODE_ENV !== 'production') { (0, _invariant2.default)(inst._hostMarkup !== undefined, 'getMarkupFromInstance: Invalid argument.'); } else { (0, _invariant2.default)(inst._hostMarkup !== undefined); } if (inst._hostMarkup) { return inst._hostMarkup; } var currentInstance = inst; // Walk up the tree until we find an ancestor whose host node we have cached. var parents = []; while (!currentInstance._hostMarkup) { parents.push(currentInstance); (0, _invariant2.default)(currentInstance._hostParent, 'React3 tree root should always have a node reference.'); currentInstance = currentInstance._hostParent; } // Now parents contains each ancestor that does *not* have a cached host // markup, and `currentInstance` is the deepest ancestor that does. for (; parents.length; currentInstance = parents.pop()) { precacheChildMarkups(currentInstance, currentInstance._hostMarkup); } return currentInstance._hostMarkup; } module.exports = { getMarkupFromInstance: getMarkupFromInstance, getInstanceFromMarkup: getInstanceFromMarkup, precacheMarkup: precacheMarkup, uncacheMarkup: uncacheMarkup, precacheChildMarkups: precacheChildMarkups, getClosestInstanceFromMarkup: getClosestInstanceFromMarkup, getRenderedHostOrTextFromComponent: getRenderedHostOrTextFromComponent };
cdnjs/cdnjs
ajax/libs/react-three-renderer/3.2.4/React3ComponentTree.js
JavaScript
mit
8,060
// Animations v1.4, Copyright 2014, Joe Mottershaw, https://github.com/joemottershaw/ // ================================================================================== // Animate function animateElement() { if ($(window).width() >= 960) { $('.animate').each(function(i, elem) { var elem = $(elem), type = $(this).attr('data-anim-type'), delay = $(this).attr('data-anim-delay'); if (elem.visible(true)) { setTimeout(function() { elem.addClass(type); }, delay); } }); } else { $('.animate').each(function(i, elem) { var elem = $(elem), type = $(this).attr('data-anim-type'), delay = $(this).attr('data-anim-delay'); setTimeout(function() { elem.addClass(type); }, delay); }); } } $(document).ready(function() { if ($('html').hasClass('no-js')) $('html').removeClass('no-js').addClass('js'); animateElement(); }); $(window).resize(function() { animateElement(); }); $(window).scroll(function() { animateElement(); if ($(window).scrollTop() + $(window).height() == $(document).height()) animateElement(); }); // Triggers function randomClass() { var random = Math.ceil(Math.random() * classAmount) return classesArray[random]; } function animateOnce(target, type) { if (type == 'random') type = randomClass(); $(target).removeClass('trigger infinite ' + triggerClasses).addClass('trigger').addClass(type).one('webkitAnimationEnd oAnimationEnd MSAnimationEnd animationend', function() { $(this).removeClass('trigger infinite ' + triggerClasses); }); } function animateInfinite(target, type) { if (type == 'random') type = randomClass(); $(target).removeClass('trigger infinite ' + triggerClasses).addClass('trigger infinite').addClass(type).one('webkitAnimationEnd oAnimationEnd MSAnimationEnd animationend', function() { $(this).removeClass('trigger infinite ' + triggerClasses); }); } function animateEnd(target) { $(target).removeClass('trigger infinite ' + triggerClasses); } // Variables var triggerClasses = 'flash strobe shakeH shakeV bounce tada wave spinCW spinCCW slingshotCW slingshotCCW wobble pulse pulsate heartbeat panic', classesArray = new Array, classesArray = triggerClasses.split(' '), classAmount = classesArray.length;
ahmedmakaty/wordpress
wp-content/themes/betheme/js/animations/animations.js
JavaScript
gpl-2.0
2,375
$(document).ready(function() { var switched = false; var updateTables = function() { if (($(window).width() < 1400) && !switched ){ switched = true; $("table.responsive.long").each(function(i, element) { splitTable($(element)); }); return true; } else if (switched && ($(window).width() > 1400)) { switched = false; $("table.responsive.long").each(function(i, element) { unsplitTable($(element)); }); } }; $(window).load(updateTables); $(window).bind("resize", updateTables); function splitTable(original) { original.wrap("<div class='table-wrapper' />"); var copy = original.clone(); copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none"); copy.removeClass("responsive"); original.closest(".table-wrapper").append(copy); copy.wrap("<div class='pinned' />"); original.wrap("<div class='scrollable' />"); } function unsplitTable(original) { original.closest(".table-wrapper").find(".pinned").remove(); original.unwrap(); original.unwrap(); } });
vladapopster/Websms
web/bundles/websms/plugins/tables/responsive-tables/responsive-long-tables.js
JavaScript
gpl-2.0
1,127
/*! * Ext JS Library 3.0.0 * Copyright(c) 2006-2009 Ext JS, LLC * [email protected] * http://www.extjs.com/license */ /** * @class Ext.dd.DropZone * @extends Ext.dd.DropTarget * <p>This class provides a container DD instance that allows dropping on multiple child target nodes.</p> * <p>By default, this class requires that child nodes accepting drop are registered with {@link Ext.dd.Registry}. * However a simpler way to allow a DropZone to manage any number of target elements is to configure the * DropZone with an implementation of {@link #getTargetFromEvent} which interrogates the passed * mouse event to see if it has taken place within an element, or class of elements. This is easily done * by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a * {@link Ext.DomQuery} selector.</p> * <p>Once the DropZone has detected through calling getTargetFromEvent, that the mouse is over * a drop target, that target is passed as the first parameter to {@link #onNodeEnter}, {@link #onNodeOver}, * {@link #onNodeOut}, {@link #onNodeDrop}. You may configure the instance of DropZone with implementations * of these methods to provide application-specific behaviour for these events to update both * application state, and UI state.</p> * <p>For example to make a GridPanel a cooperating target with the example illustrated in * {@link Ext.dd.DragZone DragZone}, the following technique might be used:</p><pre><code> myGridPanel.on('render', function() { myGridPanel.dropZone = new Ext.dd.DropZone(myGridPanel.getView().scroller, { // If the mouse is over a grid row, return that node. This is // provided as the "target" parameter in all "onNodeXXXX" node event handling functions getTargetFromEvent: function(e) { return e.getTarget(myGridPanel.getView().rowSelector); }, // On entry into a target node, highlight that node. onNodeEnter : function(target, dd, e, data){ Ext.fly(target).addClass('my-row-highlight-class'); }, // On exit from a target node, unhighlight that node. onNodeOut : function(target, dd, e, data){ Ext.fly(target).removeClass('my-row-highlight-class'); }, // While over a target node, return the default drop allowed class which // places a "tick" icon into the drag proxy. onNodeOver : function(target, dd, e, data){ return Ext.dd.DropZone.prototype.dropAllowed; }, // On node drop we can interrogate the target to find the underlying // application object that is the real target of the dragged data. // In this case, it is a Record in the GridPanel's Store. // We can use the data set up by the DragZone's getDragData method to read // any data we decided to attach in the DragZone's getDragData method. onNodeDrop : function(target, dd, e, data){ var rowIndex = myGridPanel.getView().findRowIndex(target); var r = myGridPanel.getStore().getAt(rowIndex); Ext.Msg.alert('Drop gesture', 'Dropped Record id ' + data.draggedRecord.id + ' on Record id ' + r.id); return true; } }); } </code></pre> * See the {@link Ext.dd.DragZone DragZone} documentation for details about building a DragZone which * cooperates with this DropZone. * @constructor * @param {Mixed} el The container element * @param {Object} config */ Ext.dd.DropZone = function(el, config){ Ext.dd.DropZone.superclass.constructor.call(this, el, config); }; Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, { /** * Returns a custom data object associated with the DOM node that is the target of the event. By default * this looks up the event target in the {@link Ext.dd.Registry}, although you can override this method to * provide your own custom lookup. * @param {Event} e The event * @return {Object} data The custom data */ getTargetFromEvent : function(e){ return Ext.dd.Registry.getTargetFromEvent(e); }, /** * Called when the DropZone determines that a {@link Ext.dd.DragSource} has entered a drop node * that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}. * This method has no default implementation and should be overridden to provide * node-specific processing if necessary. * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from * {@link #getTargetFromEvent} for this node) * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source */ onNodeEnter : function(n, dd, e, data){ }, /** * Called while the DropZone determines that a {@link Ext.dd.DragSource} is over a drop node * that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}. * The default implementation returns this.dropNotAllowed, so it should be * overridden to provide the proper feedback. * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from * {@link #getTargetFromEvent} for this node) * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source * @return {String} status The CSS class that communicates the drop status back to the source so that the * underlying {@link Ext.dd.StatusProxy} can be updated */ onNodeOver : function(n, dd, e, data){ return this.dropAllowed; }, /** * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dragged out of * the drop node without dropping. This method has no default implementation and should be overridden to provide * node-specific processing if necessary. * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from * {@link #getTargetFromEvent} for this node) * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source */ onNodeOut : function(n, dd, e, data){ }, /** * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped onto * the drop node. The default implementation returns false, so it should be overridden to provide the * appropriate processing of the drop event and return true so that the drag source's repair action does not run. * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from * {@link #getTargetFromEvent} for this node) * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source * @return {Boolean} True if the drop was valid, else false */ onNodeDrop : function(n, dd, e, data){ return false; }, /** * Called while the DropZone determines that a {@link Ext.dd.DragSource} is being dragged over it, * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so * it should be overridden to provide the proper feedback if necessary. * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source * @return {String} status The CSS class that communicates the drop status back to the source so that the * underlying {@link Ext.dd.StatusProxy} can be updated */ onContainerOver : function(dd, e, data){ return this.dropNotAllowed; }, /** * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped on it, * but not on any of its registered drop nodes. The default implementation returns false, so it should be * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to * be able to accept drops. It should return true when valid so that the drag source's repair action does not run. * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source * @return {Boolean} True if the drop was valid, else false */ onContainerDrop : function(dd, e, data){ return false; }, /** * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source is now over * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops * you should override this method and provide a custom implementation. * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source * @return {String} status The CSS class that communicates the drop status back to the source so that the * underlying {@link Ext.dd.StatusProxy} can be updated */ notifyEnter : function(dd, e, data){ return this.dropNotAllowed; }, /** * The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the drop zone. * This method will be called on every mouse movement while the drag source is over the drop zone. * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a * registered node, it will call {@link #onContainerOver}. * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source * @return {String} status The CSS class that communicates the drop status back to the source so that the * underlying {@link Ext.dd.StatusProxy} can be updated */ notifyOver : function(dd, e, data){ var n = this.getTargetFromEvent(e); if(!n){ // not over valid drop target if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } return this.onContainerOver(dd, e, data); } if(this.lastOverNode != n){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); } this.onNodeEnter(n, dd, e, data); this.lastOverNode = n; } return this.onNodeOver(n, dd, e, data); }, /** * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source has been dragged * out of the zone without dropping. If the drag source is currently over a registered node, the notification * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored. * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag zone */ notifyOut : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } }, /** * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the dragged item has * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling, * otherwise it will call {@link #onContainerDrop}. * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone * @param {Event} e The event * @param {Object} data An object containing arbitrary data supplied by the drag source * @return {Boolean} True if the drop was valid, else false */ notifyDrop : function(dd, e, data){ if(this.lastOverNode){ this.onNodeOut(this.lastOverNode, dd, e, data); this.lastOverNode = null; } var n = this.getTargetFromEvent(e); return n ? this.onNodeDrop(n, dd, e, data) : this.onContainerDrop(dd, e, data); }, // private triggerCacheRefresh : function(){ Ext.dd.DDM.refreshCache(this.groups); } });
sguazt/dcsj-sharegrid-portal
web/resources/scripts/ext/src/dd/DropZone.js
JavaScript
gpl-3.0
13,815
const MANY_VARS = Math.pow(2,17); var code = "function f1() {\n"; code += " var x0 = 0"; for (var i = 1; i < MANY_VARS; i++) code += ", x" + i + " = " + i; code += ";\n"; for (var i = 0; i < MANY_VARS; i += 100) code += " assertEq(x" + i + ", " + i + ");\n"; code += " return x80000;\n"; code += "}\n"; eval(code); assertEq(f1(), 80000);
JasonGross/mozjs
js/src/jit-test/tests/basic/testManyVars.js
JavaScript
mpl-2.0
350
define(["js/views/baseview", "underscore", "underscore.string", "jquery"], function(BaseView, _, str, $) { var SystemFeedback = BaseView.extend({ options: { title: "", message: "", intent: null, // "warning", "confirmation", "error", "announcement", "step-required", etc type: null, // "alert", "notification", or "prompt": set by subclass shown: true, // is this view currently being shown? icon: true, // should we render an icon related to the message intent? closeIcon: true, // should we render a close button in the top right corner? minShown: 0, // length of time after this view has been shown before it can be hidden (milliseconds) maxShown: Infinity // length of time after this view has been shown before it will be automatically hidden (milliseconds) /* Could also have an "actions" hash: here is an example demonstrating the expected structure. For each action, by default the framework will call preventDefault on the click event before the function is run; to make it not do that, just pass `preventDefault: false` in the action object. actions: { primary: { "text": "Save", "class": "action-save", "click": function(view) { // do something when Save is clicked } }, secondary: [ { "text": "Cancel", "class": "action-cancel", "click": function(view) {} }, { "text": "Discard Changes", "class": "action-discard", "click": function(view) {} } ] } */ }, initialize: function() { if(!this.options.type) { throw "SystemFeedback: type required (given " + JSON.stringify(this.options) + ")"; } if(!this.options.intent) { throw "SystemFeedback: intent required (given " + JSON.stringify(this.options) + ")"; } this.template = this.loadTemplate("system-feedback"); this.setElement($("#page-"+this.options.type)); // handle single "secondary" action if (this.options.actions && this.options.actions.secondary && !_.isArray(this.options.actions.secondary)) { this.options.actions.secondary = [this.options.actions.secondary]; } return this; }, // public API: show() and hide() show: function() { clearTimeout(this.hideTimeout); this.options.shown = true; this.shownAt = new Date(); this.render(); if($.isNumeric(this.options.maxShown)) { this.hideTimeout = setTimeout(_.bind(this.hide, this), this.options.maxShown); } return this; }, hide: function() { if(this.shownAt && $.isNumeric(this.options.minShown) && this.options.minShown > new Date() - this.shownAt) { clearTimeout(this.hideTimeout); this.hideTimeout = setTimeout(_.bind(this.hide, this), this.options.minShown - (new Date() - this.shownAt)); } else { this.options.shown = false; delete this.shownAt; this.render(); } return this; }, // the rest of the API should be considered semi-private events: { "click .action-close": "hide", "click .action-primary": "primaryClick", "click .action-secondary": "secondaryClick" }, render: function() { // there can be only one active view of a given type at a time: only // one alert, only one notification, only one prompt. Therefore, we'll // use a singleton approach. var singleton = SystemFeedback["active_"+this.options.type]; if(singleton && singleton !== this) { singleton.stopListening(); singleton.undelegateEvents(); } this.$el.html(this.template(this.options)); SystemFeedback["active_"+this.options.type] = this; return this; }, primaryClick: function(event) { var actions = this.options.actions; if(!actions) { return; } var primary = actions.primary; if(!primary) { return; } if(primary.preventDefault !== false) { event.preventDefault(); } if(primary.click) { primary.click.call(event.target, this, event); } }, secondaryClick: function(event) { var actions = this.options.actions; if(!actions) { return; } var secondaryList = actions.secondary; if(!secondaryList) { return; } // which secondary action was clicked? var i = 0; // default to the first secondary action (easier for testing) if(event && event.target) { i = _.indexOf(this.$(".action-secondary"), event.target); } var secondary = secondaryList[i]; if(secondary.preventDefault !== false) { event.preventDefault(); } if(secondary.click) { secondary.click.call(event.target, this, event); } } }); return SystemFeedback; });
jswope00/GAI
cms/static/js/views/feedback.js
JavaScript
agpl-3.0
5,884
var indexerLanguage="en"; //Auto generated index for searching by xsl-webhelpindexer for DocBook Webhelp.# Kasun Gajasinghe, University of Moratuwa w["-"]="2*5,6*1,9*2"; w["-doutput-dir"]="8*1"; w["-version"]="8*2"; w["."]="2*5,3*2,4*3,5*5,6*1,8*10,9*3,10*8,13*2,14*1,15*3"; w[".chm"]="6*1"; w[".htaccess"]="4*1"; w[".html"]="4*1"; w[".js"]="2*2"; w[".nexwave.nquindexer.indexermain"]="9*1"; w[".nexwave.nquindexer.indexertask"]="9*1"; w[".treeview"]="5*1"; w["0"]="0*2,3*1,8*5,9*6"; w["1"]="0*6,1*46,3*2,8*8,9*6,11*1,13*10"; w["1."]="0*6,3*2,8*1,13*2"; w["1.5"]="9*1"; w["1.6"]="8*1"; w["1.76.0"]="9*1"; w["1.76.1"]="9*2"; w["1.76.1."]="9*1"; w["1.77.0"]="0*2"; w["1.8.0"]="8*3,9*1"; w["1.8.2.custom.css"]="15*1"; w["172800"]="4*2"; w["2"]="0*6,3*2,4*2,8*1,10*5,11*1,15*1,16*46"; w["2."]="0*6,3*1,10*1"; w["2.0"]="3*1"; w["2006"]="3*1"; w["2008"]="3*1"; w["2008-2012"]="3*1"; w["2012"]="3*2"; w["290304000"]="4*2"; w["2:"]="8*1"; w["3"]="0*8,3*1,10*5"; w["3."]="0*6,3*1,10*1"; w["3.0.0.jar"]="9*2"; w["3.x"]="0*1"; w["4"]="0*7,2*1,8*1"; w["4."]="0*6"; w["480"]="4*1"; w["5"]="0*8,1*46,6*1,8*3,9*1,11*48,16*46"; w["5."]="0*6,11*2"; w["5.1."]="1*2,11*1"; w["5.2."]="11*1,16*2"; w["596"]="0*2"; w["596:"]="0*2"; w["6"]="8*4"; w["6.5"]="8*3"; w["6.5.5.jar"]="0*1,8*1"; w["6.5.x"]="8*1"; w["7"]="0*1"; w["7200"]="4*2"; w["76"]="9*3"; w["77"]="0*2"; w["8"]="4*1,8*3,9*1,15*1"; w[":"]="0*2,10*2,15*3"; w["_stemmer"]="2*1,10*1"; w["_stemmer.j"]="2*2,10*2"; w["abandon"]="5*1"; w["abov"]="3*1"; w["abstract"]="15*1"; w["accord"]="6*1"; w["achiev"]="5*2"; w["action"]="3*1"; w["actual"]="2*1"; w["ad"]="2*1,3*1,6*1,7*2,10*3,13*51,14*46,15*2"; w["adapt"]="8*1"; w["add"]="3*1,6*1,8*1,10*14,13*1,14*1,15*1"; w["adddefaultcharset"]="4*1"; w["addit"]="0*1,4*1,8*1,14*1"; w["addoutputfilterbytyp"]="4*9"; w["admon"]="8*1"; w["admon.graph"]="8*2"; w["advertis"]="3*1"; w["after"]="6*1"; w["against"]="8*2"; w["age"]="4*3"; w["al"]="10*1"; w["algorithm"]="10*1"; w["all"]="0*1,2*2,3*2,4*1,5*1,6*1,7*1,8*2,9*2,10*2,12*1,13*1,14*1,15*1"; w["all."]="10*1"; w["allow"]="8*1"; w["alreadi"]="10*1"; w["also"]="3*1,8*1"; w["altern"]="6*1"; w["analyz"]="9*1"; w["and"]="0*4,2*6,3*12,4*4,5*3,6*6,7*2,8*9,9*4,10*8,12*5,14*5,15*51"; w["ani"]="3*6,8*1,10*1,15*1"; w["anim"]="5*1"; w["animated:"]="5*1"; w["anoth"]="8*2,10*1"; w["ant"]="2*3,6*2,8*15,9*14,10*2,13*1"; w["ant.file.dir"]="8*2"; w["ant_hom"]="8*1,9*1"; w["apach"]="3*2,4*41,7*1,8*3,15*1"; w["apache-ant-1"]="8*2"; w["apache-ant-1.8.0"]="8*2"; w["apart"]="0*2"; w["apis.jar"]="0*2,8*4,9*1"; w["appear"]="6*2,15*1"; w["appli"]="5*2"; w["applic"]="4*5,6*1"; w["applica"]="4*1"; w["appropri"]="8*1,15*1"; w["[email protected]"]="10*1"; w["ar"]="3*1"; w["arbitrari"]="8*1"; w["argument"]="9*1"; w["arguments:"]="9*1"; w["aris"]="3*1"; w["array"]="2*3,3*1,10*7"; w["array."]="10*1"; w["ask"]="0*1"; w["associ"]="3*1"; w["assum"]="8*2,10*1"; w["assumpt"]="2*1"; w["attribut"]="0*2"; w["author"]="3*1"; w["auto"]="6*1"; w["auto-synchron"]="6*1"; w["autoidx"]="0*2"; w["autoidx.xsl"]="0*2"; w["autoidx.xsl:"]="0*4"; w["automat"]="9*1"; w["avail"]="3*1,8*1,9*2,10*3"; w["away"]="12*1"; w["back"]="14*1"; w["backward"]="6*1"; w["bar."]="15*1"; w["base"]="0*1,3*52,5*1,6*2,10*5,15*1"; w["basedir"]="8*1"; w["basic"]="0*1"; w["be"]="8*1"; w["been"]="8*1"; w["behav"]="12*1"; w["below"]="8*1"; w["below."]="8*1,13*1"; w["better"]="8*1"; w["between"]="2*1,3*1"; w["bi"]="2*1"; w["bi-gram"]="2*1"; w["bin"]="8*4"; w["binari"]="8*1"; w["bit"]="9*1"; w["bitmap"]="4*1"; w["bits."]="9*1"; w["bob"]="4*1,15*1"; w["bold"]="6*1"; w["book"]="4*1"; w["both"]="14*1"; w["box"]="6*1"; w["break"]="2*1"; w["brief"]="6*1,15*1"; w["brower"]="4*1"; w["browser"]="0*4,2*2,3*1,4*2,5*2,6*1,7*1,8*2,9*1,10*1,12*1,13*1,14*1,15*1"; w["browser."]="0*1,2*1,3*1,4*1,5*1,6*1,7*1,8*2,9*1,10*1,12*1,13*1,14*1,15*1"; w["bsd"]="3*2"; w["bsd-style"]="3*1"; w["build"]="0*3,1*1,5*1,6*3,8*13,9*1,10*3,13*1,16*1"; w["build-index"]="10*1"; w["build.properti"]="8*1,9*1,10*1,13*1"; w["build.xml"]="1*1,8*11,16*1"; w["build.xml."]="8*1"; w["built"]="5*1"; w["but"]="3*1,8*1,10*2"; w["button"]="5*1"; w["buy"]="1*1,16*1"; w["c"]="0*2,3*1,8*3"; w["c:"]="0*4,8*3"; w["cach"]="4*5"; w["cache-control"]="4*3"; w["call"]="2*1,5*1"; w["can"]="0*6,2*3,5*2,6*5,8*4,9*1,10*3,13*1,15*2"; w["caus"]="4*3,15*1"; w["certain"]="4*1"; w["ch03"]="2*1"; w["ch03.html"]="2*1"; w["chang"]="2*1,3*1,4*1,8*1,9*1,10*3,15*3"; w["chapter"]="2*1,11*4,12*1,15*1"; w["chapterinfo"]="15*1"; w["charact"]="4*1"; w["charg"]="3*1"; w["check"]="0*1"; w["checkout"]="2*1"; w["chines"]="2*1,3*1,6*1,8*1,10*2"; w["chm"]="6*1"; w["chrome"]="0*1"; w["chunk"]="5*2,6*1,15*2"; w["cjk"]="2*2,10*2"; w["cjkv"]="7*1,10*1,14*2"; w["claim"]="3*1"; w["class"]="9*1,10*1"; w["classpath"]="0*1,8*5,9*2"; w["classpath."]="9*1"; w["click."]="2*1"; w["client"]="2*2,6*1"; w["client-sid"]="2*1,6*1"; w["cn"]="10*2"; w["co"]="3*1"; w["code"]="0*1,2*1,3*4,5*1,6*1,10*9,13*6"; w["code."]="10*1"; w["code:"]="5*1"; w["collaps"]="5*1,6*1"; w["collapsed:"]="5*1"; w["color"]="6*1,15*1"; w["come"]="9*1,15*1"; w["command"]="2*2,8*4,9*1"; w["command-lin"]="9*1"; w["command."]="2*1"; w["comment"]="8*1"; w["comments."]="8*1"; w["common"]="2*1,3*1,6*1,15*7"; w["commons:"]="8*1"; w["compani"]="5*1"; w["compar"]="2*1"; w["compil"]="10*1"; w["complet"]="4*3,15*1"; w["compress"]="4*3"; w["concern"]="9*1"; w["condit"]="3*1"; w["conditions:"]="3*1"; w["conf"]="4*1"; w["configur"]="4*40,7*1,15*1"; w["confirm"]="8*3"; w["confus"]="3*1"; w["connect"]="3*1"; w["consid"]="14*1"; w["contact"]="10*1"; w["contain"]="2*1,3*1,8*1,9*1,10*1"; w["content"]="2*4,3*2,5*6,6*5,7*5,9*1,10*2,11*5,12*8"; w["content."]="2*1,9*1"; w["content.format"]="2*1"; w["content:"]="5*1"; w["contract"]="3*1"; w["contribut"]="3*1,14*1"; w["contributor"]="3*1"; w["control"]="4*3,5*1,13*1,15*1"; w["control:"]="5*1"; w["conveni"]="8*2"; w["cooki"]="3*1,5*1,12*2"; w["copi"]="3*3,8*3,10*1,13*2"; w["copyright"]="3*5"; w["core"]="9*1"; w["correct"]="0*1,3*1,8*1,10*5"; w["cosmet"]="3*1"; w["could"]="4*1,8*1"; w["cramer"]="3*4"; w["creat"]="2*1,6*1,8*4"; w["credit"]="3*1"; w["csrc"]="8*2"; w["css"]="4*5,5*3,6*1,15*8"; w["css-base"]="5*1,6*1"; w["css-style"]="5*1"; w["css."]="15*1"; w["currenc"]="1*2,16*1"; w["current"]="0*1,10*3,14*1"; w["currently."]="0*1"; w["custom"]="5*2,7*1,8*1,15*48"; w["d"]="0*1,8*1"; w["damag"]="3*1"; w["danish"]="14*1"; w["data"]="2*1"; w["david"]="3*6"; w["day"]="1*1,4*1,16*1"; w["deal"]="3*3"; w["deep"]="15*1"; w["default"]="2*1,8*1,9*2,15*1"; w["default."]="8*1"; w["defin"]="2*1,8*1"; w["deflat"]="4*10"; w["delet"]="8*1"; w["demo"]="0*4"; w["deploy"]="0*3"; w["deriv"]="3*3"; w["describ"]="7*1"; w["descript"]="6*1"; w["description."]="6*1"; w["design"]="2*1,5*47,12*1"; w["desir"]="8*2"; w["desired-output-dir"]="8*1"; w["detail"]="0*1,2*2,3*1,8*1,9*2"; w["details."]="0*1,3*1,8*1,9*1"; w["develop"]="3*1,12*51"; w["differ"]="3*1,8*1"; w["dir"]="8*6,13*1"; w["direct"]="9*1,15*1"; w["directori"]="2*2,3*1,8*15,9*3,13*4"; w["directory."]="2*1,8*4,13*1"; w["disabl"]="0*1,2*1,3*1,4*1,5*1,6*1,7*1,8*2,9*1,10*1,12*1,13*1,14*1,15*1"; w["display"]="2*1"; w["distribut"]="3*2,8*2,9*1"; w["dita"]="0*1,3*3"; w["dita-us"]="3*1"; w["dita."]="0*1"; w["div"]="5*1,12*1,15*2"; w["divid"]="5*1"; w["do"]="2*2,3*1,8*2,9*1,14*1"; w["doc"]="2*1,8*3,12*51,15*7"; w["docbkx"]="6*1,8*1"; w["docbo"]="0*2"; w["docbook"]="0*2,2*2,3*52,4*3,5*3,8*5,9*1,10*8,13*2,15*2"; w["docbook-apps@list"]="10*1"; w["[email protected]"]="10*1"; w["docbook-webhelp"]="8*1,10*7"; w["docbook-xsl-1"]="0*1"; w["docbook-xsl-1.77.0"]="0*2"; w["docbook."]="15*1"; w["docbook.sourceforge.net"]="9*2"; w["docs@@@"]="2*1"; w["docsbook"]="9*1"; w["docsbook-xsl-1"]="9*1"; w["docsbook-xsl-1.76.1"]="9*1"; w["docsr"]="13*6"; w["docsrc"]="13*1"; w["document"]="0*2,3*1,4*2,5*1,6*1,8*10,13*4"; w["document."]="8*2,13*1"; w["documentation."]="0*1,5*1,6*1"; w["doe"]="0*2,2*2,4*1,8*1,9*1"; w["does."]="4*1"; w["doesn"]="9*1"; w["don"]="8*1,15*1"; w["donat"]="3*1"; w["done"]="0*1,2*1,5*2"; w["dostem"]="2*1"; w["dot"]="3*4"; w["doutput"]="8*1"; w["down"]="3*1,13*5"; w["download"]="4*1,8*1,9*1,10*1"; w["drop"]="2*1"; w["dtd"]="8*1"; w["dtd."]="8*1"; w["dutch"]="14*1"; w["e"]="8*1,10*1,12*1"; w["each"]="4*1,6*1"; w["easi"]="10*1"; w["easili"]="5*1,10*2"; w["easily."]="10*1"; w["eclips"]="6*1"; w["edit"]="8*1,15*1"; w["editor"]="3*1,8*1,10*1"; w["editor."]="3*1"; w["efault"]="8*1"; w["element"]="15*1"; w["element."]="0*2,15*1"; w["els"]="9*1,10*7"; w["email"]="10*1"; w["empti"]="8*1"; w["enabl"]="0*1,2*1,3*1,4*1,5*1,6*1,7*1,8*2,9*1,10*1,12*1,13*1,14*1,15*1"; w["enable.stem"]="8*1"; w["endors"]="9*1"; w["engin"]="3*1,6*1"; w["engine."]="6*1"; w["english"]="2*1,6*1,8*1,10*3,14*1"; w["englishstemm"]="10*1"; w["enjoy"]="0*1,2*1,3*1,4*1,5*1,6*1,7*1,8*1,9*1,10*1,12*1,13*1,14*1,15*1"; w["environ"]="8*4,9*1"; w["equalsignorecas"]="10*3"; w["error"]="0*2"; w["error."]="0*2"; w["etc"]="2*1,5*1,6*1,8*1"; w["etc."]="2*1,5*1,6*1,8*3,15*1"; w["event"]="3*1"; w["ex"]="2*1"; w["ex:"]="2*1"; w["exact"]="10*1,12*1"; w["exampl"]="3*6,8*5,10*5,13*13,15*1"; w["example."]="10*1"; w["example:"]="8*4"; w["except"]="3*1"; w["exist"]="2*1,3*1"; w["exist."]="3*1,8*1"; w["explain"]="4*1"; w["expos"]="6*1"; w["express"]="3*1"; w["ext"]="10*2"; w["extend"]="10*2"; w["extens"]="0*2,2*1,4*1,8*2,9*1,10*1";
yuri0x7c1/ofbiz-explorer
src/test/resources/apache-ofbiz-16.11.03/specialpurpose/cmssite/template/docbook/webhelp/docs/content/search/index-1.js
JavaScript
apache-2.0
9,288
// Copyright (c) 2013-2014 Marco Biasini // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. (function(exports) { "use strict"; // atom covalent radii by element derived from Cambrige Structural Database. // Source: http://profmokeur.ca/chemistry/covalent_radii.htm var ELEMENT_COVALENT_RADII = { H : 0.31, HE : 0.28, LI : 1.28, BE : 0.96, B : 0.84, C : 0.76, N : 0.71, O : 0.66, F : 0.57, NE : 0.58, NA : 1.66, MG : 1.41, AL : 1.21, SI : 1.11, P : 1.07, S : 1.05, CL : 1.02, AR : 1.06, K : 2.03, CA : 1.76, SC : 1.70, TI : 1.60, V : 1.53, CR : 1.39, MN : 1.39, FE : 1.32, CO : 1.26, NI : 1.24, CU : 1.32, ZN : 1.22, GA : 1.22, GE : 1.20, AS : 1.19, SE : 1.20, BR : 1.20, KR : 1.16, RB : 2.20, SR : 1.95, Y : 1.90, ZR : 1.75, NB : 1.64, MO : 1.54, TC : 1.47, RU : 1.46, RH : 1.42, PD : 1.39, AG : 1.45, CD : 1.44, IN : 1.42, SN : 1.39, SB : 1.39, TE : 1.38, I : 1.39, XE : 1.40, CS : 2.44, BA : 2.15, LA : 2.07, CE : 2.04, PR : 2.03, ND : 2.01, PM : 1.99, SM : 1.98, EU : 1.98, GD : 1.96, TB : 1.94, DY : 1.92, HO : 1.92, ER : 1.89, TM : 1.90, YB : 1.87, LU : 1.87, HF : 1.75, TA : 1.70, W : 1.62, RE : 1.51, OS : 1.44, IR : 1.41, PT : 1.36, AU : 1.36, HG : 1.32, TL : 1.45, PB : 1.46, BI : 1.48, PO : 1.40, AT : 1.50, RN : 1.50, FR : 2.60, RA : 2.21, AC : 2.15, TH : 2.06, PA : 2.00, U : 1.96, NP : 1.90, PU : 1.87, AM : 1.80, CM : 1.69 }; function covalentRadius(ele) { var r = ELEMENT_COVALENT_RADII[ele.toUpperCase()]; if (r !== undefined) { return r; } return 1.5; } // combines the numeric part of the residue number with the insertion // code and returns a single number. Note that this is completely safe // and we do not have to worry about overflows, as for PDB files the // range of permitted residue numbers is quite limited anyway. function rnumInsCodeHash(num, insCode) { return num << 8 | insCode.charCodeAt(0); } //----------------------------------------------------------------------------- // MolBase, ChainBase, ResidueBase, AtomBase //----------------------------------------------------------------------------- function MolBase() { } MolBase.prototype.eachResidue = function(callback) { for (var i = 0; i < this._chains.length; i+=1) { if (this._chains[i].eachResidue(callback) === false) { return false; } } }; MolBase.prototype.eachAtom = function(callback, index) { index |= 0; for (var i = 0; i < this._chains.length; i+=1) { index = this._chains[i].eachAtom(callback, index); if (index === false) { return false; } } }; MolBase.prototype.residueCount = function () { var chains = this.chains(); var count = 0; for (var ci = 0; ci < chains.length; ++ci) { count += chains[ci].residues().length; } return count; }; MolBase.prototype.eachChain = function(callback) { var chains = this.chains(); for (var i = 0; i < chains.length; ++i) { if (callback(chains[i]) === false) { return; } } }; MolBase.prototype.atomCount = function() { var chains = this.chains(); var count = 0; for (var ci = 0; ci < chains.length; ++ci) { count += chains[ci].atomCount(); } return count; }; MolBase.prototype.atoms = function() { var atoms = []; this.eachAtom(function(atom) { atoms.push(atom); }); return atoms; }; MolBase.prototype.atom = function(name) { var parts = name.split('.'); var chain = this.chain(parts[0]); if (chain === null) { return null; } var residue = chain.residueByRnum(parseInt(parts[1], 10)); if (residue === null) { return null; } return residue.atom(parts[2]); }; MolBase.prototype.center = function() { var sum = vec3.create(); var count = 0; this.eachAtom(function(atom) { vec3.add(sum, sum, atom.pos()); count+=1; }); if (count) { vec3.scale(sum, sum, 1/count); } return sum; }; // returns a sphere containing all atoms part of this structure. This will not // calculate the minimal bounding sphere, just a good-enough approximation. MolBase.prototype.boundingSphere = function() { var center = this.center(); var radiusSquare = 0.0; this.eachAtom(function(atom) { radiusSquare = Math.max(radiusSquare, vec3.sqrDist(center, atom.pos())); }); return new Sphere(center, radiusSquare); }; // returns all backbone traces of all chains of this structure MolBase.prototype.backboneTraces = function() { var chains = this.chains(); var traces = []; for (var i = 0; i < chains.length; ++i) { Array.prototype.push.apply(traces, chains[i].backboneTraces()); } return traces; }; MolBase.prototype.select = function(what) { if (what === 'protein') { return this.residueSelect(function(r) { return r.isAminoacid(); }); } if (what === 'water') { return this.residueSelect(function(r) { return r.isWater(); }); } if (what === 'ligand') { return this.residueSelect(function(r) { return !r.isAminoacid() && !r.isWater(); }); } // when what is not one of the simple strings above, we assume what // is a dictionary containing predicates which have to be fulfilled. return this._dictSelect(what); }; MolBase.prototype.selectWithin = (function() { var dist = vec3.create(); return function(mol, options) { console.time('Mol.selectWithin'); options = options || {}; var radius = options.radius || 4.0; var radiusSqr = radius*radius; var matchResidues = !!options.matchResidues; var targetAtoms = []; mol.eachAtom(function(a) { targetAtoms.push(a); }); var view = new MolView(this.full()); var addedRes = null, addedChain = null; var chains = this.chains(); var skipResidue = false; for (var ci = 0; ci < chains.length; ++ci) { var residues = chains[ci].residues(); addedChain = null; for (var ri = 0; ri < residues.length; ++ri) { addedRes = null; skipResidue = false; var atoms = residues[ri].atoms(); for (var ai = 0; ai < atoms.length; ++ai) { if (skipResidue) { break; } for (var wi = 0; wi < targetAtoms.length; ++wi) { vec3.sub(dist, atoms[ai].pos(), targetAtoms[wi].pos()); if (vec3.sqrLen(dist) > radiusSqr) { continue; } if (!addedChain) { addedChain = view.addChain(chains[ci].full(), false); } if (!addedRes) { addedRes = addedChain.addResidue(residues[ri].full(), matchResidues); } if (matchResidues) { skipResidue = true; break; } addedRes.addAtom(atoms[ai].full()); } } } } console.timeEnd('Mol.selectWithin'); return view; }; })(); MolBase.prototype.residueSelect = function(predicate) { console.time('Mol.residueSelect'); var view = new MolView(this.full()); for (var ci = 0; ci < this._chains.length; ++ci) { var chain = this._chains[ci]; var chainView = null; var residues = chain.residues(); for (var ri = 0; ri < residues.length; ++ri) { if (predicate(residues[ri])) { if (!chainView) { chainView = view.addChain(chain, false); } chainView.addResidue(residues[ri], true); } } } console.timeEnd('Mol.residueSelect'); return view; }; MolBase.prototype._atomPredicates = function(dict) { var predicates = []; if (dict.aname !== undefined) { predicates.push(function(a) { return a.name() === dict.aname; }); } if (dict.anames !== undefined) { predicates.push(function(a) { var n = a.name(); for (var k = 0; k < dict.anames.length; ++k) { if (n === dict.anames[k]) { return true; } } return false; }); } return predicates; }; // extracts the residue predicates from the dictionary. // ignores rindices, rindexRange because they are handled separately. MolBase.prototype._residuePredicates = function(dict) { var predicates = []; if (dict.rname !== undefined) { predicates.push(function(r) { return r.name() === dict.rname; }); } if (dict.rnames !== undefined) { predicates.push(function(r) { var n = r.name(); for (var k = 0; k < dict.rnames.length; ++k) { if (n === dict.rnames[k]) { return true; } } return false; }); } if (dict.rnums !== undefined) { var num_set = {}; for (var i = 0; i < dict.rnums.length; ++i) { num_set[dict.rnums[i]] = true; } predicates.push(function(r) { var n = r.num(); return num_set[n] === true; }); } return predicates; }; MolBase.prototype._chainPredicates = function(dict) { var predicates = []; if (dict.cname !== undefined) { dict.chain = dict.cname; } if (dict.cnames !== undefined) { dict.chains = dict.cnames; } if (dict.chain !== undefined) { predicates.push(function(c) { return c.name() === dict.chain; }); } if (dict.chains !== undefined) { predicates.push(function(c) { var n = c.name(); for (var k = 0; k < dict.chains.length; ++k) { if (n === dict.chains[k]) { return true; } } return false; }); } return predicates; }; function fulfillsPredicates(obj, predicates) { for (var i = 0; i < predicates.length; ++i) { if (!predicates[i](obj)) { return false; } } return true; } MolBase.prototype._dictSelect = function(dict) { var view = new MolView(this); var residuePredicates = this._residuePredicates(dict); var atomPredicates = this._atomPredicates(dict); var chainPredicates = this._chainPredicates(dict); for (var ci = 0; ci < this._chains.length; ++ci) { var chain = this._chains[ci]; if (!fulfillsPredicates(chain, chainPredicates)) { continue; } var chainView = null; var residues = chain.residues(); if (dict.rindex) { dict.rindices = [dict.rindex]; } if (dict.rnumRange) { residues = chain.residuesInRnumRange(dict.rnumRange[0], dict.rnumRange[1]); } var selResidues = [], i, e; if (dict.rindexRange !== undefined) { for (i = dict.rindexRange[0], e = Math.min(residues.length, dict.rindexRange[1]); i < e; ++i) { selResidues.push(residues[i]); } residues = selResidues; } else if (dict.rindices) { if (dict.rindices.length !== undefined) { selResidues = []; for (i = 0; i < dict.rindices.length; ++i) { selResidues.push(residues[dict.rindices[i]]); } residues = selResidues; } } for (var ri = 0; ri < residues.length; ++ri) { if (!fulfillsPredicates(residues[ri], residuePredicates)) { continue; } if (!chainView) { chainView = view.addChain(chain, false); } var residueView = null; var atoms = residues[ri].atoms(); for (var ai = 0; ai < atoms.length; ++ai) { if (!fulfillsPredicates(atoms[ai], atomPredicates)) { continue; } if (!residueView) { residueView = chainView.addResidue(residues[ri], false); } residueView.addAtom(atoms[ai]); } } } return view; }; function rnumComp(lhs, rhs) { return lhs.num() < rhs.num(); } function numify(val) { return { num : function() { return val; }}; } MolBase.prototype.assembly = function(id) { var assemblies = this.assemblies(); for (var i = 0; i < assemblies.length; ++i) { if (assemblies[i].name() === id) { return assemblies[i]; } } return null; }; function ChainBase() { } ChainBase.prototype.eachAtom = function(callback, index) { index |= 0; for (var i = 0; i< this._residues.length; i+=1) { index = this._residues[i].eachAtom(callback, index); if (index === false) { return false; } } return index; }; ChainBase.prototype.atomCount = function() { var count = 0; var residues = this.residues(); for (var ri = 0; ri < residues.length; ++ri) { count+= residues[ri].atoms().length; } return count; }; ChainBase.prototype.eachResidue = function(callback) { for (var i = 0; i < this._residues.length; i+=1) { if (callback(this._residues[i]) === false) { return false; } } }; ChainBase.prototype.residues = function() { return this._residues; }; ChainBase.prototype.structure = function() { return this._structure; }; ChainBase.prototype.asView = function() { var view = new MolView(this.structure().full()); view.addChain(this, true); return view; }; ChainBase.prototype.residueByRnum = function(rnum) { var residues = this.residues(); if (this._rnumsOrdered) { var index = binarySearch(residues, numify(rnum), rnumComp); if (index === -1) { return null; } return residues[index]; } else { for (var i = 0; i < residues.length; ++i) { if (residues[i].num() === rnum) { return residues[i]; } } return null; } }; ChainBase.prototype.prop = function(propName) { return this[propName](); }; function ResidueBase() { } ResidueBase.prototype.prop = function(propName) { return this[propName](); }; ResidueBase.prototype.isWater = function() { return this.name() === 'HOH' || this.name() === 'DOD'; }; ResidueBase.prototype.eachAtom = function(callback, index) { index |= 0; for (var i =0; i< this._atoms.length; i+=1) { if (callback(this._atoms[i], index) === false) { return false; } index +=1; } return index; }; ResidueBase.prototype.qualifiedName = function() { return this.chain().name()+'.'+this.name()+this.num(); }; ResidueBase.prototype.atom = function(index_or_name) { if (typeof index_or_name === 'string') { for (var i =0; i < this._atoms.length; ++i) { if (this._atoms[i].name() === index_or_name) { return this._atoms[i]; } } return null; } if (index_or_name >= this._atoms.length && index_or_name < 0) { return null; } return this._atoms[index_or_name]; }; // CA for amino acids, P for nucleotides, nucleosides ResidueBase.prototype.centralAtom = function() { if (this.isAminoacid()) { return this.atom('CA'); } if (this.isNucleotide()) { return this.atom('C3\''); } return null; }; ResidueBase.prototype.center = function() { var count = 0; var c = vec3.create(); this.eachAtom(function(atom) { vec3.add(c, c, atom.pos()); count += 1; }); if (count > 0) { vec3.scale(c, c, 1.0/count); } return c; }; ResidueBase.prototype.isAminoacid = function() { return this._isAminoacid; }; ResidueBase.prototype.isNucleotide = function() { return this._isNucleotide; }; function AtomBase() { } AtomBase.prototype.name = function() { return this._name; }; AtomBase.prototype.pos = function() { return this._pos; }; AtomBase.prototype.element = function() { return this._element; }; AtomBase.prototype.index = function() { return this._index; }; AtomBase.prototype.prop = function(propName) { return this[propName](); }; AtomBase.prototype.bondCount = function() { return this.bonds().length; }; AtomBase.prototype.eachBond = function(callback) { var bonds = this.bonds(); for (var i = 0, e = bonds.length; i < e; ++i) { callback(bonds[i]); } }; //----------------------------------------------------------------------------- // Mol, Chain, Residue, Atom, Bond //----------------------------------------------------------------------------- function Mol(pv) { MolBase.prototype.constructor.call(this); this._chains = []; this._assemblies = []; this._pv = pv; this._nextAtomIndex = 0; } derive(Mol, MolBase); Mol.prototype.addAssembly = function(assembly) { this._assemblies.push(assembly); }; Mol.prototype.setAssemblies = function(assemblies) { this._assemblies = assemblies; }; Mol.prototype.assemblies = function() { return this._assemblies; }; Mol.prototype.chains = function() { return this._chains; }; Mol.prototype.full = function() { return this; }; Mol.prototype.containsResidue = function(residue) { return residue.full().structure() === this; }; Mol.prototype.chain = function(name) { for (var i = 0; i < this._chains.length; ++i) { if (this._chains[i].name() === name) { return this._chains[i]; } } return null; }; Mol.prototype.nextAtomIndex = function() { var nextIndex = this._nextAtomIndex; this._nextAtomIndex+=1; return nextIndex; }; Mol.prototype.addChain = function(name) { var chain = new Chain(this, name); this._chains.push(chain); return chain; }; Mol.prototype.connect = function(atom_a, atom_b) { var bond = new Bond(atom_a, atom_b); atom_a.addBond(bond); atom_b.addBond(bond); return bond; }; function connectPeptides(structure, left, right) { var cAtom = left.atom('C'); var nAtom = right.atom('N'); if (cAtom && nAtom) { var sqrDist = vec3.sqrDist(cAtom.pos(), nAtom.pos()); if (sqrDist < 1.6*1.6) { structure.connect(nAtom, cAtom); } } } function connectNucleotides(structure, left, right) { var o3Prime = left.atom('O3\''); var pAtom = right.atom('P'); if (o3Prime && pAtom) { var sqrDist = vec3.sqrDist(o3Prime.pos(), pAtom.pos()); // FIXME: make sure 1.7 is a good threshold here... if (sqrDist < 1.7*1.7) { structure.connect(o3Prime, pAtom); } } } // determine connectivity structure. for simplicity only connects atoms of the // same residue and peptide bonds Mol.prototype.deriveConnectivity = function() { console.time('Mol.deriveConnectivity'); var this_structure = this; var prevResidue = null; this.eachResidue(function(res) { var sqr_dist; var d = vec3.create(); for (var i = 0; i < res.atoms().length; i+=1) { var atomI = res.atom(i); var covalentI = covalentRadius(atomI.element()); for (var j = 0; j < i; j+=1) { var atomJ = res.atom(j); var covalentJ = covalentRadius(atomJ.element()); sqr_dist = vec3.sqrDist(atomI.pos(), atomJ.pos()); var lower = covalentI+covalentJ-0.30; var upper = covalentI+covalentJ+0.30; if (sqr_dist < upper*upper && sqr_dist > lower*lower) { this_structure.connect(res.atom(i), res.atom(j)); } } } res._deduceType(); if (prevResidue !== null) { if (res.isAminoacid() && prevResidue.isAminoacid()) { connectPeptides(this_structure, prevResidue, res); } if (res.isNucleotide() && prevResidue.isNucleotide()) { connectNucleotides(this_structure, prevResidue, res); } } prevResidue = res; }); console.timeEnd('Mol.deriveConnectivity'); }; function Chain(structure, name) { ChainBase.prototype.constructor.call(this); this._structure = structure; this._name = name; this._cachedTraces = []; this._residues = []; this._rnumsOrdered = true; } derive(Chain, ChainBase); Chain.prototype.name = function() { return this._name; }; Chain.prototype.full = function() { return this; }; Chain.prototype.addResidue = function(name, num, insCode) { insCode = insCode || '\0'; var residue = new Residue(this, name, num, insCode); if (this._residues.length > 0 && this._rnumsOrdered) { var combinedRNum = rnumInsCodeHash(num, insCode); var last = this._residues[this._residues.length-1]; var lastCombinedRNum = rnumInsCodeHash(last.num(),last.insCode()); this._rnumsOrdered = lastCombinedRNum < combinedRNum; } this._residues.push(residue); return residue; }; Chain.prototype.residuesInRnumRange = function(start, end) { // FIXME: this currently only works with the numeric part, insertion // codes are not honoured. var matching = []; var i, e; if (this._rnumsOrdered === true) { // binary search our way to heaven var startIdx = indexFirstLargerEqualThan(this._residues, numify(start), rnumComp); if (startIdx === -1) { return matching; } var endIdx = indexLastSmallerEqualThan(this._residues, numify(end), rnumComp); if (endIdx === -1) { return matching; } for (i = startIdx; i <= endIdx; ++i) { matching.push(this._residues[i]); } } else { for (i = 0, e = this._residues.length; i !== e; ++i) { var res = this._residues[i]; if (res.num() >= start && res.num() <= end) { matching.push(res); } } } return matching; }; // assigns secondary structure to residues in range from_num to to_num. Chain.prototype.assignSS = function(fromNumAndIns, toNumAndIns, ss) { // FIXME: when the chain numbers are completely ordered, perform binary // search to identify range of residues to assign secondary structure to. var from = rnumInsCodeHash(fromNumAndIns[0], fromNumAndIns[1]); var to = rnumInsCodeHash(toNumAndIns[0], toNumAndIns[1]); for (var i = 1; i < this._residues.length-1; ++i) { var res = this._residues[i]; // FIXME: we currently don't set the secondary structure of the first and // last residue of helices and sheets. that takes care of better // transitions between coils and helices. ideally, this should be done // in the cartoon renderer, NOT in this function. var combined = rnumInsCodeHash(res.num(), res.insCode()); if (combined <= from || combined >= to) { continue; } res.setSS(ss); } }; // invokes a callback for each connected stretch of amino acids. these // stretches are used for all trace-based rendering styles, e.g. sline, // line_trace, tube, cartoon etc. Chain.prototype.eachBackboneTrace = function(callback) { this._cacheBackboneTraces(); for (var i=0; i < this._cachedTraces.length; ++i) { callback(this._cachedTraces[i]); } }; Chain.prototype._cacheBackboneTraces = function() { if (this._cachedTraces.length > 0) { return; } var stretch = new BackboneTrace(); // true when the stretch consists of amino acid residues, false // if the stretch consists of nucleotides. var aaStretch = null; for (var i = 0; i < this._residues.length; i+=1) { var residue = this._residues[i]; var isAminoacid = residue.isAminoacid(); var isNucleotide = residue.isNucleotide(); if ((aaStretch === true && !isAminoacid) || (aaStretch === false && !isNucleotide) || (aaStretch === null && !isNucleotide && !isAminoacid)) { // a break in the trace: push stretch if there were enough residues // in it and create new backbone trace. if (stretch.length() > 1) { this._cachedTraces.push(stretch); } aaStretch = null; stretch = new BackboneTrace(); continue; } if (stretch.length() === 0) { stretch.push(residue); aaStretch = residue.isAminoacid(); continue; } // these checks are on purpose more relaxed than the checks we use in // deriveConnectivity(). We don't really care about correctness of bond // lengths here. The only thing that matters is that the residues are // more or less close so that they could potentially/ be connected. var prevAtom, thisAtom; if (aaStretch) { prevAtom = this._residues[i-1].atom('C'); thisAtom = residue.atom('N'); } else { prevAtom = this._residues[i-1].atom('O3\''); thisAtom = residue.atom('P'); } var sqrDist = vec3.sqrDist(prevAtom.pos(), thisAtom.pos()); if (Math.abs(sqrDist - 1.5*1.5) < 1) { stretch.push(residue); } else { if (stretch.length() > 1) { this._cachedTraces.push(stretch); stretch = new BackboneTrace(); } } } if (stretch.length() > 1) { this._cachedTraces.push(stretch); } }; // returns all connected stretches of amino acids found in this chain as // a list. Chain.prototype.backboneTraces = function() { var traces = []; this.eachBackboneTrace(function(trace) { traces.push(trace); }); return traces; }; function Residue(chain, name, num, insCode) { ResidueBase.prototype.constructor.call(this); this._name = name; this._num = num; this._insCode = insCode; this._atoms = []; this._ss = 'C'; this._chain = chain; this._isAminoacid = false; this._isNucleotide = false; this._index = chain.residues().length; } derive(Residue, ResidueBase); Residue.prototype._deduceType = function() { this._isNucleotide = this.atom('P')!== null && this.atom('C3\'') !== null; this._isAminoacid = this.atom('N') !== null && this.atom('CA') !== null && this.atom('C') !== null && this.atom('O') !== null; }; Residue.prototype.name = function() { return this._name; }; Residue.prototype.insCode = function() { return this._insCode; }; Residue.prototype.num = function() { return this._num; }; Residue.prototype.full = function() { return this; }; Residue.prototype.addAtom = function(name, pos, element) { var atom = new Atom(this, name, pos, element, this.structure().nextAtomIndex()); this._atoms.push(atom); return atom; }; Residue.prototype.ss = function() { return this._ss; }; Residue.prototype.setSS = function(ss) { this._ss = ss; }; Residue.prototype.index = function() { return this._index; }; Residue.prototype.atoms = function() { return this._atoms; }; Residue.prototype.chain = function() { return this._chain; }; Residue.prototype.structure = function() { return this._chain.structure(); }; function Atom(residue, name, pos, element, index) { AtomBase.prototype.constructor.call(this); this._residue = residue; this._bonds = []; this._name = name; this._pos = pos; this._index = index; this._element = element; } derive(Atom, AtomBase); Atom.prototype.addBond = function(bond) { this._bonds.push(bond); }; Atom.prototype.name = function() { return this._name; }; Atom.prototype.bonds = function() { return this._bonds; }; Atom.prototype.residue = function() { return this._residue; }; Atom.prototype.structure = function() { return this._residue.structure(); }; Atom.prototype.full = function() { return this; }; Atom.prototype.qualifiedName = function() { return this.residue().qualifiedName()+'.'+this.name(); }; var Bond = function(atom_a, atom_b) { var self = { atom_one : atom_a, atom_two : atom_b }; return { atom_one : function() { return self.atom_one; }, atom_two : function() { return self.atom_two; }, // calculates the mid-point between the two atom positions mid_point : function(out) { if (!out) { out = vec3.create(); } vec3.add(out, self.atom_one.pos(), self.atom_two.pos()); vec3.scale(out, out, 0.5); return out; } }; }; //----------------------------------------------------------------------------- // MolView, ChainView, ResidueView, AtomView //----------------------------------------------------------------------------- function MolView(mol) { MolBase.prototype.constructor.call(this); this._mol = mol; this._chains = []; } derive(MolView, MolBase); MolView.prototype.full = function() { return this._mol; }; MolView.prototype.assemblies = function() { return this._mol.assemblies(); }; // add chain to view MolView.prototype.addChain = function(chain, recurse) { var chainView = new ChainView(this, chain.full()); this._chains.push(chainView); if (recurse) { var residues = chain.residues(); for (var i = 0; i< residues.length; ++i) { chainView.addResidue(residues[i], true); } } return chainView; }; MolView.prototype.containsResidue = function(residue) { if (!residue) { return false; } var chain = this.chain(residue.chain().name()); if (!chain) { return false; } return chain.containsResidue(residue); }; MolView.prototype.chains = function() { return this._chains; }; MolView.prototype.chain = function(name) { for (var i = 0; i < this._chains.length; ++i) { if (this._chains[i].name() === name) { return this._chains[i]; } } return null; }; function ChainView(molView, chain) { ChainBase.prototype.constructor.call(this); this._chain = chain; this._residues = []; this._molView = molView; this._residueMap = {}; } derive(ChainView, ChainBase); ChainView.prototype.addResidue = function(residue, recurse) { var resView = new ResidueView(this, residue.full()); this._residues.push(resView); this._residueMap[residue.full().index()] = resView; if (recurse) { var atoms = residue.atoms(); for (var i = 0; i < atoms.length; ++i) { resView.addAtom(atoms[i].full()); } } return resView; }; ChainView.prototype.containsResidue = function(residue) { var resView = this._residueMap[residue.full().index()]; if (resView === undefined) { return false; } return resView.full() === residue.full(); }; ChainView.prototype.eachBackboneTrace = function(callback) { // backbone traces for the view must be based on the the full // traces for the following reasons: // - we must be able to display subsets with one residue in length, // when they are part of a larger trace. // - when a trace residue is not at the end, e.g. the C-terminal or // N-terminal end of the full trace, the trace residue starts // midway between the residue and the previous, and ends midway // between the residue and the next. // - the tangents for the Catmull-Rom spline depend on the residues // before and after. Thus, to get the same curvature for a // trace subset, the residues before and after must be taken // into account. var fullTraces = this._chain.backboneTraces(); var traceSubsets = []; for (var i = 0; i < fullTraces.length; ++i) { var subsets = fullTraces[i].subsets(this._residues); for (var j = 0; j < subsets.length; ++j) { callback(subsets[j]); } } }; ChainView.prototype.backboneTraces = function() { var traces = []; this.eachBackboneTrace(function(trace) { traces.push(trace); }); return traces; }; ChainView.prototype.full = function() { return this._chain; }; ChainView.prototype.name = function () { return this._chain.name(); }; ChainView.prototype.structure = function() { return this._molView; }; function ResidueView(chainView, residue) { ResidueBase.prototype.constructor.call(this); this._chainView = chainView; this._atoms = []; this._residue = residue; } derive(ResidueView, ResidueBase); ResidueView.prototype.addAtom = function(atom) { var atomView = new AtomView(this, atom.full()); this._atoms.push(atomView); }; ResidueView.prototype.full = function() { return this._residue; }; ResidueView.prototype.num = function() { return this._residue.num(); }; ResidueView.prototype.insCode = function() { return this._residue.insCode(); }; ResidueView.prototype.ss = function() { return this._residue.ss(); }; ResidueView.prototype.index = function() { return this._residue.index(); }; ResidueView.prototype.chain = function() { return this._chainView; }; ResidueView.prototype.name = function() { return this._residue.name(); }; ResidueView.prototype.atoms = function() { return this._atoms; }; ResidueView.prototype.qualifiedName = function() { return this._residue.qualifiedName(); }; ResidueView.prototype.containsResidue = function(residue) { return this._residue.full() === residue.full(); }; function AtomView(resView, atom) { AtomBase.prototype.constructor.call(this); this._resView = resView; this._atom = atom; this._bonds = []; } derive(AtomView, AtomBase); AtomView.prototype.full = function() { return this._atom; }; AtomView.prototype.name = function() { return this._atom.name(); }; AtomView.prototype.pos = function() { return this._atom.pos(); }; AtomView.prototype.element = function() { return this._atom.element(); }; AtomView.prototype.residue = function() { return this._resView; }; AtomView.prototype.bonds = function() { return this._atom.bonds(); }; AtomView.prototype.index = function() { return this._atom.index(); }; AtomView.prototype.qualifiedName = function() { return this._atom.qualifiedName(); }; var zhangSkolnickSS = (function() { var posOne = vec3.create(); var posTwo = vec3.create(); return function(trace, i, distances, delta) { for (var j = Math.max(0, i-2); j <= i; ++j) { for (var k = 2; k < 5; ++k) { if (j+k >= trace.length()) { continue; } var d = vec3.dist(trace.posAt(posOne, j), trace.posAt(posTwo, j+k)); if (Math.abs(d - distances[k-2]) > delta) { return false; } } } return true; }; })(); var isHelical = function(trace, i) { var helixDistances = [5.45, 5.18, 6.37]; var helixDelta = 2.1; return zhangSkolnickSS(trace, i, helixDistances, helixDelta); }; var isSheet = function(trace, i) { var sheetDistances = [6.1, 10.4, 13.0]; var sheetDelta = 1.42; return zhangSkolnickSS(trace, i, sheetDistances, sheetDelta); }; function traceAssignHelixSheet(trace) { for (var i = 0; i < trace.length(); ++i) { if (isHelical(trace, i)) { trace.residueAt(i).setSS('H'); continue; } if (isSheet(trace, i)) { trace.residueAt(i).setSS('E'); continue; } trace.residueAt(i).setSS('C'); } } // assigns secondary structure information based on a simple and very fast // algorithm published by Zhang and Skolnick in their TM-align paper. // Reference: // // TM-align: a protein structure alignment algorithm based on the Tm-score // (2005) NAR, 33(7) 2302-2309 function assignHelixSheet(structure) { console.time('mol.assignHelixSheet'); var chains = structure.chains(); for (var ci = 0; ci < chains.length; ++ci) { var chain = chains[ci]; chain.eachBackboneTrace(traceAssignHelixSheet); } console.timeEnd('mol.assignHelixSheet'); } exports.mol = {}; exports.mol.Mol = Mol; exports.mol.Chain = Chain; exports.mol.Residue = Residue; exports.mol.Atom = Atom; exports.mol.MolView = MolView; exports.mol.ChainView = ChainView; exports.mol.ResidueView = ResidueView; exports.mol.AtomView = AtomView; exports.mol.assignHelixSheet = assignHelixSheet; return true; })(this);
haoyuchen1992/modular-file-renderer
mfr/extensions/pdb/static/js/mol.js
JavaScript
apache-2.0
35,162
'use strict'; import _ from 'lodash'; import File from 'vinyl'; import gulp from 'gulp'; import merge from 'merge-stream'; import sprity from 'sprity'; import svgSprite from 'gulp-svg-sprite'; import through2 from 'through2'; import { humanize, titleize } from 'underscore.string'; /** Names of directories containing icons. */ const ICON_CATEGORIES = [ 'action', 'alert', 'av', 'communication', 'content', 'editor', 'file', 'hardware', 'image', 'maps', 'navigation', 'notification', 'places', 'social', 'toggle', ]; /** Standard PNG colors. */ const PNG_COLORS = [ 'black', 'white', ]; /** * Generates PNG sprites and their corresponding CSS files for each category of * icon, and places them in `sprites/css-sprite`. * * TODO(shyndman): Add support for double density sprites. */ gulp.task('png-sprites', () => _(getCategoryColorPairs()) .map(([ category, color ]) => sprity.src({ src: `./${ category }/1x_web/*_${ color }_24dp.png`, style: `sprite-${ category }-${ color }.css`, name: `sprite-${ category }-${ color }`, engine: 'sprity-gm', orientation: 'left-right' })) .thru(merge) .value() .pipe(gulp.dest('./sprites/css-sprite/'))); /** * Generates CSS and Symbol-based SVG sprites for each category, and places * them in `sprites/svg-sprite`. */ gulp.task('svg-sprites', () => _(ICON_CATEGORIES) .map((category) => gulp.src(`./${ category }/svg/production/*_24px.svg`) .pipe(svgSprite(getSvgSpriteConfig(category)))) .thru(merge) .value() .pipe(gulp.dest('./sprites/svg-sprite'))); /** * Generates a file to allow the consumption of the icon font by Iconjar * (http://geticonjar.com/). */ gulp.task('iconjar', () => gulp.src('./iconfont/codepoints') .pipe(generateIjmap('MaterialIcons-Regular.ijmap')) .pipe(gulp.dest('./iconfont/'))); /** Runs all tasks. */ gulp.task('default', ['png-sprites', 'svg-sprites', 'iconjar']); /** * Returns a stream that transforms between our icon font's codepoint file * and an Iconjar ijmap. */ function generateIjmap(ijmapPath) { return through2.obj((codepointsFile, encoding, callback) => { const ijmap = { icons: codepointsToIjmap(codepointsFile.contents.toString()) }; callback(null, new File({ path: ijmapPath, contents: new Buffer(JSON.stringify(ijmap), 'utf8') })); function codepointsToIjmap(codepoints) { return _(codepoints) .split('\n') // split into lines .reject(_.isEmpty) // remove empty lines .reduce((codepointMap, line) => { // build up the codepoint map let [ name, codepoint ] = line.split(' '); codepointMap[codepoint] = { name: titleize(humanize(name)) }; return codepointMap; }, {}); } }); } /** * Returns the SVG sprite configuration for the specified category. */ function getSvgSpriteConfig(category) { return { shape: { dimension: { maxWidth: 24, maxHeight: 24 }, }, mode: { css : { bust: false, dest: './', sprite: `./svg-sprite-${ category }.svg`, example: { dest: `./svg-sprite-${ category }.html` }, render: { css: { dest: `./svg-sprite-${ category }.css` } } }, symbol : { bust: false, dest: './', sprite: `./svg-sprite-${ category }-symbol.svg`, example: { dest: `./svg-sprite-${ category }-symbol.html` } } } }; } /** * Returns the catesian product of categories and colors. */ function getCategoryColorPairs() { return _(ICON_CATEGORIES) .map((category) => _.zip(_.times(PNG_COLORS.length, () => category), PNG_COLORS)) .flatten() // flattens 1 level .value(); }
christoga/cepatsembuh
www/bower_components/material-design-icons/gulpfile.babel.js
JavaScript
mit
3,887
var nomnom = require('../nomnom'), assert = require('assert'); var options = nomnom() .opts({ config: { string: '-c PATH, --config=PATH', default: 'config.json', help: 'JSON file with tests to run' }, debug: { string: '-d, --debug', help: 'Print debugging info' } }) .parseArgs(["-d", "--config=test.json"]); assert.ok(options.debug); assert.equal(options.config, "test.json"); var options = nomnom.parseArgs(["-xvf", "--file=test.js"]); assert.ok(options.x); assert.equal(options.file, "test.js"); var parser = nomnom() .usage("test"); assert.equal(parser.getUsage(), "test"); var parser = nomnom() .scriptName("test") .help("help"); assert.equal(parser.getUsage(), "Usage: test\nhelp\n");
mhogeweg/Terraformer
dist/node/Parsers/WKT/node_modules/jison/node_modules/nomnom/test/chain.js
JavaScript
mit
770
/** * @file * Handles asynchronous requests for order editing forms. */ var customer_select = ''; var add_product_browser = ''; var order_save_holds = 0; /** * Add the double click behavior to the order table at admin/store/orders. */ Drupal.behaviors.ucOrderClick = function(context) { $('.uc-orders-table tr.odd, .uc-orders-table tr.even:not(.ucOrderClick-processed)', context).addClass('ucOrderClick-processed').each( function() { $(this).dblclick( function() { var url = Drupal.settings.ucURL.adminOrders + this.id.substring(6); window.location = url; } ); } ); } /** * Add the submit behavior to the order form */ Drupal.behaviors.ucOrderSubmit = function(context) { $('#uc-order-edit-form:not(.ucOrderSubmit-processed)', context).addClass('ucOrderSubmit-processed').submit( function() { $('#products-selector').empty().removeClass(); $('#delivery_address_select').empty().removeClass(); $('#billing_address_select').empty().removeClass(); $('#customer-select').empty().removeClass(); } ); } $(document).ready( function() { if (order_save_holds == 0) { release_held_buttons(); } $('.uc-orders-table tr.odd, .uc-orders-table tr.even').each( function() { $(this).dblclick( function() { var url = Drupal.settings.ucURL.adminOrders + this.id.substring(6); window.location = url; } ); } ); $('#uc-order-edit-form').submit( function() { $('#products-selector').empty().removeClass(); $('#delivery_address_select').empty().removeClass(); $('#billing_address_select').empty().removeClass(); $('#customer-select').empty().removeClass(); } ); } ); /** * Copy the shipping data on the order edit screen to the corresponding billing * fields if they exist. */ function uc_order_copy_shipping_to_billing() { if ($('#edit-delivery-zone').html() != $('#edit-billing-zone').html()) { $('#edit-billing-zone').empty().append($('#edit-delivery-zone').children().clone()); } $('#uc-order-edit-form input, select, textarea').each( function() { if (this.id.substring(0, 13) == 'edit-delivery') { $('#edit-billing' + this.id.substring(13)).val($(this).val()); } } ); } /** * Copy the billing data on the order edit screen to the corresponding shipping * fields if they exist. */ function uc_order_copy_billing_to_shipping() { if ($('#edit-billing-zone').html() != $('#edit-delivery-zone').html()) { $('#edit-delivery-zone').empty().append($('#edit-billing-zone').children().clone()); } $('#uc-order-edit-form input, select, textarea').each( function() { if (this.id.substring(0, 12) == 'edit-billing') { $('#edit-delivery' + this.id.substring(12)).val($(this).val()); } } ); } /** * Load the address book div on the order edit screen. */ function load_address_select(uid, div, address_type) { var options = { 'uid' : uid, 'type' : address_type, 'func' : "apply_address('" + address_type + "', this.value);" }; $.post(Drupal.settings.ucURL.adminOrders + 'address_book', options, function (contents) { $(div).empty().addClass('address-select-box').append(contents); } ); } /** * Apply the selected address to the appropriate fields in the order edit form. */ function apply_address(type, address_str) { eval('var address = ' + address_str + ';'); $('#edit-' + type + '-first-name').val(address['first_name']); $('#edit-' + type + '-last-name').val(address['last_name']); $('#edit-' + type + '-phone').val(address['phone']); $('#edit-' + type + '-company').val(address['company']); $('#edit-' + type + '-street1').val(address['street1']); $('#edit-' + type + '-street2').val(address['street2']); $('#edit-' + type + '-city').val(address['city']); $('#edit-' + type + '-postal-code').val(address['postal_code']); if ($('#edit-' + type + '-country').val() != address['country']) { $('#edit-' + type + '-country').val(address['country']); try { uc_update_zone_select('edit-' + type + '-country', address['zone']); } catch (err) {} } $('#edit-' + type + '-zone').val(address['zone']); } /** * Close the address book div. */ function close_address_select(div) { $(div).empty().removeClass('address-select-box'); return false; } /** * Load the customer select div on the order edit screen. */ function load_customer_search() { if (customer_select == 'search' && $('#customer-select #edit-back').val() == null) { return close_customer_select(); } $.post(Drupal.settings.ucURL.adminOrders + 'customer', {}, function (contents) { $('#customer-select').empty().addClass('customer-select-box').append(contents); $('#customer-select #edit-first-name').val($('#edit-billing-first-name').val()); $('#customer-select #edit-last-name').val($('#edit-billing-last-name').val()); customer_select = 'search'; } ); return false; } /** * Display the results of the customer search. */ function load_customer_search_results() { $.post(Drupal.settings.ucURL.adminOrders + 'customer/search', { first_name: $('#customer-select #edit-first-name').val(), last_name: $('#customer-select #edit-last-name').val(), email: $('#customer-select #edit-email').val() }, function (contents) { $('#customer-select').empty().append(contents); } ); return false; } /** * Set customer values from search selection. */ function select_customer_search() { var data = $('#edit-cust-select').val(); $('#edit-uid').val(data.substr(0, data.indexOf(':'))); $('#edit-uid-text').val(data.substr(0, data.indexOf(':'))); $('#edit-primary-email').val(data.substr(data.indexOf(':') + 1)); $('#edit-primary-email-text').val(data.substr(data.indexOf(':') + 1)); try { $('#edit-submit-changes').get(0).click(); } catch (err) { } return close_customer_select(); } /** * Display the new customer form. */ function load_new_customer_form() { if (customer_select == 'new') { return close_customer_select(); } $.post(Drupal.settings.ucURL.adminOrders + 'customer/new', {}, function (contents) { $('#customer-select').empty().addClass('customer-select-box').append(contents); customer_select = 'new'; } ); return false; } /** * Validate the customer's email address. */ function check_new_customer_address() { var options = { 'email' : $('#customer-select #edit-email').val(), 'sendmail' : $('#customer-select #edit-sendmail').attr('checked') }; $.post(Drupal.settings.ucURL.adminOrders + 'customer/new/check', options, function (contents) { $('#customer-select').empty().append(contents); } ); return false; } /** * Load existing customer as new order's customer. */ function select_existing_customer(uid, email) { $('#edit-uid').val(uid); $('#edit-uid-text').val(uid); $('#edit-primary-email').val(email); $('#edit-primary-email-text').val(email); try { $('#edit-submit-changes').click(); } catch (err) { } return close_customer_select(); } /** * Hide the customer selection form. */ function close_customer_select() { $('#customer-select').empty().removeClass('customer-select-box'); customer_select = ''; return false; } /** * Load the products div on the order edit screen. */ function uc_order_load_product_edit_div(order_id) { $(document).ready( function() { add_order_save_hold(); show_product_throbber(); $.post(Drupal.settings.ucURL.adminOrders + order_id + '/products', { action: 'view' }, function(contents) { if (contents != '') { $('#products-container').empty().append(contents); } remove_order_save_hold(); hide_product_throbber(); }); } ); } /** * Load the product selection form. */ function load_product_select(order_id, search) { if (search == true) { options = {'search' : $('#edit-product-search').val()}; } else { options = { }; } show_product_throbber(); $.post(Drupal.settings.ucURL.adminOrders + order_id + '/product_select', options, function (contents) { $('#products-selector').empty().addClass('product-select-box2').append(contents); hide_product_throbber(); } ); return false; } /** * Deprecated? */ function select_product() { add_product_form(); return false; } /** * Hide product selection form. */ function close_product_select() { $('#products-selector').empty().removeClass('product-select-box2'); return false; } /** * Load the quantity and other extra product fields. */ function add_product_form() { add_product_browser = $('#products-selector').html(); show_product_throbber(); if (parseInt($('#edit-unid').val()) > 0) { $.post(Drupal.settings.ucURL.adminOrders + $('#edit-order-id').val() + '/add_product/' + $('#edit-unid').val(), { }, function(contents) { $('#products-selector').empty().append(contents); hide_product_throbber(); } ); } } /** * Add the selected product to the order. */ function add_product_to_order(order_id, node_id) { var post_vars = fetch_product_data(); post_vars['action'] = 'add'; post_vars['nid'] = node_id; post_vars['qty'] = $('#edit-add-qty').val(); $('#uc-order-add-product-form :input').not(':radio:not(:checked), :checkbox:not(:checked)').each( function() { post_vars[$(this).attr('name')] = $(this).val(); } ); show_product_throbber(); $.post(Drupal.settings.ucURL.adminOrders + order_id + '/products', post_vars, function(contents) { if (contents != '') { $('#products-container').empty().append(contents); } hide_product_throbber(); } ); $('#add-product-button').click(); return false; } /** * Gather all of the products' data fields into one array. */ function fetch_product_data() { var pdata = { }; $('.order-pane-table :input').each( function() { pdata[$(this).attr('name')] = $(this).val(); } ); $('.order-pane-table ~ :input').each( function() { pdata[$(this).attr('name')] = $(this).val(); } ); return pdata; } /** * Button to create a new row of empty data fields. */ function add_blank_line_button(order_id) { var post_vars = fetch_product_data(); post_vars['action'] = 'add_blank'; show_product_throbber(); $.post(Drupal.settings.ucURL.adminOrders + order_id + '/products', post_vars, function(contents) { if (contents != '') { $('#products-container').empty().append(contents); } hide_product_throbber(); } ); } /** * Button to remove product from the order. */ function remove_product_button(message, opid) { if (confirm(message)) { var post_vars = fetch_product_data(); post_vars['action'] = 'remove'; post_vars['opid'] = opid; show_product_throbber(); $.post(Drupal.settings.ucURL.adminOrders + $('#edit-order-id').val() + '/products', post_vars, function(contents) { if (contents != '') { $('#products-container').empty().append(contents); } hide_product_throbber(); } ); } } /** * Prevent mistakes by confirming deletion. */ function confirm_line_item_delete(message, img_id) { if (confirm(message)) { var li_id = img_id.substring(3); $('#edit-li-delete-id').val(li_id); $('#uc-order-edit-form #edit-submit-changes').get(0).click(); } } /** * Disable order submit button while parts of the page are still loading. */ function add_order_save_hold() { order_save_holds++; $('#uc-order-edit-form input.save-button').attr('disabled', 'disabled'); } /** * Remove a hold and enable the save buttons when all holds are gone! */ function remove_order_save_hold() { order_save_holds--; if (order_save_holds == 0) { release_held_buttons(); } } /** * Remove the disable attribute on any input item with the save-button class. */ function release_held_buttons() { $('#uc-order-edit-form input.save-button').removeAttr('disabled'); } /** * User feedback that something is happening. */ function show_product_throbber() { $('#product-div-throbber').attr('style', 'background-image: url(' + Drupal.settings.basePath + 'misc/throbber.gif); background-repeat: no-repeat; background-position: 100% -20px;').html('&nbsp;&nbsp;&nbsp;&nbsp;'); } /** * Done loading forms. */ function hide_product_throbber() { $('#product-div-throbber').removeAttr('style').empty(); }
nadavoid/ReadySiteBase
sites/all/modules/ubercart/uc_order/uc_order.js
JavaScript
gpl-2.0
12,940
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ gTestfile = '11.2.2-8-n.js'; /** File Name: 11.2.2-8-n.js ECMA Section: 11.2.2. The new operator Description: MemberExpression: PrimaryExpression MemberExpression[Expression] MemberExpression.Identifier new MemberExpression Arguments new NewExpression The production NewExpression : new NewExpression is evaluated as follows: 1. Evaluate NewExpression. 2. Call GetValue(Result(1)). 3. If Type(Result(2)) is not Object, generate a runtime error. 4. If Result(2) does not implement the internal [[Construct]] method, generate a runtime error. 5. Call the [[Construct]] method on Result(2), providing no arguments (that is, an empty list of arguments). 6. If Type(Result(5)) is not Object, generate a runtime error. 7. Return Result(5). The production MemberExpression : new MemberExpression Arguments is evaluated as follows: 1. Evaluate MemberExpression. 2. Call GetValue(Result(1)). 3. Evaluate Arguments, producing an internal list of argument values (section 0). 4. If Type(Result(2)) is not Object, generate a runtime error. 5. If Result(2) does not implement the internal [[Construct]] method, generate a runtime error. 6. Call the [[Construct]] method on Result(2), providing the list Result(3) as the argument values. 7. If Type(Result(6)) is not Object, generate a runtime error. 8 .Return Result(6). Author: [email protected] Date: 12 november 1997 */ var SECTION = "11.2.2-8-n.js"; var VERSION = "ECMA_1"; startTest(); var TITLE = "The new operator"; writeHeaderToLog( SECTION + " "+ TITLE); var NUMBER = new Number(1); DESCRIPTION = "var NUMBER = new Number(1); var n = new NUMBER()"; EXPECTED = "error"; new TestCase( SECTION, "var NUMBER = new Number(1); var n = new NUMBER()", "error", eval("n = new NUMBER()") ); test(); function TestFunction() { return arguments; }
ashwinrayaprolu1984/rhino
testsrc/tests/ecma/Expressions/11.2.2-8-n.js
JavaScript
mpl-2.0
2,282
define(function () { return {"zones":{"Indian/Mayotte":["z",{"wallclock":-1846281600000,"format":"EAT","abbrev":"EAT","offset":10800000,"posix":-1846292456000,"save":0},{"wallclock":-1.7976931348623157e+308,"format":"LMT","abbrev":"LMT","offset":10856000,"posix":-1.7976931348623157e+308,"save":0}]},"rules":{}} });
wye0220/shindig-canvas
public/javascripts/vendor/timezone/Indian/Mayotte.js
JavaScript
agpl-3.0
315
import { debounce } from 'lodash'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import StatusContainer from '../containers/status_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import LoadGap from './load_gap'; import ScrollableList from './scrollable_list'; import RegenerationIndicator from 'mastodon/components/regeneration_indicator'; export default class StatusList extends ImmutablePureComponent { static propTypes = { scrollKey: PropTypes.string.isRequired, statusIds: ImmutablePropTypes.list.isRequired, featuredStatusIds: ImmutablePropTypes.list, onLoadMore: PropTypes.func, onScrollToTop: PropTypes.func, onScroll: PropTypes.func, trackScroll: PropTypes.bool, shouldUpdateScroll: PropTypes.func, isLoading: PropTypes.bool, isPartial: PropTypes.bool, hasMore: PropTypes.bool, prepend: PropTypes.node, emptyMessage: PropTypes.node, alwaysPrepend: PropTypes.bool, timelineId: PropTypes.string, }; static defaultProps = { trackScroll: true, }; getFeaturedStatusCount = () => { return this.props.featuredStatusIds ? this.props.featuredStatusIds.size : 0; } getCurrentStatusIndex = (id, featured) => { if (featured) { return this.props.featuredStatusIds.indexOf(id); } else { return this.props.statusIds.indexOf(id) + this.getFeaturedStatusCount(); } } handleMoveUp = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) - 1; this._selectChild(elementIndex, true); } handleMoveDown = (id, featured) => { const elementIndex = this.getCurrentStatusIndex(id, featured) + 1; this._selectChild(elementIndex, false); } handleLoadOlder = debounce(() => { this.props.onLoadMore(this.props.statusIds.size > 0 ? this.props.statusIds.last() : undefined); }, 300, { leading: true }) _selectChild (index, align_top) { const container = this.node.node; const element = container.querySelector(`article:nth-of-type(${index + 1}) .focusable`); if (element) { if (align_top && container.scrollTop > element.offsetTop) { element.scrollIntoView(true); } else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) { element.scrollIntoView(false); } element.focus(); } } setRef = c => { this.node = c; } render () { const { statusIds, featuredStatusIds, shouldUpdateScroll, onLoadMore, timelineId, ...other } = this.props; const { isLoading, isPartial } = other; if (isPartial) { return <RegenerationIndicator />; } let scrollableContent = (isLoading || statusIds.size > 0) ? ( statusIds.map((statusId, index) => statusId === null ? ( <LoadGap key={'gap:' + statusIds.get(index + 1)} disabled={isLoading} maxId={index > 0 ? statusIds.get(index - 1) : null} onClick={onLoadMore} /> ) : ( <StatusContainer key={statusId} id={statusId} onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} scrollKey={this.props.scrollKey} showThread /> )) ) : null; if (scrollableContent && featuredStatusIds) { scrollableContent = featuredStatusIds.map(statusId => ( <StatusContainer key={`f-${statusId}`} id={statusId} featured onMoveUp={this.handleMoveUp} onMoveDown={this.handleMoveDown} contextType={timelineId} showThread /> )).concat(scrollableContent); } return ( <ScrollableList {...other} showLoading={isLoading && statusIds.size === 0} onLoadMore={onLoadMore && this.handleLoadOlder} shouldUpdateScroll={shouldUpdateScroll} ref={this.setRef}> {scrollableContent} </ScrollableList> ); } }
cobodo/mastodon
app/javascript/mastodon/components/status_list.js
JavaScript
agpl-3.0
4,044
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License for more * details. */ (function () { 'use strict'; angular .module('platformThumbModule') .directive('platformThumb', platformThumbDirective); platformThumbDirective.$inject = ['$window', '$log']; function platformThumbDirective($window, $log) { return { restrict: 'A', template: '<canvas/>', link: link }; function link(scope, element, attributes) { var helper = { support: !!($window.FileReader && $window.CanvasRenderingContext2D), isFile: function (item) { return angular.isObject(item) && item instanceof $window.File; }, isImage: function (file) { var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|'.indexOf(type) !== -1; } }; $log.debug('platformThumbDirective'); if (!helper.support) return; var params = scope.$eval(attributes.platformThumb); if (!helper.isFile(params.file)) return; if (!helper.isImage(params.file)) return; var canvas = element.find('canvas'); var reader = new FileReader(); reader.onload = onLoadFile; reader.readAsDataURL(params.file); function onLoadFile(event) { var img = new Image(); img.onload = onLoadImage; img.src = event.target.result; } function onLoadImage() { var width = params.width || this.width / this.height * params.height; var height = params.height || this.height / this.width * params.width; canvas.attr({width: width, height: height}); canvas[0].getContext('2d').drawImage(this, 0, 0, width, height); } } } })();
CypraxPuch/abixen-platform
abixen-platform-web-client/src/main/web/common/thumb/ng-thumb.directive.js
JavaScript
lgpl-2.1
2,532
/** * Copyright 2019 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 {shouldBlockOnConsentByMeta} from '../../src/consent'; describes.fakeWin('consent', {amp: true}, (env) => { describe('block by meta tags', () => { let doc; let head; let meta; beforeEach(() => { doc = env.win.document; head = doc.head; meta = doc.createElement('meta'); meta.setAttribute('name', 'amp-consent-blocking'); meta.setAttribute('content', 'AMP-TEST,amp-ad'); }); it('block by tagName', () => { doc.head.appendChild(meta); const element = doc.createElement('amp-test'); element.getAmpDoc = () => { return env.ampdoc; }; doc.body.appendChild(element); expect(shouldBlockOnConsentByMeta(element)).to.be.true; }); it('block by lowercase tagName', () => { head.appendChild(meta); const element = doc.createElement('amp-ad'); element.getAmpDoc = () => { return env.ampdoc; }; doc.body.appendChild(element); expect(shouldBlockOnConsentByMeta(element)).to.be.true; }); it('not block unspecified element', () => { head.appendChild(meta); const element = doc.createElement('amp-not-exist'); element.getAmpDoc = () => { return env.ampdoc; }; doc.body.appendChild(element); expect(shouldBlockOnConsentByMeta(element)).to.be.false; }); it('handles white space', () => { meta = doc.createElement('meta'); meta.setAttribute('name', 'amp-consent-blocking'); meta.setAttribute('content', ' amp-this, amp-that '); head.appendChild(meta); const element = doc.createElement('amp-that'); element.getAmpDoc = () => { return env.ampdoc; }; doc.body.appendChild(element); expect(shouldBlockOnConsentByMeta(element)).to.be.true; }); it('only work with tagName', () => { meta = doc.createElement('meta'); meta.setAttribute('name', 'amp-consent-blocking'); meta.setAttribute('content', 'amp-this:name,amp-this[name]'); head.appendChild(meta); const element = doc.createElement('amp-this'); element.getAmpDoc = () => { return env.ampdoc; }; doc.body.appendChild(element); expect(shouldBlockOnConsentByMeta(element)).to.be.false; }); }); });
prateekbh/amphtml
test/unit/test-consent.js
JavaScript
apache-2.0
2,920
module.exports={A:{A:{"1":"A","2":"J C G E B UB"},B:{"1":"D X g H L"},C:{"2":"0 1 2 4 5 SB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s QB PB"},D:{"2":"0 1 4 5 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s EB BB TB CB"},E:{"2":"9 F I J C G E B A DB FB GB HB IB JB KB"},F:{"2":"6 7 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB OB RB y"},G:{"2":"3 9 G A AB VB WB XB YB ZB aB bB cB"},H:{"2":"dB"},I:{"2":"2 3 F s eB fB gB hB iB jB"},J:{"2":"C B"},K:{"2":"6 7 B A D K y"},L:{"2":"8"},M:{"2":"t"},N:{"1":"A","2":"B"},O:{"2":"kB"},P:{"2":"F I"},Q:{"2":"lB"},R:{"2":"mB"}},B:7,C:"Resource Hints: Lazyload"};
redq81/redq81.github.io
test/node_modules/caniuse-lite/data/features/lazyload.js
JavaScript
mit
754
Meteor.startup(function() { RocketChat.TabBar.addButton({ groups: ['channel', 'group', 'direct'], id: 'starred-messages', i18nTitle: 'Starred_Messages', icon: 'star', template: 'starredMessages', order: 3 }); });
pitamar/Rocket.Chat
packages/rocketchat-message-star/client/tabBar.js
JavaScript
mit
227
consts: function() { __i18nMsg__('intro {$interpolation}', [['interpolation', String.raw`\uFFFD0\uFFFD`]], {meaning: 'm', desc: 'd'}) return [ [__AttributeMarker.I18n__, "title"], ["title", $i18n_0$] ]; }, template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵelementStart(0, "div", 0); $r3$.ɵɵpipe(1, "uppercase"); $r3$.ɵɵi18nAttributes(2, 1); $r3$.ɵɵelementEnd(); } if (rf & 2) { $r3$.ɵɵi18nExp($r3$.ɵɵpipeBind1(1, 1, ctx.valueA)); $r3$.ɵɵi18nApply(2); } }
ocombe/angular
packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_i18n/element_attributes/interpolation_custom_config.js
JavaScript
mit
536
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:anime/index', 'AnimeIndexController', { // Specify the other units that are required for this test. needs: [] }); // Replace this with your real tests. test('it exists', function() { var controller = this.subject(); ok(controller); });
vevix/hummingbird
frontend/tests/unit/controllers/anime/index-test.js
JavaScript
apache-2.0
319
// Copyright 2014 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. cr.define('cr.ui', function() { /** * A class to manage focus between given horizontally arranged elements. * For example, given the page: * * <input type="checkbox"> <label>Check me!</label> <button>X</button> * * One could create a FocusRow by doing: * * var focusRow = new cr.ui.FocusRow(rowBoundary, rowEl); * * focusRow.addFocusableElement(checkboxEl); * focusRow.addFocusableElement(labelEl); * focusRow.addFocusableElement(buttonEl); * * focusRow.setInitialFocusability(true); * * Pressing left cycles backward and pressing right cycles forward in item * order. Pressing Home goes to the beginning of the list and End goes to the * end of the list. * * If an item in this row is focused, it'll stay active (accessible via tab). * If no items in this row are focused, the row can stay active until focus * changes to a node inside |this.boundary_|. If |boundary| isn't specified, * any focus change deactivates the row. * * @constructor * @extends {HTMLDivElement} */ function FocusRow() {} /** @interface */ FocusRow.Delegate = function() {}; FocusRow.Delegate.prototype = { /** * Called when a key is pressed while an item in |this.focusableElements| is * focused. If |e|'s default is prevented, further processing is skipped. * @param {cr.ui.FocusRow} row The row that detected a keydown. * @param {Event} e * @return {boolean} Whether the event was handled. */ onKeydown: assertNotReached, /** * @param {cr.ui.FocusRow} row The row that detected the mouse going down. * @param {Event} e * @return {boolean} Whether the event was handled. */ onMousedown: assertNotReached, }; /** @const {string} */ FocusRow.ACTIVE_CLASS = 'focus-row-active'; FocusRow.prototype = { __proto__: HTMLDivElement.prototype, /** * Should be called in the constructor to decorate |this|. * @param {Node} boundary Focus events are ignored outside of this node. * @param {cr.ui.FocusRow.Delegate=} opt_delegate A delegate to handle key * events. */ decorate: function(boundary, opt_delegate) { /** @private {!Node} */ this.boundary_ = boundary || document; /** @type {cr.ui.FocusRow.Delegate|undefined} */ this.delegate = opt_delegate; /** @type {Array<Element>} */ this.focusableElements = []; /** @private {!EventTracker} */ this.eventTracker_ = new EventTracker; this.eventTracker_.add(cr.doc, 'focusin', this.onFocusin_.bind(this)); this.eventTracker_.add(cr.doc, 'keydown', this.onKeydown_.bind(this)); }, /** * Called when the row's active state changes and it is added/removed from * the focus order. * @param {boolean} state Whether the row has become active or inactive. */ onActiveStateChanged: function(state) {}, /** * Find the element that best matches |sampleElement|. * @param {Element} sampleElement An element from a row of the same type * which previously held focus. * @return {!Element} The element that best matches sampleElement. */ getEquivalentElement: function(sampleElement) { assertNotReached(); }, /** * Add an element to this FocusRow. No-op if |element| is not provided. * @param {Element} element The element that should be added. */ addFocusableElement: function(element) { if (!element) return; assert(this.focusableElements.indexOf(element) == -1); assert(this.contains(element)); element.tabIndex = this.isActive() ? 0 : -1; this.focusableElements.push(element); this.eventTracker_.add(element, 'mousedown', this.onMousedown_.bind(this)); }, /** * Called when focus changes to activate/deactivate the row. Focus is * removed from the row when |element| is not in the FocusRow. * @param {Element} element The element that has focus. null if focus should * be removed. * @private */ onFocusChange_: function(element) { this.makeActive(this.contains(element)); }, /** @return {boolean} Whether this row is currently active. */ isActive: function() { return this.classList.contains(FocusRow.ACTIVE_CLASS); }, /** * Enables/disables the tabIndex of the focusable elements in the FocusRow. * tabIndex can be set properly. * @param {boolean} active True if tab is allowed for this row. */ makeActive: function(active) { if (active == this.isActive()) return; this.focusableElements.forEach(function(element) { element.tabIndex = active ? 0 : -1; }); this.classList.toggle(FocusRow.ACTIVE_CLASS, active); this.onActiveStateChanged(active); }, /** Dereferences nodes and removes event handlers. */ destroy: function() { this.focusableElements.length = 0; this.eventTracker_.removeAll(); }, /** * @param {Event} e The focusin event. * @private */ onFocusin_: function(e) { var target = assertInstanceof(e.target, Element); if (this.boundary_.contains(target)) this.onFocusChange_(target); }, /** * Handles a keypress for an element in this FocusRow. * @param {Event} e The keydown event. * @private */ onKeydown_: function(e) { var element = assertInstanceof(e.target, Element); var elementIndex = this.focusableElements.indexOf(element); if (elementIndex < 0) return; if (this.delegate && this.delegate.onKeydown(this, e)) return; if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return; var index = -1; if (e.keyIdentifier == 'Left') index = elementIndex + (isRTL() ? 1 : -1); else if (e.keyIdentifier == 'Right') index = elementIndex + (isRTL() ? -1 : 1); else if (e.keyIdentifier == 'Home') index = 0; else if (e.keyIdentifier == 'End') index = this.focusableElements.length - 1; var elementToFocus = this.focusableElements[index]; if (elementToFocus) { this.getEquivalentElement(elementToFocus).focus(); e.preventDefault(); } }, /** * @param {Event} e A click event. * @private */ onMousedown_: function(e) { if (this.delegate && this.delegate.onMousedown(this, e)) return; // Only accept the left mouse click. if (!e.button) { // Focus this row if the target is one of the elements in this row. this.onFocusChange_(assertInstanceof(e.target, Element)); } }, }; return { FocusRow: FocusRow, }; });
guorendong/iridium-browser-ubuntu
ui/webui/resources/js/cr/ui/focus_row.js
JavaScript
bsd-3-clause
6,946
// Copyright (c) 2012 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. /** @typedef {{active: boolean, * command_name: string, * description: string, * extension_action: boolean, * extension_id: string, * global: boolean, * keybinding: string}} */ var ExtensionCommand; cr.define('options', function() { 'use strict'; /** @const */ var keyComma = 188; /** @const */ var keyDel = 46; /** @const */ var keyDown = 40; /** @const */ var keyEnd = 35; /** @const */ var keyEscape = 27; /** @const */ var keyHome = 36; /** @const */ var keyIns = 45; /** @const */ var keyLeft = 37; /** @const */ var keyMediaNextTrack = 176; /** @const */ var keyMediaPlayPause = 179; /** @const */ var keyMediaPrevTrack = 177; /** @const */ var keyMediaStop = 178; /** @const */ var keyPageDown = 34; /** @const */ var keyPageUp = 33; /** @const */ var keyPeriod = 190; /** @const */ var keyRight = 39; /** @const */ var keySpace = 32; /** @const */ var keyTab = 9; /** @const */ var keyUp = 38; /** * Enum for whether we require modifiers of a keycode. * @enum {number} */ var Modifiers = { ARE_NOT_ALLOWED: 0, ARE_REQUIRED: 1 }; /** * Returns whether the passed in |keyCode| is a valid extension command * char or not. This is restricted to A-Z and 0-9 (ignoring modifiers) at * the moment. * @param {number} keyCode The keycode to consider. * @return {boolean} Returns whether the char is valid. */ function validChar(keyCode) { return keyCode == keyComma || keyCode == keyDel || keyCode == keyDown || keyCode == keyEnd || keyCode == keyHome || keyCode == keyIns || keyCode == keyLeft || keyCode == keyMediaNextTrack || keyCode == keyMediaPlayPause || keyCode == keyMediaPrevTrack || keyCode == keyMediaStop || keyCode == keyPageDown || keyCode == keyPageUp || keyCode == keyPeriod || keyCode == keyRight || keyCode == keySpace || keyCode == keyTab || keyCode == keyUp || (keyCode >= 'A'.charCodeAt(0) && keyCode <= 'Z'.charCodeAt(0)) || (keyCode >= '0'.charCodeAt(0) && keyCode <= '9'.charCodeAt(0)); } /** * Convert a keystroke event to string form, while taking into account * (ignoring) invalid extension commands. * @param {Event} event The keyboard event to convert. * @return {string} The keystroke as a string. */ function keystrokeToString(event) { var output = []; if (cr.isMac && event.metaKey) output.push('Command'); if (cr.isChromeOS && event.metaKey) output.push('Search'); if (event.ctrlKey) output.push('Ctrl'); if (!event.ctrlKey && event.altKey) output.push('Alt'); if (event.shiftKey) output.push('Shift'); var keyCode = event.keyCode; if (validChar(keyCode)) { if ((keyCode >= 'A'.charCodeAt(0) && keyCode <= 'Z'.charCodeAt(0)) || (keyCode >= '0'.charCodeAt(0) && keyCode <= '9'.charCodeAt(0))) { output.push(String.fromCharCode('A'.charCodeAt(0) + keyCode - 65)); } else { switch (keyCode) { case keyComma: output.push('Comma'); break; case keyDel: output.push('Delete'); break; case keyDown: output.push('Down'); break; case keyEnd: output.push('End'); break; case keyHome: output.push('Home'); break; case keyIns: output.push('Insert'); break; case keyLeft: output.push('Left'); break; case keyMediaNextTrack: output.push('MediaNextTrack'); break; case keyMediaPlayPause: output.push('MediaPlayPause'); break; case keyMediaPrevTrack: output.push('MediaPrevTrack'); break; case keyMediaStop: output.push('MediaStop'); break; case keyPageDown: output.push('PageDown'); break; case keyPageUp: output.push('PageUp'); break; case keyPeriod: output.push('Period'); break; case keyRight: output.push('Right'); break; case keySpace: output.push('Space'); break; case keyTab: output.push('Tab'); break; case keyUp: output.push('Up'); break; } } } return output.join('+'); } /** * Returns whether the passed in |keyCode| require modifiers. Currently only * "MediaNextTrack", "MediaPrevTrack", "MediaStop", "MediaPlayPause" are * required to be used without any modifier. * @param {number} keyCode The keycode to consider. * @return {Modifiers} Returns whether the keycode require modifiers. */ function modifiers(keyCode) { switch (keyCode) { case keyMediaNextTrack: case keyMediaPlayPause: case keyMediaPrevTrack: case keyMediaStop: return Modifiers.ARE_NOT_ALLOWED; default: return Modifiers.ARE_REQUIRED; } } /** * Return true if the specified keyboard event has any one of following * modifiers: "Ctrl", "Alt", "Cmd" on Mac, and "Shift" when the * countShiftAsModifier is true. * @param {Event} event The keyboard event to consider. * @param {boolean} countShiftAsModifier Whether the 'ShiftKey' should be * counted as modifier. */ function hasModifier(event, countShiftAsModifier) { return event.ctrlKey || event.altKey || (cr.isMac && event.metaKey) || (cr.isChromeOS && event.metaKey) || (countShiftAsModifier && event.shiftKey); } /** * Creates a new list of extension commands. * @param {HTMLDivElement} div * @constructor * @extends {HTMLDivElement} */ function ExtensionCommandList(div) { div.__proto__ = ExtensionCommandList.prototype; return div; } ExtensionCommandList.prototype = { __proto__: HTMLDivElement.prototype, /** * While capturing, this records the current (last) keyboard event generated * by the user. Will be |null| after capture and during capture when no * keyboard event has been generated. * @type {KeyboardEvent}. * @private */ currentKeyEvent_: null, /** * While capturing, this keeps track of the previous selection so we can * revert back to if no valid assignment is made during capture. * @type {string}. * @private */ oldValue_: '', /** * While capturing, this keeps track of which element the user asked to * change. * @type {HTMLElement}. * @private */ capturingElement_: null, /** * Updates the extensions data for the overlay. * @param {!Array<ExtensionInfo>} data The extension data. */ setData: function(data) { /** @private {!Array<ExtensionInfo>} */ this.data_ = data; this.textContent = ''; // Iterate over the extension data and add each item to the list. this.data_.forEach(this.createNodeForExtension_.bind(this)); }, /** * Synthesizes and initializes an HTML element for the extension command * metadata given in |extension|. * @param {ExtensionInfo} extension A dictionary of extension metadata. * @private */ createNodeForExtension_: function(extension) { if (extension.commands.length == 0 || extension.state == chrome.developerPrivate.ExtensionState.DISABLED) return; var template = $('template-collection-extension-commands').querySelector( '.extension-command-list-extension-item-wrapper'); var node = template.cloneNode(true); var title = node.querySelector('.extension-title'); title.textContent = extension.name; this.appendChild(node); // Iterate over the commands data within the extension and add each item // to the list. extension.commands.forEach( this.createNodeForCommand_.bind(this, extension.id)); }, /** * Synthesizes and initializes an HTML element for the extension command * metadata given in |command|. * @param {string} extensionId The associated extension's id. * @param {Command} command A dictionary of extension command metadata. * @private */ createNodeForCommand_: function(extensionId, command) { var template = $('template-collection-extension-commands').querySelector( '.extension-command-list-command-item-wrapper'); var node = template.cloneNode(true); node.id = this.createElementId_('command', extensionId, command.name); var description = node.querySelector('.command-description'); description.textContent = command.description; var shortcutNode = node.querySelector('.command-shortcut-text'); shortcutNode.addEventListener('mouseup', this.startCapture_.bind(this)); shortcutNode.addEventListener('focus', this.handleFocus_.bind(this)); shortcutNode.addEventListener('blur', this.handleBlur_.bind(this)); shortcutNode.addEventListener('keydown', this.handleKeyDown_.bind(this)); shortcutNode.addEventListener('keyup', this.handleKeyUp_.bind(this)); if (!command.isActive) { shortcutNode.textContent = loadTimeData.getString('extensionCommandsInactive'); var commandShortcut = node.querySelector('.command-shortcut'); commandShortcut.classList.add('inactive-keybinding'); } else { shortcutNode.textContent = command.keybinding; } var commandClear = node.querySelector('.command-clear'); commandClear.id = this.createElementId_( 'clear', extensionId, command.name); commandClear.title = loadTimeData.getString('extensionCommandsDelete'); commandClear.addEventListener('click', this.handleClear_.bind(this)); var select = node.querySelector('.command-scope'); select.id = this.createElementId_( 'setCommandScope', extensionId, command.name); select.hidden = false; // Add the 'In Chrome' option. var option = document.createElement('option'); option.textContent = loadTimeData.getString('extensionCommandsRegular'); select.appendChild(option); if (command.isExtensionAction || !command.isActive) { // Extension actions cannot be global, so we might as well disable the // combo box, to signify that, and if the command is inactive, it // doesn't make sense to allow the user to adjust the scope. select.disabled = true; } else { // Add the 'Global' option. option = document.createElement('option'); option.textContent = loadTimeData.getString('extensionCommandsGlobal'); select.appendChild(option); select.selectedIndex = command.scope == chrome.developerPrivate.CommandScope.GLOBAL ? 1 : 0; select.addEventListener( 'change', this.handleSetCommandScope_.bind(this)); } this.appendChild(node); }, /** * Starts keystroke capture to determine which key to use for a particular * extension command. * @param {Event} event The keyboard event to consider. * @private */ startCapture_: function(event) { if (this.capturingElement_) return; // Already capturing. chrome.developerPrivate.setShortcutHandlingSuspended(true); var shortcutNode = event.target; this.oldValue_ = shortcutNode.textContent; shortcutNode.textContent = loadTimeData.getString('extensionCommandsStartTyping'); shortcutNode.parentElement.classList.add('capturing'); var commandClear = shortcutNode.parentElement.querySelector('.command-clear'); commandClear.hidden = true; this.capturingElement_ = /** @type {HTMLElement} */(event.target); }, /** * Ends keystroke capture and either restores the old value or (if valid * value) sets the new value as active.. * @param {Event} event The keyboard event to consider. * @private */ endCapture_: function(event) { if (!this.capturingElement_) return; // Not capturing. chrome.developerPrivate.setShortcutHandlingSuspended(false); var shortcutNode = this.capturingElement_; var commandShortcut = shortcutNode.parentElement; commandShortcut.classList.remove('capturing'); commandShortcut.classList.remove('contains-chars'); // When the capture ends, the user may have not given a complete and valid // input (or even no input at all). Only a valid key event followed by a // valid key combination will cause a shortcut selection to be activated. // If no valid selection was made, however, revert back to what the // textbox had before to indicate that the shortcut registration was // canceled. if (!this.currentKeyEvent_ || !validChar(this.currentKeyEvent_.keyCode)) shortcutNode.textContent = this.oldValue_; var commandClear = commandShortcut.querySelector('.command-clear'); if (this.oldValue_ == '') { commandShortcut.classList.remove('clearable'); commandClear.hidden = true; } else { commandShortcut.classList.add('clearable'); commandClear.hidden = false; } this.oldValue_ = ''; this.capturingElement_ = null; this.currentKeyEvent_ = null; }, /** * Handles focus event and adds visual indication for active shortcut. * @param {Event} event to consider. * @private */ handleFocus_: function(event) { var commandShortcut = event.target.parentElement; commandShortcut.classList.add('focused'); }, /** * Handles lost focus event and removes visual indication of active shortcut * also stops capturing on focus lost. * @param {Event} event to consider. * @private */ handleBlur_: function(event) { this.endCapture_(event); var commandShortcut = event.target.parentElement; commandShortcut.classList.remove('focused'); }, /** * The KeyDown handler. * @param {Event} event The keyboard event to consider. * @private */ handleKeyDown_: function(event) { event = /** @type {KeyboardEvent} */(event); if (event.keyCode == keyEscape) { if (!this.capturingElement_) { // If we're not currently capturing, allow escape to propagate (so it // can close the overflow). return; } // Otherwise, escape cancels capturing. this.endCapture_(event); var parsed = this.parseElementId_('clear', event.target.parentElement.querySelector('.command-clear').id); chrome.developerPrivate.updateExtensionCommand({ extensionId: parsed.extensionId, commandName: parsed.commandName, keybinding: '' }); event.preventDefault(); event.stopPropagation(); return; } if (event.keyCode == keyTab) { // Allow tab propagation for keyboard navigation. return; } if (!this.capturingElement_) this.startCapture_(event); this.handleKey_(event); }, /** * The KeyUp handler. * @param {Event} event The keyboard event to consider. * @private */ handleKeyUp_: function(event) { event = /** @type {KeyboardEvent} */(event); if (event.keyCode == keyTab || event.keyCode == keyEscape) { // We need to allow tab propagation for keyboard navigation, and escapes // are fully handled in handleKeyDown. return; } // We want to make it easy to change from Ctrl+Shift+ to just Ctrl+ by // releasing Shift, but we also don't want it to be easy to lose for // example Ctrl+Shift+F to Ctrl+ just because you didn't release Ctrl // as fast as the other two keys. Therefore, we process KeyUp until you // have a valid combination and then stop processing it (meaning that once // you have a valid combination, we won't change it until the next // KeyDown message arrives). if (!this.currentKeyEvent_ || !validChar(this.currentKeyEvent_.keyCode)) { if (!event.ctrlKey && !event.altKey || ((cr.isMac || cr.isChromeOS) && !event.metaKey)) { // If neither Ctrl nor Alt is pressed then it is not a valid shortcut. // That means we're back at the starting point so we should restart // capture. this.endCapture_(event); this.startCapture_(event); } else { this.handleKey_(event); } } }, /** * A general key handler (used for both KeyDown and KeyUp). * @param {KeyboardEvent} event The keyboard event to consider. * @private */ handleKey_: function(event) { // While capturing, we prevent all events from bubbling, to prevent // shortcuts lacking the right modifier (F3 for example) from activating // and ending capture prematurely. event.preventDefault(); event.stopPropagation(); if (modifiers(event.keyCode) == Modifiers.ARE_REQUIRED && !hasModifier(event, false)) { // Ctrl or Alt (or Cmd on Mac) is a must for most shortcuts. return; } if (modifiers(event.keyCode) == Modifiers.ARE_NOT_ALLOWED && hasModifier(event, true)) { return; } var shortcutNode = this.capturingElement_; var keystroke = keystrokeToString(event); shortcutNode.textContent = keystroke; event.target.classList.add('contains-chars'); this.currentKeyEvent_ = event; if (validChar(event.keyCode)) { var node = event.target; while (node && !node.id) node = node.parentElement; this.oldValue_ = keystroke; // Forget what the old value was. var parsed = this.parseElementId_('command', node.id); // Ending the capture must occur before calling // setExtensionCommandShortcut to ensure the shortcut is set. this.endCapture_(event); chrome.developerPrivate.updateExtensionCommand( {extensionId: parsed.extensionId, commandName: parsed.commandName, keybinding: keystroke}); } }, /** * A handler for the delete command button. * @param {Event} event The mouse event to consider. * @private */ handleClear_: function(event) { var parsed = this.parseElementId_('clear', event.target.id); chrome.developerPrivate.updateExtensionCommand( {extensionId: parsed.extensionId, commandName: parsed.commandName, keybinding: ''}); }, /** * A handler for the setting the scope of the command. * @param {Event} event The mouse event to consider. * @private */ handleSetCommandScope_: function(event) { var parsed = this.parseElementId_('setCommandScope', event.target.id); var element = document.getElementById( 'setCommandScope-' + parsed.extensionId + '-' + parsed.commandName); var scope = element.selectedIndex == 1 ? chrome.developerPrivate.CommandScope.GLOBAL : chrome.developerPrivate.CommandScope.CHROME; chrome.developerPrivate.updateExtensionCommand( {extensionId: parsed.extensionId, commandName: parsed.commandName, scope: scope}); }, /** * A utility function to create a unique element id based on a namespace, * extension id and a command name. * @param {string} namespace The namespace to prepend the id with. * @param {string} extensionId The extension ID to use in the id. * @param {string} commandName The command name to append the id with. * @private */ createElementId_: function(namespace, extensionId, commandName) { return namespace + '-' + extensionId + '-' + commandName; }, /** * A utility function to parse a unique element id based on a namespace, * extension id and a command name. * @param {string} namespace The namespace to prepend the id with. * @param {string} id The id to parse. * @return {{extensionId: string, commandName: string}} The parsed id. * @private */ parseElementId_: function(namespace, id) { var kExtensionIdLength = 32; return { extensionId: id.substring(namespace.length + 1, namespace.length + 1 + kExtensionIdLength), commandName: id.substring(namespace.length + 1 + kExtensionIdLength + 1) }; }, }; return { ExtensionCommandList: ExtensionCommandList }; });
Chilledheart/chromium
chrome/browser/resources/extensions/extension_command_list.js
JavaScript
bsd-3-clause
21,050
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v14.1.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../context/context"); var logger_1 = require("../logger"); var columnController_1 = require("../columnController/columnController"); var column_1 = require("../entities/column"); var utils_1 = require("../utils"); var dragAndDropService_1 = require("../dragAndDrop/dragAndDropService"); var gridPanel_1 = require("../gridPanel/gridPanel"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var MoveColumnController = (function () { function MoveColumnController(pinned, eContainer) { this.needToMoveLeft = false; this.needToMoveRight = false; this.pinned = pinned; this.eContainer = eContainer; this.centerContainer = !utils_1.Utils.exists(pinned); } MoveColumnController.prototype.init = function () { this.logger = this.loggerFactory.create('MoveColumnController'); }; MoveColumnController.prototype.getIconName = function () { return this.pinned ? dragAndDropService_1.DragAndDropService.ICON_PINNED : dragAndDropService_1.DragAndDropService.ICON_MOVE; }; MoveColumnController.prototype.onDragEnter = function (draggingEvent) { // we do dummy drag, so make sure column appears in the right location when first placed var columns = draggingEvent.dragItem.columns; var dragCameFromToolPanel = draggingEvent.dragSource.type === dragAndDropService_1.DragSourceType.ToolPanel; if (dragCameFromToolPanel) { // the if statement doesn't work if drag leaves grid, then enters again this.columnController.setColumnsVisible(columns, true); } else { // restore previous state of visible columns upon re-entering var visibleState_1 = draggingEvent.dragItem.visibleState; var visibleColumns = columns.filter(function (column) { return visibleState_1[column.getId()]; }); this.columnController.setColumnsVisible(visibleColumns, true); } this.columnController.setColumnsPinned(columns, this.pinned); this.onDragging(draggingEvent, true); }; MoveColumnController.prototype.onDragLeave = function (draggingEvent) { var hideColumnOnExit = !this.gridOptionsWrapper.isSuppressDragLeaveHidesColumns() && !draggingEvent.fromNudge; if (hideColumnOnExit) { var dragItem = draggingEvent.dragSource.dragItemCallback(); var columns = dragItem.columns; this.columnController.setColumnsVisible(columns, false); } this.ensureIntervalCleared(); }; MoveColumnController.prototype.onDragStop = function () { this.ensureIntervalCleared(); }; MoveColumnController.prototype.normaliseX = function (x) { // flip the coordinate if doing RTL var flipHorizontallyForRtl = this.gridOptionsWrapper.isEnableRtl(); if (flipHorizontallyForRtl) { var clientWidth = this.eContainer.clientWidth; x = clientWidth - x; } // adjust for scroll only if centre container (the pinned containers dont scroll) var adjustForScroll = this.centerContainer; if (adjustForScroll) { x += this.gridPanel.getBodyViewportScrollLeft(); } return x; }; MoveColumnController.prototype.checkCenterForScrolling = function (xAdjustedForScroll) { if (this.centerContainer) { // scroll if the mouse has gone outside the grid (or just outside the scrollable part if pinning) // putting in 50 buffer, so even if user gets to edge of grid, a scroll will happen var firstVisiblePixel = this.gridPanel.getBodyViewportScrollLeft(); var lastVisiblePixel = firstVisiblePixel + this.gridPanel.getCenterWidth(); if (this.gridOptionsWrapper.isEnableRtl()) { this.needToMoveRight = xAdjustedForScroll < (firstVisiblePixel + 50); this.needToMoveLeft = xAdjustedForScroll > (lastVisiblePixel - 50); } else { this.needToMoveLeft = xAdjustedForScroll < (firstVisiblePixel + 50); this.needToMoveRight = xAdjustedForScroll > (lastVisiblePixel - 50); } if (this.needToMoveLeft || this.needToMoveRight) { this.ensureIntervalStarted(); } else { this.ensureIntervalCleared(); } } }; MoveColumnController.prototype.onDragging = function (draggingEvent, fromEnter) { if (fromEnter === void 0) { fromEnter = false; } this.lastDraggingEvent = draggingEvent; // if moving up or down (ie not left or right) then do nothing if (utils_1.Utils.missing(draggingEvent.hDirection)) { return; } var xNormalised = this.normaliseX(draggingEvent.x); // if the user is dragging into the panel, ie coming from the side panel into the main grid, // we don't want to scroll the grid this time, it would appear like the table is jumping // each time a column is dragged in. if (!fromEnter) { this.checkCenterForScrolling(xNormalised); } var hDirectionNormalised = this.normaliseDirection(draggingEvent.hDirection); var dragSourceType = draggingEvent.dragSource.type; var columnsToMove = draggingEvent.dragSource.dragItemCallback().columns; this.attemptMoveColumns(dragSourceType, columnsToMove, hDirectionNormalised, xNormalised, fromEnter); }; MoveColumnController.prototype.normaliseDirection = function (hDirection) { if (this.gridOptionsWrapper.isEnableRtl()) { switch (hDirection) { case dragAndDropService_1.HDirection.Left: return dragAndDropService_1.HDirection.Right; case dragAndDropService_1.HDirection.Right: return dragAndDropService_1.HDirection.Left; default: console.error("ag-Grid: Unknown direction " + hDirection); } } else { return hDirection; } }; // returns the index of the first column in the list ONLY if the cols are all beside // each other. if the cols are not beside each other, then returns null MoveColumnController.prototype.calculateOldIndex = function (movingCols) { var gridCols = this.columnController.getAllGridColumns(); var indexes = []; movingCols.forEach(function (col) { return indexes.push(gridCols.indexOf(col)); }); utils_1.Utils.sortNumberArray(indexes); var firstIndex = indexes[0]; var lastIndex = indexes[indexes.length - 1]; var spread = lastIndex - firstIndex; var gapsExist = spread !== indexes.length - 1; return gapsExist ? null : firstIndex; }; MoveColumnController.prototype.attemptMoveColumns = function (dragSourceType, allMovingColumns, hDirection, xAdjusted, fromEnter) { var draggingLeft = hDirection === dragAndDropService_1.HDirection.Left; var draggingRight = hDirection === dragAndDropService_1.HDirection.Right; var validMoves = this.calculateValidMoves(allMovingColumns, draggingRight, xAdjusted); // if cols are not adjacent, then this returns null. when moving, we constrain the direction of the move // (ie left or right) to the mouse direction. however var oldIndex = this.calculateOldIndex(allMovingColumns); // fromEnter = false; for (var i = 0; i < validMoves.length; i++) { var newIndex = validMoves[i]; // the two check below stop an error when the user grabs a group my a middle column, then // it is possible the mouse pointer is to the right of a column while been dragged left. // so we need to make sure that the mouse pointer is actually left of the left most column // if moving left, and right of the right most column if moving right // we check 'fromEnter' below so we move the column to the new spot if the mouse is coming from // outside the grid, eg if the column is moving from side panel, mouse is moving left, then we should // place the column to the RHS even if the mouse is moving left and the column is already on // the LHS. otherwise we stick to the rule described above. var constrainDirection = oldIndex !== null && !fromEnter; // don't consider 'fromEnter' when dragging header cells, otherwise group can jump to opposite direction of drag if (dragSourceType == dragAndDropService_1.DragSourceType.HeaderCell) { constrainDirection = oldIndex !== null; } if (constrainDirection) { // only allow left drag if this column is moving left if (draggingLeft && newIndex >= oldIndex) { continue; } // only allow right drag if this column is moving right if (draggingRight && newIndex <= oldIndex) { continue; } } if (!this.columnController.doesMovePassRules(allMovingColumns, newIndex)) { continue; } this.columnController.moveColumns(allMovingColumns, newIndex); // important to return here, so once we do the first valid move, we don't try do any more return; } }; MoveColumnController.prototype.calculateValidMoves = function (movingCols, draggingRight, x) { // this is the list of cols on the screen, so it's these we use when comparing the x mouse position var allDisplayedCols = this.columnController.getDisplayedColumns(this.pinned); // but this list is the list of all cols, when we move a col it's the index within this list that gets used, // so the result we return has to be and index location for this list var allGridCols = this.columnController.getAllGridColumns(); var colIsMovingFunc = function (col) { return movingCols.indexOf(col) >= 0; }; var colIsNotMovingFunc = function (col) { return movingCols.indexOf(col) < 0; }; var movingDisplayedCols = allDisplayedCols.filter(colIsMovingFunc); var otherDisplayedCols = allDisplayedCols.filter(colIsNotMovingFunc); var otherGridCols = allGridCols.filter(colIsNotMovingFunc); // work out how many DISPLAYED columns fit before the 'x' position. this gives us the displayIndex. // for example, if cols are a,b,c,d and we find a,b fit before 'x', then we want to place the moving // col between b and c (so that it is under the mouse position). var displayIndex = 0; var availableWidth = x; // if we are dragging right, then the columns will be to the left of the mouse, so we also want to // include the width of the moving columns if (draggingRight) { var widthOfMovingDisplayedCols_1 = 0; movingDisplayedCols.forEach(function (col) { return widthOfMovingDisplayedCols_1 += col.getActualWidth(); }); availableWidth -= widthOfMovingDisplayedCols_1; } // now count how many of the displayed columns will fit to the left for (var i = 0; i < otherDisplayedCols.length; i++) { var col = otherDisplayedCols[i]; availableWidth -= col.getActualWidth(); if (availableWidth < 0) { break; } displayIndex++; } // trial and error, if going right, we adjust by one, i didn't manage to quantify why, but it works if (draggingRight) { displayIndex++; } // the display index is with respect to all the showing columns, however when we move, it's with // respect to all grid columns, so we need to translate from display index to grid index var gridColIndex; if (displayIndex > 0) { var leftColumn = otherDisplayedCols[displayIndex - 1]; gridColIndex = otherGridCols.indexOf(leftColumn) + 1; } else { gridColIndex = 0; } var validMoves = [gridColIndex]; // add in all adjacent empty columns as other valid moves. this allows us to try putting the new // column in any place of a hidden column, to try different combinations so that we don't break // married children. in other words, maybe the new index breaks a group, but only because some // columns are hidden, maybe we can reshuffle the hidden columns to find a place that works. var nextCol = allGridCols[gridColIndex]; while (utils_1.Utils.exists(nextCol) && this.isColumnHidden(allDisplayedCols, nextCol)) { gridColIndex++; validMoves.push(gridColIndex); nextCol = allGridCols[gridColIndex]; } return validMoves; }; // isHidden takes into account visible=false and group=closed, ie it is not displayed MoveColumnController.prototype.isColumnHidden = function (displayedColumns, col) { return displayedColumns.indexOf(col) < 0; }; MoveColumnController.prototype.ensureIntervalStarted = function () { if (!this.movingIntervalId) { this.intervalCount = 0; this.failedMoveAttempts = 0; this.movingIntervalId = setInterval(this.moveInterval.bind(this), 100); if (this.needToMoveLeft) { this.dragAndDropService.setGhostIcon(dragAndDropService_1.DragAndDropService.ICON_LEFT, true); } else { this.dragAndDropService.setGhostIcon(dragAndDropService_1.DragAndDropService.ICON_RIGHT, true); } } }; MoveColumnController.prototype.ensureIntervalCleared = function () { if (this.moveInterval) { clearInterval(this.movingIntervalId); this.movingIntervalId = null; this.dragAndDropService.setGhostIcon(dragAndDropService_1.DragAndDropService.ICON_MOVE); } }; MoveColumnController.prototype.moveInterval = function () { var pixelsToMove; this.intervalCount++; pixelsToMove = 10 + (this.intervalCount * 5); if (pixelsToMove > 100) { pixelsToMove = 100; } var pixelsMoved; if (this.needToMoveLeft) { pixelsMoved = this.gridPanel.scrollHorizontally(-pixelsToMove); } else if (this.needToMoveRight) { pixelsMoved = this.gridPanel.scrollHorizontally(pixelsToMove); } if (pixelsMoved !== 0) { this.onDragging(this.lastDraggingEvent); this.failedMoveAttempts = 0; } else { this.failedMoveAttempts++; this.dragAndDropService.setGhostIcon(dragAndDropService_1.DragAndDropService.ICON_PINNED); if (this.failedMoveAttempts > 7) { var columns = this.lastDraggingEvent.dragItem.columns; var pinType = this.needToMoveLeft ? column_1.Column.PINNED_LEFT : column_1.Column.PINNED_RIGHT; this.columnController.setColumnsPinned(columns, pinType); this.dragAndDropService.nudge(); } } }; __decorate([ context_1.Autowired('loggerFactory'), __metadata("design:type", logger_1.LoggerFactory) ], MoveColumnController.prototype, "loggerFactory", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], MoveColumnController.prototype, "columnController", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata("design:type", gridPanel_1.GridPanel) ], MoveColumnController.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('dragAndDropService'), __metadata("design:type", dragAndDropService_1.DragAndDropService) ], MoveColumnController.prototype, "dragAndDropService", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], MoveColumnController.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], MoveColumnController.prototype, "init", null); return MoveColumnController; }()); exports.MoveColumnController = MoveColumnController;
seogi1004/cdnjs
ajax/libs/ag-grid/14.1.1/lib/headerRendering/moveColumnController.js
JavaScript
mit
17,602
define([ 'summernote/core/agent', 'summernote/core/dom' ], function (agent, dom) { /** * Style * @class */ var Style = function () { /** * passing an array of style properties to .css() * will result in an object of property-value pairs. * (compability with version < 1.9) * * @param {jQuery} $obj * @param {Array} propertyNames - An array of one or more CSS properties. * @returns {Object} */ var jQueryCSS = function ($obj, propertyNames) { if (agent.jqueryVersion < 1.9) { var result = {}; $.each(propertyNames, function (idx, propertyName) { result[propertyName] = $obj.css(propertyName); }); return result; } return $obj.css.call($obj, propertyNames); }; /** * paragraph level style * * @param {WrappedRange} rng * @param {Object} styleInfo */ this.stylePara = function (rng, styleInfo) { $.each(rng.nodes(dom.isPara, { includeAncestor: true }), function (idx, para) { $(para).css(styleInfo); }); }; /** * get current style on cursor * * @param {WrappedRange} rng * @return {Object} - object contains style properties. */ this.current = function (rng) { var $cont = $(dom.isText(rng.sc) ? rng.sc.parentNode : rng.sc); var properties = ['font-family', 'font-size', 'text-align', 'list-style-type', 'line-height']; var styleInfo = jQueryCSS($cont, properties) || {}; styleInfo['font-size'] = parseInt(styleInfo['font-size'], 10); // document.queryCommandState for toggle state styleInfo['font-bold'] = document.queryCommandState('bold') ? 'bold' : 'normal'; styleInfo['font-italic'] = document.queryCommandState('italic') ? 'italic' : 'normal'; styleInfo['font-underline'] = document.queryCommandState('underline') ? 'underline' : 'normal'; styleInfo['font-strikethrough'] = document.queryCommandState('strikeThrough') ? 'strikethrough' : 'normal'; styleInfo['font-superscript'] = document.queryCommandState('superscript') ? 'superscript' : 'normal'; styleInfo['font-subscript'] = document.queryCommandState('subscript') ? 'subscript' : 'normal'; // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { styleInfo['list-style'] = 'none'; } else { var aOrderedType = ['circle', 'disc', 'disc-leading-zero', 'square']; var isUnordered = $.inArray(styleInfo['list-style-type'], aOrderedType) > -1; styleInfo['list-style'] = isUnordered ? 'unordered' : 'ordered'; } var para = dom.ancestor(rng.sc, dom.isPara); if (para && para.style['line-height']) { styleInfo['line-height'] = para.style.lineHeight; } else { var lineHeight = parseInt(styleInfo['line-height'], 10) / parseInt(styleInfo['font-size'], 10); styleInfo['line-height'] = lineHeight.toFixed(1); } styleInfo.image = rng.isOnImg(); styleInfo.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); styleInfo.ancestors = dom.listAncestor(rng.sc, dom.isEditable); styleInfo.range = rng; return styleInfo; }; }; return Style; });
zbqf109/goodo
openerp/addons/web_editor/static/lib/summernote/src/js/editing/Style.js
JavaScript
gpl-3.0
3,266
function setValFromSelectPage(org_id, bom_resource_id, bom_resource, combination) { this.org_id = org_id; this.bom_resource_id = bom_resource_id; this.combination = combination; this.bom_resource = bom_resource; } setValFromSelectPage.prototype.setVal = function() { if (this.org_id) { $("#org_id").val(this.org_id); } if (this.bom_resource_id) { $("#bom_resource_id").val(this.bom_resource_id); } if (this.bom_resource) { $("#bom_resource").val(this.bom_resource); } if (this.combination) { var fieldClass = '.' + localStorage.getItem("field_class").replace(/\s+/g, '.') $('#content').find(fieldClass).val(this.combination); localStorage.removeItem("field_class"); } if (this.bom_resource_id) { $('a.show.bom_resource_id').trigger('click'); } }; $(document).ready(function() { var mandatoryCheck = new mandatoryFieldMain(); mandatoryCheck.header_id = 'bom_resource_id'; mandatoryCheck.mandatoryHeader(); //selecting data $(".bom_resource_id.select_popup").on("click", function() { localStorage.idValue = ""; void window.open('select.php?class_name=bom_resource', '_blank', 'width=1000,height=800,TOOLBAR=no,MENUBAR=no,SCROLLBARS=yes,RESIZABLE=yes,LOCATION=no,DIRECTORIES=no,STATUS=no'); }); });
htphuoc94/MyERP_Stable
modules/lms/resource/lms_resource.js
JavaScript
mpl-2.0
1,248
module('embedding', { setup: function() { var $fixture = $('#qunit-fixture'); var $paper = $('<div/>'); $fixture.append($paper); this.graph = new joint.dia.Graph; this.paper = new joint.dia.Paper({ el: $paper, gridSize: 10, model: this.graph, embeddingMode: true }); }, teardown: function() { delete this.graph; delete this.paper; } }); test('sanity', function() { var r1 = new joint.shapes.basic.Rect({ position: { x: 100, y: 100 }, size: { width: 100, height: 100 } }); var r2 = new joint.shapes.basic.Rect({ position: { x: 500, y: 500 }, size: { width: 100, height: 100 } }); this.graph.addCells([r1,r2]); var v1 = r1.findView(this.paper); var v2 = r2.findView(this.paper); this.paper.options.embeddingMode = false; v2.pointerdown({ target: v1.el }, 500, 500); v2.pointermove({ target: v1.el }, 100, 100); v2.pointerup({ target: v1.el }, 100, 100); notEqual(r2.get('parent'), r1.id, 'embeddingMode disabled: element not embedded'); this.paper.options.embeddingMode = true; r2.set('position', { x: 500, y: 500 }); v2.pointerdown({ target: v1.el }, 500, 500); v2.pointermove({ target: v1.el }, 100, 100); v2.pointerup({ target: v1.el }, 100, 100); equal(r2.get('parent'), r1.id, 'embeddingMode enabled: element embedded'); this.paper.options.validateEmbedding = function() { return false; }; r1.unembed(r2); r2.set('position', { x: 500, y: 500 }); v2.pointerdown({ target: v2.el }, 500, 500); v2.pointermove({ target: v2.el }, 100, 100); v2.pointerup({ target: v2.el }, 100, 100); notEqual(r2.get('parent'), r1.id, 'validating function denying all element pairs provided: element not embedded.'); }); test('passing UI flag', function() { var r1 = new joint.shapes.basic.Rect({ position: { x: 100, y: 100 }, size: { width: 100, height: 100 } }); var r2 = new joint.shapes.basic.Rect({ position: { x: 500, y: 500 }, size: { width: 100, height: 100 } }); var r3 = new joint.shapes.basic.Rect({ position: { x: 600, y: 600 }, size: { width: 100, height: 100 } }); var l23 = new joint.dia.Link({ source: { id: r2.id }, target: { id: r3.id }}); var l22 = new joint.dia.Link({ source: { id: r2.id }, target: { id: r2.id }}); this.graph.addCells([r1,r2,r3,l23,l22]); var v2 = r2.findView(this.paper); this.paper.options.embeddingMode = true; var embedsCounter = 0; var parentCounter = 0; var zCounter = 0; this.graph.on('change:embeds', function(cell, embed, opt) { opt.ui && embedsCounter++; }); this.graph.on('change:parent', function(cell, parent, opt) { opt.ui && parentCounter++; }); this.graph.on('change:z', function(cell, z, opt) { opt.ui && zCounter++; }); v2.pointerdown({ target: v2.el }, 500, 500); v2.pointermove({ target: v2.el }, 100, 100); v2.pointerup({ target: v2.el }, 100, 100); deepEqual([embedsCounter, parentCounter, zCounter], [2,2,3], 'UI flags present (2 embedded, 2 reparented, 3 changed z-indexes).'); }); test('findParentBy option', function() { var r1 = new joint.shapes.basic.Rect({ position: { x: 100, y: 100 }, size: { width: 100, height: 100 } }); var r2 = new joint.shapes.basic.Rect({ position: { x: 50, y: 50 }, size: { width: 100, height: 100 } }); this.graph.addCells([r1,r2]); var v1 = r1.findView(this.paper); var v2 = r2.findView(this.paper); this.paper.options.findParentBy = 'bbox'; v2.prepareEmbedding(); v2.processEmbedding(); v2.finalizeEmbedding(); equal(r2.get('parent'), r1.id, 'parent found by bbox'); r1.unembed(r2); this.paper.options.findParentBy = 'corner'; v2.prepareEmbedding(); v2.processEmbedding(); v2.finalizeEmbedding(); equal(r2.get('parent'), r1.id, 'parent found by corner'); r1.unembed(r2); this.paper.options.findParentBy = 'origin'; v2.prepareEmbedding(); v2.processEmbedding(); v2.finalizeEmbedding(); notEqual(r2.get('parent'), r1.id, 'parent not found by origin'); }); test('highlighting & unhighlighting', function() { expect(4); var r1 = new joint.shapes.basic.Rect({ position: { x: 0, y: 0 }, size: { width: 1000, height: 1000 } }); var r2 = new joint.shapes.basic.Rect({ position: { x: 50, y: 50 }, size: { width: 100, height: 100 } }); this.graph.addCells([r1,r2]); var v2 = r2.findView(this.paper); this.paper.on('cell:highlight', function(cellView, el, opt) { equal(cellView.model.id,r1.id, 'Highlight event triggered for correct element.'); ok(opt.embedding, 'And embedding flag is present.'); }); this.paper.on('cell:unhighlight', function(cellView, el, opt) { equal(cellView.model.id,r1.id, 'Unhighlight event triggered for correct element.'); ok(opt.embedding, 'And embedding flag is present.'); }); v2.prepareEmbedding(); v2.processEmbedding(); v2.finalizeEmbedding(); }); test('frontParentOnly option', function() { var r1 = new joint.shapes.basic.Rect({ position: { x: 0, y: 0 }, size: { width: 200, height: 200 } }); var r2 = new joint.shapes.basic.Rect({ position: { x: 50, y: 50 }, size: { width: 100, height: 100 } }); var r3 = new joint.shapes.basic.Rect({ position: { x: 50, y: 50 }, size: { width: 100, height: 100 } }); this.graph.addCells([r1,r2,r3]); var v3 = r3.findView(this.paper); this.paper.options.validateEmbedding = function(childView, parentView) { return parentView.model.id != r2.id; }; this.paper.options.frontParentOnly = true; v3.prepareEmbedding(); v3.processEmbedding(); v3.finalizeEmbedding(); ok(!r3.get('parent'), 'disabled: parent on the bottom not found'); this.paper.options.frontParentOnly = false; v3.prepareEmbedding(); v3.processEmbedding(); v3.finalizeEmbedding(); equal(r3.get('parent'), r1.id, 'enabled: parent on the bottom found'); });
automagic/joint
test/jointjs/embedding.js
JavaScript
mpl-2.0
6,053
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeStaticFileCache = makeStaticFileCache; var _caching = require("../caching"); var fs = _interopRequireWildcard(require("../../gensync-utils/fs")); function _fs2() { const data = _interopRequireDefault(require("fs")); _fs2 = function () { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function makeStaticFileCache(fn) { return (0, _caching.makeStrongCache)(function* (filepath, cache) { const cached = cache.invalidate(() => fileMtime(filepath)); if (cached === null) { cache.forever(); return null; } return fn(filepath, (yield* fs.readFile(filepath, "utf8"))); }); } function fileMtime(filepath) { try { return +_fs2().default.statSync(filepath).mtime; } catch (e) { if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; } return null; }
BigBoss424/portfolio
v8/development/node_modules/@babel/core/lib/config/files/utils.js
JavaScript
apache-2.0
1,918