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
|
|---|---|---|---|---|---|
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Current list of countries of the world. This is generated from
* CLDR data using ICU. The algorithm is to list only country codes (not
* containments representing a groups of countries).
*
* File generated from CLDR ver. 36
*/
// clang-format off
/**
* Namespace for current country codes.
*/
goog.provide('goog.locale.countries');
/**
* List of codes for countries valid today.
* @type {!Array<string>}
*/
goog.locale.countries = [
'AC', // Ascension Island
'AD', // Andorra
'AE', // United Arab Emirates
'AF', // Afghanistan
'AG', // Antigua & Barbuda
'AI', // Anguilla
'AL', // Albania
'AM', // Armenia
'AO', // Angola
'AQ', // Antarctica
'AR', // Argentina
'AS', // American Samoa
'AT', // Austria
'AU', // Australia
'AW', // Aruba
'AX', // Åland Islands
'AZ', // Azerbaijan
'BA', // Bosnia & Herzegovina
'BB', // Barbados
'BD', // Bangladesh
'BE', // Belgium
'BF', // Burkina Faso
'BG', // Bulgaria
'BH', // Bahrain
'BI', // Burundi
'BJ', // Benin
'BL', // St. Barthélemy
'BM', // Bermuda
'BN', // Brunei
'BO', // Bolivia
'BQ', // Caribbean Netherlands
'BR', // Brazil
'BS', // Bahamas
'BT', // Bhutan
'BV', // Bouvet Island
'BW', // Botswana
'BY', // Belarus
'BZ', // Belize
'CA', // Canada
'CC', // Cocos (Keeling) Islands
'CD', // Congo - Kinshasa
'CF', // Central African Republic
'CG', // Congo - Brazzaville
'CH', // Switzerland
'CI', // Côte d’Ivoire
'CK', // Cook Islands
'CL', // Chile
'CM', // Cameroon
'CN', // China
'CO', // Colombia
'CP', // Clipperton Island
'CR', // Costa Rica
'CU', // Cuba
'CV', // Cape Verde
'CW', // Curaçao
'CX', // Christmas Island
'CY', // Cyprus
'CZ', // Czechia
'DE', // Germany
'DG', // Diego Garcia
'DJ', // Djibouti
'DK', // Denmark
'DM', // Dominica
'DO', // Dominican Republic
'DZ', // Algeria
'EA', // Ceuta & Melilla
'EC', // Ecuador
'EE', // Estonia
'EG', // Egypt
'EH', // Western Sahara
'ER', // Eritrea
'ES', // Spain
'ET', // Ethiopia
'FI', // Finland
'FJ', // Fiji
'FK', // Falkland Islands (Islas Malvinas)
'FM', // Micronesia
'FO', // Faroe Islands
'FR', // France
'GA', // Gabon
'GB', // United Kingdom
'GD', // Grenada
'GE', // Georgia
'GF', // French Guiana
'GG', // Guernsey
'GH', // Ghana
'GI', // Gibraltar
'GL', // Greenland
'GM', // Gambia
'GN', // Guinea
'GP', // Guadeloupe
'GQ', // Equatorial Guinea
'GR', // Greece
'GS', // South Georgia & South Sandwich Islands
'GT', // Guatemala
'GU', // Guam
'GW', // Guinea-Bissau
'GY', // Guyana
'HK', // Hong Kong
'HM', // Heard & McDonald Islands
'HN', // Honduras
'HR', // Croatia
'HT', // Haiti
'HU', // Hungary
'IC', // Canary Islands
'ID', // Indonesia
'IE', // Ireland
'IL', // Israel
'IM', // Isle of Man
'IN', // India
'IO', // British Indian Ocean Territory
'IQ', // Iraq
'IR', // Iran
'IS', // Iceland
'IT', // Italy
'JE', // Jersey
'JM', // Jamaica
'JO', // Jordan
'JP', // Japan
'KE', // Kenya
'KG', // Kyrgyzstan
'KH', // Cambodia
'KI', // Kiribati
'KM', // Comoros
'KN', // St. Kitts & Nevis
'KP', // North Korea
'KR', // South Korea
'KW', // Kuwait
'KY', // Cayman Islands
'KZ', // Kazakhstan
'LA', // Laos
'LB', // Lebanon
'LC', // St. Lucia
'LI', // Liechtenstein
'LK', // Sri Lanka
'LR', // Liberia
'LS', // Lesotho
'LT', // Lithuania
'LU', // Luxembourg
'LV', // Latvia
'LY', // Libya
'MA', // Morocco
'MC', // Monaco
'MD', // Moldova
'ME', // Montenegro
'MF', // St. Martin
'MG', // Madagascar
'MH', // Marshall Islands
'MK', // North Macedonia
'ML', // Mali
'MM', // Myanmar (Burma)
'MN', // Mongolia
'MO', // Macao
'MP', // Northern Mariana Islands
'MQ', // Martinique
'MR', // Mauritania
'MS', // Montserrat
'MT', // Malta
'MU', // Mauritius
'MV', // Maldives
'MW', // Malawi
'MX', // Mexico
'MY', // Malaysia
'MZ', // Mozambique
'NA', // Namibia
'NC', // New Caledonia
'NE', // Niger
'NF', // Norfolk Island
'NG', // Nigeria
'NI', // Nicaragua
'NL', // Netherlands
'NO', // Norway
'NP', // Nepal
'NR', // Nauru
'NU', // Niue
'NZ', // New Zealand
'OM', // Oman
'PA', // Panama
'PE', // Peru
'PF', // French Polynesia
'PG', // Papua New Guinea
'PH', // Philippines
'PK', // Pakistan
'PL', // Poland
'PM', // St. Pierre & Miquelon
'PN', // Pitcairn Islands
'PR', // Puerto Rico
'PS', // Palestine
'PT', // Portugal
'PW', // Palau
'PY', // Paraguay
'QA', // Qatar
'RE', // Réunion
'RO', // Romania
'RS', // Serbia
'RU', // Russia
'RW', // Rwanda
'SA', // Saudi Arabia
'SB', // Solomon Islands
'SC', // Seychelles
'SD', // Sudan
'SE', // Sweden
'SG', // Singapore
'SH', // St. Helena
'SI', // Slovenia
'SJ', // Svalbard & Jan Mayen
'SK', // Slovakia
'SL', // Sierra Leone
'SM', // San Marino
'SN', // Senegal
'SO', // Somalia
'SR', // Suriname
'SS', // South Sudan
'ST', // São Tomé & Príncipe
'SV', // El Salvador
'SX', // Sint Maarten
'SY', // Syria
'SZ', // Eswatini
'TA', // Tristan da Cunha
'TC', // Turks & Caicos Islands
'TD', // Chad
'TF', // French Southern Territories
'TG', // Togo
'TH', // Thailand
'TJ', // Tajikistan
'TK', // Tokelau
'TL', // Timor-Leste
'TM', // Turkmenistan
'TN', // Tunisia
'TO', // Tonga
'TR', // Turkey
'TT', // Trinidad & Tobago
'TV', // Tuvalu
'TW', // Taiwan
'TZ', // Tanzania
'UA', // Ukraine
'UG', // Uganda
'UM', // U.S. Outlying Islands
'US', // United States
'UY', // Uruguay
'UZ', // Uzbekistan
'VA', // Vatican City
'VC', // St. Vincent & Grenadines
'VE', // Venezuela
'VG', // British Virgin Islands
'VI', // U.S. Virgin Islands
'VN', // Vietnam
'VU', // Vanuatu
'WF', // Wallis & Futuna
'WS', // Samoa
'XK', // Kosovo
'YE', // Yemen
'YT', // Mayotte
'ZA', // South Africa
'ZM', // Zambia
'ZW' // Zimbabwe
];
|
lucidsoftware/closure-library
|
closure/goog/locale/countries.js
|
JavaScript
|
apache-2.0
| 6,672
|
export default class WordsService {
constructor($http, $filter) {
this.$http = $http;
this.$filter = $filter;
this.auth = 'K4OGxRo7BRwVduiz8KBijyZsmshvXI0WXOQFzWzS';
};
getWordObj(data){
var selfParent = this;
class Word{
constructor(data){
this.id = data && data.id !== undefined ? data.id : null;
this.value = data && data.value ? data.value : null;
this.maskedValue = null;
this.size = data && data.value ? (data.value.length)*74 : null; //74 full size for letter
this.mask = '';
var self = this;
for(var i = 0;i < this.value.length;i++){
self.mask += 'A';
};
};
setMaskedValue(){
var a = this.value.split(""),
n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
this.maskedValue = a.join("");
// console.info('setMaskedValue : this.value',this.value,a.join("")', a.join(""));
};
checkInput(val){
var result = true,
self = this;
if(val){
for(var i = 0;i < val.length; i++){
if(selfParent.$filter('uppercase')(self.value[i]) !== selfParent.$filter('uppercase')(val[i])){
result = false;
}
};
if(val.length !== self.value.length){
result = false;
};
}else{
result = false;
}
// console.info('XXX result', result);
return result;
};
}
return new Word(data);
};
getListOfWordsObject(){
class ListOfWords{
constructor(){
this.data = [];
this.testingData = [];
}
getRandomList(){
var shuffle = function(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
angular.copy(this.data, this.testingData);
this.testingData = shuffle(this.testingData);
this.testingData.forEach(function(el){
el.setMaskedValue();
});
// console.info(this.data, this.testingData);
};
};
return new ListOfWords();
};
//call http request for getting words from backend
getWordsFromBackend(successCbk, errorCbk){
var url = 'https://nx-puzzle.firebaseio.com/words.json?auth=' + this.auth;
this.$http.get(url).then(function(res){
console.log('WordsService -≥ getWordsFromBackend : Words were loaded successfully. Response:',res);
successCbk(res);
}, function (res) {
console.error('WordsService -≥ getWordsFromBackend : There was an error during loading words. Response:', res);
errorCbk(res);
});
}
initListOfWords(succCbk, errorCbk){
var listOfWords = this.getListOfWordsObject(),
self = this;
this.getWordsFromBackend(function(res){
if(res && res.data && res.data.length){
listOfWords.data = res.data.map(function(el){
return self.getWordObj(el);
});
// console.log('WordsService -≥ initListOfWords : XXX',res);
succCbk(listOfWords);
};
}, function(){
errorCbk();
});
};
}
WordsService.$inject = ['$http', '$filter'];
|
nusix/nx-puzzle
|
client/app/common/services/words.service.js
|
JavaScript
|
apache-2.0
| 4,582
|
MacPlayer.Html = '<iframe width="100%" height="'+MacPlayer.Height+'" src="http://vip.jiuli8.com/ykvip.php?url='+MacPlayer.PlayUrl+'" frameborder="0" border="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>';
MacPlayer.Show();
|
chendaiming/VideoMao
|
player/youku.js
|
JavaScript
|
apache-2.0
| 240
|
/**
* @license Copyright 2018 The Lighthouse 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.
*/
'use strict';
/**
* @param {LH.Gatherer.Simulation.Result['nodeTimings']} nodeTimings
* @return {LH.Trace}
*/
function convertNodeTimingsToTrace(nodeTimings) {
/** @type {LH.TraceEvent[]} */
const traceEvents = [];
const baseTs = 1e9;
const baseEvent = {pid: 1, tid: 1, cat: 'devtools.timeline'};
const frame = 'A00001';
/** @param {number} ms */
const toMicroseconds = ms => baseTs + ms * 1000;
traceEvents.push(createFakeTracingStartedEvent());
traceEvents.push({...createFakeTracingStartedEvent(), name: 'TracingStartedInBrowser'});
// Create a fake requestId counter
let requestId = 1;
let lastEventEndTime = 0;
for (const [node, timing] of nodeTimings.entries()) {
lastEventEndTime = Math.max(lastEventEndTime, timing.endTime);
if (node.type === 'cpu') {
// Represent all CPU work that was bundled in a task as an EvaluateScript event
traceEvents.push(...createFakeTaskEvents(node, timing));
} else {
// Ignore data URIs as they don't really add much value
if (/^data/.test(node.record.url)) continue;
traceEvents.push(...createFakeNetworkEvents(node.record, timing));
}
}
// Create a fake task event ~1s after the trace ends for a sane default bounds in DT
traceEvents.push(
...createFakeTaskEvents(
// @ts-expect-error
{childEvents: [], event: {}},
{
startTime: lastEventEndTime + 1000,
endTime: lastEventEndTime + 1001,
}
)
);
return {traceEvents};
/**
* @return {LH.TraceEvent}
*/
function createFakeTracingStartedEvent() {
const argsData = {
frameTreeNodeId: 1,
sessionId: '1.1',
page: frame,
persistentIds: true,
frames: [{frame, url: 'about:blank', name: '', processId: 1}],
};
return {
...baseEvent,
ts: baseTs - 1e5,
ph: 'I',
s: 't',
cat: 'disabled-by-default-devtools.timeline',
name: 'TracingStartedInPage',
args: {data: argsData},
dur: 0,
};
}
/**
* @param {LH.Gatherer.Simulation.GraphCPUNode} cpuNode
* @param {{startTime: number, endTime: number}} timing
* @return {LH.TraceEvent[]}
*/
function createFakeTaskEvents(cpuNode, timing) {
const argsData = {
url: '',
frame,
lineNumber: 0,
columnNumber: 0,
};
const eventTs = toMicroseconds(timing.startTime);
/** @type {LH.TraceEvent[]} */
const events = [
{
...baseEvent,
ph: 'X',
name: 'Task',
ts: eventTs,
dur: (timing.endTime - timing.startTime) * 1000,
args: {data: argsData},
},
];
const nestedBaseTs = cpuNode.event.ts || 0;
const multiplier = (timing.endTime - timing.startTime) * 1000 / cpuNode.event.dur;
// https://github.com/ChromeDevTools/devtools-frontend/blob/5429ac8a61ad4fa/front_end/timeline_model/TimelineModel.js#L1129-L1130
const netReqEvents = new Set(['ResourceSendRequest', 'ResourceFinish',
'ResourceReceiveResponse', 'ResourceReceivedData']);
for (const event of cpuNode.childEvents) {
if (netReqEvents.has(event.name)) continue;
const ts = eventTs + (event.ts - nestedBaseTs) * multiplier;
const newEvent = {...event, ...{pid: baseEvent.pid, tid: baseEvent.tid}, ts};
if (event.dur) newEvent.dur = event.dur * multiplier;
events.push(newEvent);
}
return events;
}
/**
* @param {LH.Artifacts.NetworkRequest} record
* @param {LH.Gatherer.Simulation.NodeTiming} timing
* @return {LH.TraceEvent[]}
*/
function createFakeNetworkEvents(record, timing) {
requestId++;
// 0ms requests get super-messed up rendering
// Use 0.3ms instead so they're still hoverable, https://github.com/GoogleChrome/lighthouse/pull/5350#discussion_r194563201
let {startTime, endTime} = timing; // eslint-disable-line prefer-const
if (startTime === endTime) endTime += 0.3;
const requestData = {requestId: requestId.toString(), frame};
/** @type {StrictOmit<LH.TraceEvent, 'name'|'ts'|'args'>} */
const baseRequestEvent = {...baseEvent, ph: 'I', s: 't', dur: 0};
const sendRequestData = {
...requestData,
requestMethod: record.requestMethod,
url: record.url,
priority: record.priority,
};
const receiveResponseData = {
...requestData,
statusCode: record.statusCode,
mimeType: record.mimeType,
encodedDataLength: record.transferSize,
fromCache: record.fromDiskCache,
fromServiceWorker: record.fetchedViaServiceWorker,
};
const resourceFinishData = {
...requestData,
decodedBodyLength: record.resourceSize,
didFail: !!record.failed,
finishTime: endTime,
};
/** @type {LH.TraceEvent[]} */
const events = [
{
...baseRequestEvent,
name: 'ResourceSendRequest',
ts: toMicroseconds(startTime),
args: {data: sendRequestData},
},
{
...baseRequestEvent,
name: 'ResourceFinish',
ts: toMicroseconds(endTime),
args: {data: resourceFinishData},
},
];
if (!record.failed) {
events.push({
...baseRequestEvent,
name: 'ResourceReceiveResponse',
ts: toMicroseconds((startTime + endTime) / 2),
args: {data: receiveResponseData},
});
}
return events;
}
}
module.exports = {
simulationNamesToIgnore: [
'unlabeled',
// These node timings should be nearly identical to the ones produced for Interactive
'optimisticFirstCPUIdle',
'optimisticFlexFirstCPUIdle',
'pessimisticFirstCPUIdle',
'optimisticSpeedIndex',
'optimisticFlexSpeedIndex',
'pessimisticSpeedIndex',
'optimisticEstimatedInputLatency',
'optimisticFlexEstimatedInputLatency',
'pessimisticEstimatedInputLatency',
],
convertNodeTimingsToTrace,
};
|
ev1stensberg/lighthouse
|
lighthouse-core/lib/lantern-trace-saver.js
|
JavaScript
|
apache-2.0
| 6,464
|
/**
* (C) Copyright 2014 WebGAP (http://www.webgap.eu/).
*
* 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.
*
* Created by: ManuelMartins
* Created on: 23-05-2014
*
*/
"use strict";
var configuration = require('@webgap/configuration');
var moment = require('moment');
var jwt = require('jwt-simple');
var assert = require('assert');
/**
* Abstract Token utilities
*
* @param {Object} options
* @param {string} options.host - the token generator host
* @param {string} options.validityThreshold - the validation threshold in milliseconds
*
* @returns {AbstractAlgorithm}
* @constructor
*/
function AbstractAlgorithm(options) {
var self = this;
options = options || {};
// algorithm
self.ALGORITHM = 'NONE';
self.host = options.host || configuration.get('SERVER.HOST');
self.validityThreshold = options.validityThreshold || configuration.get('GENERAL.TOKEN.VALIDITY_TIME');
// imports
this.jwt = jwt;
}
/**
* Encodes an object using The
*
* @param data the data to encode
* @returns {*}
*/
AbstractAlgorithm.prototype.encode = function (data) {
assert.ok(data);
throw new Error('Not implemented');
};
/**
* Decodes a specific token encoded in HS512
*
* @param token the token to decode
* @returns {*}
*/
AbstractAlgorithm.prototype.decode = function (token, complete) {
assert.ok(token);
assert.ok(complete);
throw new Error('Not implemented');
};
/**
* Wraps the data into an object containing:
*
* {String} data - the data passed as argument (can be an object)
* {String} host - the host creating the token
* {String} issuedAt - the creation date
* {String} expiresAt - the expire date
*
* @param data the data to encode
* @returns {*}
*/
AbstractAlgorithm.prototype.generateJWTObject = function (data) {
var self = this;
return {
data: data,
host: self.host,
issuedAt: moment(),
expiresAt: moment().add(self.validityThreshold, 'milliseconds')
};
};
/**
* Check whether a token is valid by check is integrity and validity
*
* @param token the token to validate
* @returns {*}
*/
AbstractAlgorithm.prototype.isValid = function (token) {
var decodedToken = this.decode(token, true);
return decodedToken && moment().isBefore(moment(decodedToken.expiresAt));
};
module.exports = AbstractAlgorithm;
|
webgap/token
|
lib/abstract.js
|
JavaScript
|
apache-2.0
| 2,801
|
/**
* @module last-saved.spec.js
* @description This module tests functionality around the
* `jr://instance/last-saved` virtual endpoint, including client storage and
* populating secondary instances.
* @see {@link https://getodk.github.io/xforms-spec/#virtual-endpoints}
* @see {@link https://getodk.github.io/xforms-spec/#secondary-instances---external}
* @see {ConnectionSpec}
* @see {RecordQueueSpec}
* @see {SurveyEncryptionFeatureSpec}
*/
import connection from '../../../public/js/src/module/connection';
import encryptor from '../../../public/js/src/module/encryptor';
import formCache from '../../../public/js/src/module/form-cache';
import {
getLastSavedRecord,
isLastSaveEnabled,
LAST_SAVED_VIRTUAL_ENDPOINT,
populateLastSavedInstances,
removeLastSavedRecord,
setLastSavedRecord,
} from '../../../public/js/src/module/last-saved';
import records from '../../../public/js/src/module/records-queue';
import settings from '../../../public/js/src/module/settings';
import store from '../../../public/js/src/module/store';
/**
* @typedef {import('../connection.spec.js')} ConnectionSpec
*/
/**
* @typedef {import('../records-queue.spec.js')} RecordQueueSpec
*/
/**
* @typedef {import('../store.spec.js')} StoreSpec
*/
/**
* @typedef {import('./survey-encryption.spec.js')} SurveyEncryptionFeatureSpec
*/
/**
* @typedef {import('../../app/models/record-model').EnketoRecord} EnketoRecord
*/
/**
* @typedef {import('../../app/models/survey-model').SurveyObject} Survey
*/
/**
* @typedef SinonSandbox { import('sinon').SinonSandbox }
*/
describe( 'Support for jr://instance/last-saved endpoint', () => {
const nativeDateNow = Date.now.bind( Date );
const enketoIdA = 'surveyA';
const instanceIdA = 'recordA';
const enketoIdB = 'surveyB';
const instanceIdB = 'recordB';
const encryptionKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5s9p+VdyX1ikG8nnoXLCC9hKfivAp/e1sHr3O15UQ+a8CjR/QV29+cO8zjS/KKgXZiOWvX+gDs2+5k9Kn4eQm5KhoZVw5Xla2PZtJESAd7dM9O5QrqVJ5Ukrq+kG/uV0nf6X8dxyIluNeCK1jE55J5trQMWT2SjDcj+OVoTdNGJ1H6FL+Horz2UqkIObW5/elItYF8zUZcO1meCtGwaPHxAxlvODe8JdKs3eMiIo9eTT4WbH1X+7nJ21E/FBd8EmnK/91UGOx2AayNxM0RN7pAcj47a434LzeM+XCnBztd+mtt1PSflF2CFE116ikEgLcXCj4aklfoON9TwDIQSp0wIDAQAB';
/** @type {string} */
let autoSavedKey;
/** @type { string } */
let enketoId;
/** @type { SinonSandbox } */
let sandbox;
/** @type {SinonFakeTimers} */
let timers;
/** @type { Survey } */
let surveyA;
/** @type { Survey } */
let surveyB;
/** @type { EnketoRecord } */
let recordA;
/** @type { EnketoRecord } */
let recordB;
/** @type {boolean} */
let skipStoreInitForSuite;
before( () => {
skipStoreInitForSuite = false;
} );
beforeEach( done => {
enketoId = enketoIdA;
sandbox = sinon.createSandbox();
// Prevent calls to `_updateCache` after tests complete/stubs are restored
timers = sandbox.useFakeTimers();
sandbox.stub( settings, 'enketoId' ).get( () => enketoId );
autoSavedKey = records.getAutoSavedKey();
surveyA = {
openRosaId: 'formA',
openRosaServer: 'http://localhost:3000',
enketoId: enketoIdA,
externalData: [
{
id: 'last-saved',
src: 'jr://instance/last-saved',
},
],
theme: '',
form: `<form class="or"><img src="/path/to/${enketoIdA}.jpg"/></form>`,
model: `<model><instance><data id="${enketoIdA}"><foo/></data></instance></model>`,
hash: '12345',
};
surveyB = {
openRosaId: 'formB',
openRosaServer: 'http://localhost:3000',
enketoId: enketoIdB,
externalData: [
{
id: 'last-saved',
src: 'jr://instance/last-saved',
},
],
theme: '',
form: `<form class="or"><img src="/path/to/${enketoIdB}.jpg"/></form>`,
model: `<model><instance><data id="${enketoIdB}"><bar/></data></instance></model>`,
hash: '67890',
};
recordA = {
draft: false,
enketoId,
files: [],
instanceId: instanceIdA,
name: 'name A',
xml: '<model><something>a</something></model>',
};
recordB = {
draft: false,
enketoId,
files: [],
instanceId: 'b',
name: 'name B',
xml: '<model><something>b</something></model>',
};
if ( skipStoreInitForSuite ) {
sandbox.stub( store, 'available' ).value( false );
return done();
}
store.init()
.then( records.init )
.then( () => store.record.set( {
draft: true,
instanceId: autoSavedKey,
enketoId,
name: `__autoSave_${nativeDateNow()}`,
xml: '<model><autosaved/></model>',
files: [],
} ) )
.then( () => store.survey.set( surveyA ) )
.then( () => store.survey.set( surveyB ) )
.then( () => done(), done );
} );
afterEach( done => {
timers.clearTimeout();
timers.clearInterval();
timers.restore();
sandbox.restore();
if ( skipStoreInitForSuite ) {
return done();
}
Promise.all( [
store.property.removeAll(),
store.record.removeAll(),
store.survey.removeAll(),
store.lastSavedRecords.clear(),
] ).then( () => done(), done );
} );
after( () => {
skipStoreInitForSuite = false;
} );
describe( 'surveys', () => {
/**
* @param {Partial<GetFormPartsStubResult>} updates
*/
const updateSurvey = ( updates ) => {
// Ensure `_updateCache` receives a new hash indicating it should perform an update
sandbox.stub( connection, 'getFormPartsHash' ).callsFake( () => {
return Promise.resolve( updates.hash );
} );
let updatePromise = new Promise( resolve => {
setTimeout( resolve, formCache.CACHE_UPDATE_INITIAL_DELAY + 1 );
} );
const originalStoreUpdate = store.survey.update.bind( store.survey );
sandbox.stub( store.survey, 'update' ).callsFake( update => {
return originalStoreUpdate( update ).then( result => {
if ( update.model === updates.model ) {
timers.tick( 1 );
}
return result;
} );
} );
timers.tick( formCache.CACHE_UPDATE_INITIAL_DELAY );
getFormPartsStubResult = Object.assign( {}, getFormPartsStubResult, updates );
// Wait for `_updateCache` to resolve
return updatePromise.then( () => formCache.get( survey ) );
};
const url1 = '/path/to/source.png';
const form1 = `<form class="or"><img src="${url1}"/></form>`;
const defaultInstanceData = '<data id="modelA"><item>initial</item><meta><instanceID/></meta></data>';
const model1 = `<model><instance>${defaultInstanceData}</instance><instance id="last-saved" src="jr://instance/last-saved"/></model>`;
const hash1 = '12345';
const parser = new DOMParser();
/** @type { Survey } */
let survey;
/** @type {SurveyExternalData} */
let lastSavedExternalData;
/** @type {GetFormPartsStubResult} */
let getFormPartsStubResult;
/** @type {EnketoRecord} */
let record;
beforeEach( done => {
enketoId = 'surveyC';
record = {
draft: false,
enketoId,
instanceId: 'recordA',
name: 'name A',
xml: '<data id="modelA"><item>initial</item><meta><instanceID/></meta></data>',
};
survey = {
openRosaId: 'formC',
openRosaServer: 'http://localhost:3000',
enketoId,
theme: '',
};
sandbox.stub( settings, 'enketoId' ).get( () => enketoId );
lastSavedExternalData = {
id: 'last-saved',
src: 'jr://instance/last-saved',
xml: parser.parseFromString( defaultInstanceData, 'text/xml' ),
};
getFormPartsStubResult = {
externalData: [
lastSavedExternalData,
],
form: form1,
model: model1,
hash: hash1
};
sandbox.stub( connection, 'getFormParts' ).callsFake( survey => {
return getLastSavedRecord( survey.enketoId )
.then( lastSavedRecord => {
if ( lastSavedRecord != null ) {
return { lastSavedRecord };
}
return {};
} )
.then( lastSavedData => {
const formParts = Object.assign( {
enketoId: survey.enketoId,
}, getFormPartsStubResult, lastSavedData );
if ( encryptor.isEncryptionEnabled( survey ) ) {
return encryptor.setEncryptionEnabled( formParts );
}
return formParts;
} );
} );
store.init().then( done, done );
} );
afterEach( done => {
store.survey.removeAll().then( done, done );
} );
it( 'sets the survey\'s last saved record', done => {
const originalRecord = Object.assign( {}, record );
formCache.init( survey )
.then( survey => {
return setLastSavedRecord( survey, record );
} )
.then( ( { lastSavedRecord } ) => {
Object.entries( originalRecord ).forEach( ( [ key, value ] ) => {
expect( lastSavedRecord[ key ] ).to.equal( value );
} );
} )
.then( done, done );
} );
it( 'preserves the last saved record when a form is updated', done => {
const originalRecord = Object.assign( {}, record );
const update = Object.assign( {}, survey, {
hash: '123456',
model: `${model1}<!-- updated -->`,
} );
formCache.init( survey )
.then( survey => {
return setLastSavedRecord( survey, record );
} )
.then( () => updateSurvey( update ) )
.then( () => getLastSavedRecord( enketoId ) )
.then( lastSavedRecord => {
Object.entries( originalRecord ).forEach( ( [ key, value ] ) => {
expect( lastSavedRecord[ key ] ).to.equal( value );
} );
} )
.then( done, done );
} );
it( 'updates last-saved externalData when the last saved record is updated', done => {
const updatedItemValue = 'populated';
const update = Object.assign( {}, record, {
xml: `<data id="surveyA"><item>${updatedItemValue}</item><meta><instanceID>uuid:ea3baa91-74b5-4892-af6f-96267f7fe12e</instanceID></meta></data>`,
} );
formCache.init( survey )
.then( survey => setLastSavedRecord( survey, update ) )
.then( ( { survey } ) => {
expect( Array.isArray( survey.externalData ) ).to.equal( true );
expect( survey.externalData.length ).to.equal( 1 );
const data = survey.externalData[0];
expect( data.id ).to.equal( lastSavedExternalData.id );
expect( data.src ).to.equal( lastSavedExternalData.src );
/** @type {Element} */
const xmlDocument = data.xml.documentElement;
const dataItemValue = xmlDocument.querySelector( 'item' ).innerHTML;
expect( dataItemValue ).to.equal( updatedItemValue );
} )
.then( done, done );
} );
it( 'does not set the survey\'s last saved record when encryption is enabled', done => {
/** @type {Survey} */
let encryptedSurvey;
encryptor.setEncryptionEnabled( survey );
const form = { id: 'abc', version: '2', encryptionKey };
formCache.init( survey )
.then( survey => {
encryptedSurvey = encryptor.setEncryptionEnabled( survey );
} )
.then( () => encryptor.encryptRecord( form, record ) )
.then( encryptedRecord => {
return setLastSavedRecord( encryptedSurvey, encryptedRecord );
} )
.then( ( { lastSavedRecord } ) => {
expect( lastSavedRecord ).to.equal( undefined );
} )
.then( done, done );
} );
it( 'does not set the survey\'s last saved unencrypted draft record when encryption is enabled', done => {
encryptor.setEncryptionEnabled( survey );
record.draft = true;
formCache.init( survey )
.then( survey => {
return setLastSavedRecord( survey, record );
} )
.then( ( { lastSavedRecord } ) => {
expect( lastSavedRecord ).to.equal( undefined );
} )
.then( done, done );
} );
it( 'does not set the survey\'s last saved record when the model does not populate a last-saved secondary instance', done => {
getFormPartsStubResult = Object.assign( {}, getFormPartsStubResult, {
externalData: [],
} );
formCache.init( survey )
.then( survey => {
return setLastSavedRecord( survey, record );
} )
.then( ( { lastSavedRecord } ) => {
expect( lastSavedRecord ).to.equal( undefined );
} )
.then( done, done );
} );
it( 'removes the survey\'s last saved record when the model no longer populates a last-saved secondary instance', done => {
const update = Object.assign( {}, survey, {
hash: '123456',
model: `${model1}<!-- updated -->`,
externalData: [],
} );
formCache.init( survey )
.then( survey => {
return setLastSavedRecord( survey, record );
} )
.then( () => updateSurvey( update ) )
.then( () => getLastSavedRecord( enketoId ) )
.then( lastSavedRecord => {
expect( lastSavedRecord ).to.equal( undefined );
} )
.then( done, done );
} );
it( 'gets the survey\'s last saved record', done => {
const originalRecord = Object.assign( {}, record );
formCache.init( survey )
.then( survey => {
return setLastSavedRecord( survey, record );
} )
.then( ( { survey } ) => {
return getLastSavedRecord( survey.enketoId );
} )
.then( lastSavedRecord => {
Object.entries( originalRecord ).forEach( ( [ key, value ] ) => {
expect( lastSavedRecord[ key ] ).to.equal( value );
} );
} )
.then( done, done );
} );
} );
describe( 'storage for offline mode', () => {
beforeEach( done => {
formCache.init( surveyA ).then( () => done(), done );
} );
it( 'creates a last-saved record when creating a record', done => {
const originalRecord = Object.assign( {}, recordA );
records.save( 'set', recordA )
.then( () => {
return getLastSavedRecord( enketoId );
} )
.then( record => {
Object.entries( originalRecord ).forEach( ( [ key, value ] ) => {
expect( record[key] ).to.deep.equal( value );
} );
} )
.then( done, done );
} );
it( 'replaces a last-saved record when creating a newer record', done => {
const originalRecord = Object.assign( {}, recordA );
records.save( 'set', recordB )
.then( () => {
return records.save( 'set', recordA );
} )
.then( () => {
return getLastSavedRecord( enketoId );
} )
.then( record => {
Object.entries( originalRecord ).forEach( ( [ key, value ] ) => {
expect( record[key] ).to.deep.equal( value );
} );
} )
.then( done, done );
} );
it( 'creates a last-saved record when updating a record', done => {
const originalSurvey = Object.assign( {}, surveyA );
const update = {
draft: false,
enketoId,
instanceId: instanceIdA,
name: 'name A updated',
xml: '<model><updated/></model>'
};
const payload = Object.assign( {}, update );
records.save( 'set', recordA )
.then( () => {
// This would be the condition in cases where a record already
// existed before this feature was implemented
return store.survey.update( originalSurvey );
} )
.then( () => {
return records.save( 'update', update );
} )
.then( () => {
return getLastSavedRecord( enketoId );
} )
.then( record => {
Object.entries( payload ).forEach( ( [ key, value ] ) => {
expect( record[key] ).to.deep.equal( value );
} );
} )
.then( done, done );
} );
it( 'replaces a last-saved record when updating a record', done => {
const update = {
draft: false,
enketoId,
instanceId: instanceIdA,
name: 'name A updated',
xml: '<model><updated/></model>'
};
const payload = Object.assign( {}, update );
records.save( 'set', recordA )
.then( () => {
return records.save( 'update', update );
} )
.then( () => {
return getLastSavedRecord( enketoId );
} )
.then( record => {
Object.entries( payload ).forEach( ( [ key, value ] ) => {
expect( record[key] ).to.deep.equal( value );
} );
} )
.then( done, done );
} );
it( 'creates separate last-saved records for different forms', done => {
const originalRecordA = Object.assign( {}, recordA );
/** @type { EnketoRecord } */
const recordB = {
draft: false,
enketoId: enketoIdB,
instanceId: instanceIdB,
name: 'name B',
xml: `<model><instance><something id="${enketoIdB}">b</something></model>`,
};
const originalRecordB = Object.assign( {}, recordB );
// Create record/last-saved for first form id
records.save( 'set', recordA )
// Create autosave record for second form id
.then( () => {
enketoId = enketoIdB;
return store.record.set( {
draft: true,
instanceId: records.getAutoSavedKey(),
enketoId,
name: `__autoSave_${nativeDateNow()}`,
xml: `<model><instance><autosaved id="${enketoId}"/></instance></model>`,
files: [],
} );
} )
// Create record/last-saved for second form id
.then( () => {
return records.save( 'set', recordB );
} )
// Get last-saved record for second form id
.then( () => {
return getLastSavedRecord( enketoId );
} )
// Validate last-saved record for second form id
.then( lastSavedB => {
Object.entries( originalRecordB ).forEach( ( [ key, value ] ) => {
expect( lastSavedB[key] ).to.deep.equal( value );
} );
} )
// Get last-saved record for first form id
.then( () => {
enketoId = enketoIdA;
return getLastSavedRecord( enketoId );
} )
// Validate last-saved record for first form id has not changed
.then( lastSavedA => {
Object.entries( originalRecordA ).forEach( ( [ key, value ] ) => {
expect( lastSavedA[key] ).to.deep.equal( value );
} );
} )
.then( done, done );
} );
} );
describe( 'storage for online mode', () => {
beforeEach( () => {
sandbox.stub( settings, 'enketoId' ).get( () => enketoId );
sandbox.stub( window, 'fetch' ).callsFake( () => {
return Promise.resolve( {
ok: true,
status: 201,
text() {
return Promise.resolve( `
<OpenRosaResponse xmlns="http://openrosa.org/http/response">
<message nature="submit_success">Success</message>
</OpenRosaResponse>
` );
},
} );
} );
} );
it( 'creates a last-saved record when uploading a record', done => {
const originalRecord = Object.assign( {}, recordA );
connection.uploadRecord( surveyA, recordA )
.then( () => {
return getLastSavedRecord( enketoId );
} )
.then( ( record ) => {
expect( record ).to.deep.equal( originalRecord );
} )
.then( done, done );
} );
it( 'does not create the survey\'s last saved record when editing a record', done => {
const updates = Object.assign( {}, recordA, {
xml: `${recordA.model}<-- Updated -->`,
} );
sandbox.stub( settings, 'type' ).get( () => 'edit' );
connection.uploadRecord( surveyA, updates )
.then( () => getLastSavedRecord( enketoId ) )
.then( lastSavedRecord => {
expect( lastSavedRecord ).to.equal( undefined );
} )
.then( done, done );
} );
it( 'does not update the survey\'s last saved record when editing a record', done => {
const originalXml = recordA.xml;
const updates = Object.assign( {}, recordA, {
xml: `${originalXml}<-- Updated -->`,
} );
let submissionType = 'other';
sandbox.stub( settings, 'type' ).get( () => submissionType );
setLastSavedRecord( surveyA, recordA )
.then( () => {
submissionType = 'edit';
} )
.then( () => connection.uploadRecord( surveyA, updates ) )
.then( () => {
submissionType = 'other';
} )
.then( () => getLastSavedRecord( enketoId ) )
.then( lastSavedRecord => {
expect( lastSavedRecord.xml ).to.equal( originalXml );
} )
.then( done, done );
} );
it( 'does not create a last-saved record when uploading a queued record', done => {
connection.uploadQueuedRecord( recordA )
.then( () => {
return getLastSavedRecord( enketoId );
} )
.then( ( record ) => {
expect( record ).to.equal( undefined );
} )
.then( done, done );
} );
it( 'does not cache the survey when uploading a record', done => {
const surveySetStub = sandbox.stub( store.survey, 'set' );
const surveyUpdateStub = sandbox.stub( store.survey, 'update' );
store.survey.removeAll()
.then( () => connection.uploadRecord( surveyA, recordA ) )
.then( () => {
expect( surveySetStub.callCount ).to.equal( 0 );
expect( surveyUpdateStub.callCount ).to.equal( 0 );
} )
.then( done, done );
} );
} );
describe( 'populating secondary instances', () => {
const enketoId = 'surveyA';
const instanceId = 'recordA';
const defaultInstanceData = '<data id="modelA"><item>initial</item><meta><instanceID/></meta></data>';
const xmlSerializer = new XMLSerializer();
/**
* @typedef FetchFormResponse
* @property {string} form
* @property {string} model
* @property {string} theme
* @property {string} hash
* @property {string} languageMap
*/
/** @type {boolean} */
let isFormEncrypted;
/** @type {string} */
let settingsType;
beforeEach( () => {
isFormEncrypted = false;
settingsType = 'other';
sandbox.stub( settings, 'type' ).get( () => settingsType );
sandbox.stub( settings, 'enketoId' ).get( () => enketoId );
sandbox.stub( window, 'fetch' ).callsFake( () => {
return Promise.resolve( {
ok: true,
status: 201,
json() {
const submission = isFormEncrypted
? `<submission base64RsaPublicKey="${encryptionKey}"/>`
: '';
return Promise.resolve( {
form: '<form autocomplete="off" novalidate="novalidate" class="or clearfix" dir="ltr" id="surveyA"><!--This form was created by transforming an ODK/OpenRosa-flavored (X)Form using an XSL stylesheet created by Enketo LLC.--><section class="form-logo"></section><h3 dir="auto" id="form-title">Form with last-saved instance</h3><label class="question non-select "><span lang="" class="question-label active">Last saved</span><input type="text" name="/data/item" data-type-xml="string" data-setvalue="instance(\'last-saved\')/data/item" data-event="odk-instance-first-load"></label><fieldset id="or-setvalue-items" style="display:none;"></fieldset></form>',
model: `<model><instance>${defaultInstanceData}</instance><instance id="last-saved" src="jr://instance/last-saved"/>${submission}</model>`,
theme: '',
hash: 'md5:1fbbe9738efec026b5a14aa3c3152221--2a8178bb883ae91dfe205c168b54c0cf---1',
languageMap: {},
} );
},
} );
} );
} );
it( 'populates a last-saved secondary instance from the survey\'s last-saved record', done => {
const lastSavedRecord = {
enketoId,
instanceId,
name: 'name A',
xml: '<data id="surveyA"><item>populated</item><meta><instanceID>uuid:ea3baa91-74b5-4892-af6f-96267f7fe12e</instanceID></meta></data>',
files: [],
};
connection.getFormParts( { enketoId } )
.then( survey => setLastSavedRecord( survey, lastSavedRecord ) )
.then( () => connection.getFormParts( { enketoId } ) )
.then( result => {
expect( Array.isArray( result.externalData ) ).to.equal( true );
expect( result.externalData.length ).to.equal( 1 );
const data = result.externalData[0];
expect( data.id ).to.equal( 'last-saved' );
expect( data.src ).to.equal( 'jr://instance/last-saved' );
const xml = xmlSerializer.serializeToString( data.xml.documentElement, 'text/xml' );
expect( xml ).to.equal( lastSavedRecord.xml );
} )
.then( done, done );
} );
it( 'populates a last-saved secondary instance with the model\'s defaults when no last-saved record is available', done => {
connection.getFormParts( { enketoId } )
.then( result => {
expect( Array.isArray( result.externalData ) ).to.equal( true );
expect( result.externalData.length ).to.equal( 1 );
const data = result.externalData[0];
expect( data.id ).to.equal( 'last-saved' );
expect( data.src ).to.equal( 'jr://instance/last-saved' );
const xml = xmlSerializer.serializeToString( data.xml.documentElement, 'text/xml' );
expect( xml ).to.equal( defaultInstanceData );
} )
.then( done, done );
} );
it( 'populates a last-saved secondary instance with the model\'s defaults when editing an instance', done => {
settingsType = 'edit';
const lastSavedRecord = {
enketoId,
instanceId,
name: 'name A',
xml: '<data id="surveyA"><item>populated</item><meta><instanceID>uuid:ea3baa91-74b5-4892-af6f-96267f7fe12e</instanceID></meta></data>',
files: [],
};
connection.getFormParts( { enketoId, instanceId } )
.then( survey => setLastSavedRecord( survey, lastSavedRecord ) )
.then( () => connection.getFormParts( { enketoId, instanceId } ) )
.then( result => {
expect( Array.isArray( result.externalData ) ).to.equal( true );
expect( result.externalData.length ).to.equal( 1 );
const data = result.externalData[0];
expect( data.id ).to.equal( 'last-saved' );
expect( data.src ).to.equal( 'jr://instance/last-saved' );
const xml = xmlSerializer.serializeToString( data.xml.documentElement, 'text/xml' );
expect( xml ).to.equal( defaultInstanceData );
} )
.then( done, done );
} );
it( 'populates a last-saved secondary instance with the model\'s defaults when previewing a form', done => {
settingsType = 'preview';
connection.getFormParts( { enketoId, instanceId } )
.then( result => {
expect( Array.isArray( result.externalData ) ).to.equal( true );
expect( result.externalData.length ).to.equal( 1 );
const data = result.externalData[0];
expect( data.id ).to.equal( 'last-saved' );
expect( data.src ).to.equal( 'jr://instance/last-saved' );
const xml = xmlSerializer.serializeToString( data.xml.documentElement, 'text/xml' );
expect( xml ).to.equal( defaultInstanceData );
} )
.then( done, done );
} );
it( 'updates an existing cached survey\'s last saved secondary instances when uploading a record', done => {
connection.uploadRecord( surveyA, recordA )
.then( () => formCache.get( surveyA ) )
.then( cachedSurvey => {
expect( Array.isArray( cachedSurvey.externalData ) ).to.equal( true );
expect( cachedSurvey.externalData.length ).to.equal( 1 );
const data = cachedSurvey.externalData[0];
expect( data.id ).to.equal( 'last-saved' );
expect( data.src ).to.equal( 'jr://instance/last-saved' );
const xml = xmlSerializer.serializeToString( data.xml.documentElement, 'text/xml' );
expect( xml ).to.equal( recordA.xml );
} )
.then( done, done );
} );
it( 'populates a last-saved secondary instance with the model\'s defaults when requesting an encrypted form online', async () => {
const survey = await connection.getFormParts( { enketoId } );
const lastSavedRecord = {
enketoId,
instanceId,
name: 'name A',
xml: '<data id="surveyA"><item>populated</item><meta><instanceID>uuid:ea3baa91-74b5-4892-af6f-96267f7fe12e</instanceID></meta></data>',
files: [],
};
await setLastSavedRecord( survey, lastSavedRecord );
isFormEncrypted = true;
const result = await connection.getFormParts( { enketoId } );
expect( Array.isArray( result.externalData ) ).to.equal( true );
expect( result.externalData.length ).to.equal( 1 );
const data = result.externalData[0];
expect( data.id ).to.equal( 'last-saved' );
expect( data.src ).to.equal( 'jr://instance/last-saved' );
const xml = xmlSerializer.serializeToString( data.xml.documentElement, 'text/xml' );
expect( xml ).not.to.equal( recordA.xml );
expect( xml ).to.equal( defaultInstanceData );
} );
it( 'populates a last-saved secondary instance with the model\'s defaults when encryption is enabled on an offline cached survey with a last-saved instance', async () => {
const parser = new DOMParser();
const model = parser.parseFromString( surveyA.model, 'text/xml' );
const defaultInstance = model.documentElement.querySelector( 'instance > *' );
const defaultInstanceData = xmlSerializer.serializeToString( defaultInstance, 'text/xml' );
await setLastSavedRecord( surveyA, recordA );
const survey = await formCache.init( surveyA );
const encryptedSurvey = encryptor.setEncryptionEnabled( survey );
await store.survey.update( encryptedSurvey );
const result = await formCache.get( { enketoId } );
expect( Array.isArray( result.externalData ) ).to.equal( true );
expect( result.externalData.length ).to.equal( 1 );
const data = result.externalData[0];
expect( data.id ).to.equal( 'last-saved' );
expect( data.src ).to.equal( 'jr://instance/last-saved' );
const xml = xmlSerializer.serializeToString( data.xml.documentElement, 'text/xml' );
expect( xml ).not.to.equal( recordA.xml );
expect( xml ).to.equal( defaultInstanceData );
} );
} );
describe( 'IndexedDB initialization failure', () => {
/**
* @typedef {import('sinon').SinonStub} Stub
*/
/** @type {Stub} */
let getStub;
/** @type {Stub} */
let removeStub;
/** @type {Stub} */
let updateStub;
before( () => {
skipStoreInitForSuite = true;
} );
beforeEach( () => {
sandbox.stub( settings, 'type' ).get( () => 'other' );
getStub = sandbox.stub().resolves();
removeStub = sandbox.stub().resolves();
updateStub = sandbox.stub().resolves();
sandbox.stub( store, 'lastSavedRecords' ).get( () => {
return {
get: getStub,
remove: removeStub,
update: updateStub,
};
} );
} );
it( 'does not enable last-saved', () => {
const result = isLastSaveEnabled( surveyA );
expect( result ).to.equal( false );
} );
it( 'does not get a last saved record', async () => {
await getLastSavedRecord( enketoId );
expect( getStub ).not.to.have.been.called;
} );
it( 'does not attempt to remove a last saved record', async () => {
await removeLastSavedRecord( enketoId );
expect( removeStub ).not.to.have.been.called;
} );
it( 'populates a last saved record with the default model', async () => {
const defaultValue = 'default value';
const survey = {
...surveyA,
externalData: [
{
id: 'last-saved',
src: LAST_SAVED_VIRTUAL_ENDPOINT,
},
],
model: `<model>
<instance>
<something>${defaultValue}</something>
</instance>
</model>`,
};
const { externalData } = populateLastSavedInstances( survey, recordA );
const [ lastSaved ] = externalData;
const { textContent } = lastSaved.xml.querySelector( 'something' );
expect( textContent ).to.equal( defaultValue );
} );
it( 'does not attempt to set the last saved record', async () => {
await setLastSavedRecord( surveyA, recordA );
expect( updateStub ).not.to.have.been.called;
} );
it( 'does not attempt to remove the last saved record when setting with no last-saved record', async () => {
await setLastSavedRecord( surveyA );
expect( removeStub ).not.to.have.been.called;
} );
} );
} );
|
enketo/enketo-express
|
test/client/feature/last-saved.spec.js
|
JavaScript
|
apache-2.0
| 39,074
|
/**
* Fox details component.
*/
import React, {PropTypes, Component} from 'react';
import { bindActionCreators } from 'redux';
import {
View,
Text,
Image,
StyleSheet,
TouchableHighlight,
AsyncStorage
} from 'react-native';
import { connect } from 'react-redux';
import { Actions } from 'react-native-router-flux';
import _ from 'lodash';
import nativeImageSource from 'nativeImageSource';
import Navigation from '../components/Navigation';
class Details extends Component {
static propTypes = {
uuid: PropTypes.string.isRequired,
major: PropTypes.number.isRequired,
minor: PropTypes.number.isRequired
};
constructor(props) {
super(props);
this.state = {
isFoxСaught: false,
isReady: false
};
}
componentDidMount() {
this.startTime = new Date().getTime() / 1000;
const { uuid, major, minor } = this.props;
AsyncStorage.getItem('caughtFoxes')
.then(req => JSON.parse(req))
.then(caughtFoxes => {
if (!caughtFoxes) {
return null;
}
return _.find(caughtFoxes, (beacon) => {
return beacon.uuid === uuid && major === beacon.major && minor === beacon.minor;
});
})
.then(fox => {
this.setState({
isReady: true,
isFoxСaught: fox,
spentTime: fox ? fox.spentTime : 0
})
})
.catch(error => console.log('error!'))
}
handleFoxCatch() {
const spentTime = (new Date().getTime() / 1000 - this.startTime).toFixed(0);
const { uuid, major, minor } = this.props;
this.setState({
isFoxСaught: true,
spentTime
});
AsyncStorage.getItem('caughtFoxes')
.then(req => JSON.parse(req))
.then(caughtFoxes => {
if (!caughtFoxes) {
return [];
}
caughtFoxes.push({uuid, major, minor, spentTime});
return caughtFoxes;
})
.then(caughtFoxes => {
AsyncStorage.setItem('caughtFoxes', JSON.stringify(caughtFoxes))
})
.catch(error => console.log('error!'));
}
render() {
const { uuid, major, minor } = this.props;
const fox = _.find(this.props.beacons.items, (beacon) => {
return beacon.uuid === uuid && major === beacon.major && minor === beacon.minor;
});
return (
<View style={styles.container}>
<Navigation
title="CatchTheFox"
isBackShown
onBack={() => Actions.pop()}
/>
<View style={styles.content}>
<Text style={styles.foxInfo}>Лиса {this.props.beacons.aliases[`${uuid}|${major}|${minor}`]}</Text>
{this.renderCongratulation()}
{this.renderDistance(fox)}
{this.renderFoxCatch(fox)}
</View>
</View>
);
}
renderDistance(fox) {
if (this.state.isFoxСaught) {
return null;
}
if (!fox) {
return (
<Text style={styles.foxInfo}>Лиса куда-то убежала :(</Text>
);
} else {
return (
<Text style={styles.foxInfo}>Расстояние: <Text style={styles.distance}>{fox.distance.toFixed(2)} м</Text></Text>
);
}
}
renderFoxCatch(fox) {
if (this.state.isReady && !this.state.isFoxСaught && fox && fox.distance < 1) {
return (
<View
style={styles.catchContainer}>
<TouchableHighlight
underlayColor='#E0E0E0'
onPress={this.handleFoxCatch.bind(this)}>
<Image
source={require('../images/ic_fox.png')}/>
</TouchableHighlight>
</View>
);
}
}
renderCongratulation() {
if (this.state.isReady && this.state.isFoxСaught) {
return (
<View style={styles.congratulationContainer}>
<Text style={styles.congratulation}>Лиса поймана за</Text>
<Text style={styles.congratulationTime}>{this.state.spentTime} сек!</Text>
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
content: {
flex: 1,
padding: 16
},
toolbar: {
height: 48,
backgroundColor: '#E0E0E0'
},
catchContainer: {
alignItems: 'center',
margin: 16,
paddingTop: 32
},
congratulationContainer: {
backgroundColor: '#4CAF50',
alignItems: 'center',
padding: 16
},
congratulation: {
fontSize: 25,
color: '#FFFFFF'
},
congratulationTime: {
fontWeight: 'bold',
fontSize: 25,
color: '#FFFFFF'
},
foxInfo: {
fontSize: 20,
paddingBottom: 16
},
catchFox: {
fontSize: 25,
color: '#FFFFFF'
},
distance: {
fontWeight: 'bold',
fontSize: 24
}
});
const mapStateToProps = (state) => {
return {
beacons: state.beacons
};
};
export default connect(mapStateToProps)(Details);
|
AlekseiIvshin/CatchTheFox
|
app/containers/Details.js
|
JavaScript
|
apache-2.0
| 4,797
|
function (doc) {
if (doc.type && doc.type === 'question')
emit(doc._id, doc);
};
|
metajack/surveycouch
|
views/questions/map.js
|
JavaScript
|
apache-2.0
| 93
|
/* eslint-disable no-unused-vars */
var React = require("react");
/* eslint-enable no-unused-vars */
var TestUtils;
if (React.version.match(/15.[0-5]/)) {
TestUtils = require("react-addons-test-utils");
} else {
TestUtils = require("react-dom/test-utils");
}
jest.dontMock("../List.js");
jest.dontMock("../ListItem.js");
jest.dontMock("./fixtures/MockList");
jest.dontMock("../../Util/Util");
var MockList = require("./fixtures/MockList");
var List = require("../List.js");
describe("List", function() {
beforeEach(function() {
this.listTag = "ul";
this.instance = TestUtils.renderIntoDocument(
<List content={MockList} tag={this.listTag} />
);
});
it("should render whatever tag it receives in its attributes", function() {
var ulElements = TestUtils.scryRenderedDOMComponentsWithTag(
this.instance,
this.listTag
);
expect(ulElements.length).toEqual(1);
});
it("should render only one element with the class list", function() {
var listItems = TestUtils.scryRenderedDOMComponentsWithClass(
this.instance,
"list"
);
expect(listItems.length).toEqual(1);
});
it("renders one row per top-level item in the list array", function() {
var listItems = TestUtils.scryRenderedDOMComponentsWithClass(
this.instance,
"my-custom-row-class"
);
expect(listItems.length).toEqual(MockList.length);
});
});
|
mesosphere/reactjs-components
|
src/List/__tests__/List-test.js
|
JavaScript
|
apache-2.0
| 1,410
|
angular.module('xentinels').factory('AuthService', ['$q', '$location', '$timeout', '$http', '$cookies',
function($q, $location, $timeout, $http, $cookies) {
var _Auth = {};
// create user variable
var user = null;
_Auth.isLogged = false;
// return available functions for use in controllers
_Auth.logged = logged;
_Auth.login = login;
_Auth.logout = logout;
_Auth.register = register;
_Auth.signout = removeSession;
function removeSession() {
$cookies.remove("auth");
_Auth.isLogged = false;
$location.path("/");
}
function logged() {
if ($cookies.get("auth")) {
_Auth.isLogged = true;
return true;
} else {
return false;
}
}
function login(email, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/api/users/login', {
user_name: email,
password: password
})
// handle success
.success(function(data, status) {
if (status === 200 && data) {
_Auth.isLogged = true;
deferred.resolve(data);
} else {
_Auth.isLogged = false;
deferred.reject();
}
})
// handle error
.error(function(data) {
_Auth.isLogged = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function logout() {
// create a new instance of deferred
var deferred = $q.defer();
// send a get request to the server
$http.get('/api/logout')
// handle success
.success(function(data) {
user = false;
deferred.resolve();
})
// handle error
.error(function(data) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function register(email, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.post('/api/register', {
email: email,
password: password
})
// handle success
.success(function(data, status) {
if (status === 200 && data.result) {
deferred.resolve();
} else {
deferred.reject();
}
})
// handle error
.error(function(data) {
deferred.reject();
});
// return promise object
return deferred.promise;
}
return _Auth;
}
]);
|
emarinizquierdo/xentinels
|
app/app/services/auth.js
|
JavaScript
|
apache-2.0
| 3,334
|
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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';
// MODULES //
var tape = require( 'tape' );
var acoversin = require( '@stdlib/math/base/special/acoversin' );
var uniform = require( '@stdlib/random/base/uniform' ).factory;
var acoversinBy = require( './../lib/ndarray.js' );
// VARIABLES //
var rand = uniform( 0.0, 2.0 );
// FUNCTIONS //
function accessor( v ) {
if ( v === void 0 ) {
return;
}
return v;
}
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof acoversinBy, 'function', 'main export is a function' );
t.end();
});
tape( 'the function has an arity of 9', function test( t ) {
t.strictEqual( acoversinBy.length, 9, 'arity of 9' );
t.end();
});
tape( 'the function computes the inverse coversed sine via a callback function', function test( t ) {
var expected;
var x;
var y;
var i;
x = [];
y = [];
expected = [];
for ( i = 0; i < 10; i++ ) {
x.push( rand() );
y.push( 0.0 );
expected.push( acoversin( x[ i ] ) );
}
acoversinBy( x.length, x, 1, 0, y, 1, 0, accessor );
t.deepEqual( y, expected, 'deep equal' );
x = new Array( 5 ); // sparse array
y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
expected = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
acoversinBy( x.length, x, 1, 0, y, 1, 0, accessor );
t.deepEqual( y, expected, 'deep equal' );
x = new Array( 5 ); // sparse array
x[ 2 ] = rand();
y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
expected = y.slice();
expected[ 2 ] = acoversin( x[ 2 ] );
acoversinBy( x.length, x, 1, 0, y, 1, 0, accessor );
t.deepEqual( y, expected, 'deep equal' );
t.end();
});
tape( 'the function supports an `x` stride', function test( t ) {
var expected;
var x;
var y;
var N;
x = [
rand(), // 0
rand(),
rand(), // 1
rand(),
rand() // 2
];
y = [
0.0, // 0
0.0, // 1
0.0, // 2
0.0,
0.0
];
N = 3;
acoversinBy( N, x, 2, 0, y, 1, 0, accessor );
expected = [
acoversin( x[ 0 ] ),
acoversin( x[ 2 ] ),
acoversin( x[ 4 ] ),
0.0,
0.0
];
t.deepEqual( y, expected, 'deep equal' );
t.end();
});
tape( 'the function supports an `x` offset', function test( t ) {
var expected;
var x;
var y;
var N;
x = [
rand(),
rand(),
rand(), // 0
rand(), // 1
rand() // 2
];
y = [
0.0, // 0
0.0, // 1
0.0, // 2
0.0,
0.0
];
N = 3;
acoversinBy( N, x, 1, 2, y, 1, 0, accessor );
expected = [
acoversin( x[ 2 ] ),
acoversin( x[ 3 ] ),
acoversin( x[ 4 ] ),
0.0,
0.0
];
t.deepEqual( y, expected, 'deep equal' );
t.end();
});
tape( 'the function supports a `y` stride', function test( t ) {
var expected;
var x;
var y;
var N;
x = [
rand(), // 0
rand(), // 1
rand(), // 2
rand(),
rand()
];
y = [
0.0, // 0
0.0,
0.0, // 1
0.0,
0.0 // 2
];
N = 3;
acoversinBy( N, x, 1, 0, y, 2, 0, accessor );
expected = [
acoversin( x[ 0 ] ),
0.0,
acoversin( x[ 1 ] ),
0.0,
acoversin( x[ 2 ] )
];
t.deepEqual( y, expected, 'deep equal' );
t.end();
});
tape( 'the function supports a `y` offset', function test( t ) {
var expected;
var x;
var y;
var N;
x = [
rand(), // 0
rand(), // 1
rand(), // 2
rand(),
rand()
];
y = [
0.0,
0.0,
0.0, // 0
0.0, // 1
0.0 // 2
];
N = 3;
acoversinBy( N, x, 1, 0, y, 1, 2, accessor );
expected = [
0.0,
0.0,
acoversin( x[ 0 ] ),
acoversin( x[ 1 ] ),
acoversin( x[ 2 ] )
];
t.deepEqual( y, expected, 'deep equal' );
t.end();
});
tape( 'the function returns a reference to the destination array', function test( t ) {
var out;
var x;
var y;
x = [ rand(), rand(), rand(), rand(), rand() ];
y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
out = acoversinBy( x.length, x, 1, 0, y, 1, 0, accessor );
t.strictEqual( out, y, 'same reference' );
t.end();
});
tape( 'if provided an `N` parameter less than or equal to `0`, the function returns `y` unchanged', function test( t ) {
var expected;
var x;
var y;
x = [ rand(), rand(), rand(), rand(), rand() ];
y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
expected = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
acoversinBy( -1, x, 1, 0, y, 1, 0, accessor );
t.deepEqual( y, expected, 'returns `y` unchanged' );
acoversinBy( 0, x, 1, 0, y, 1, 0, accessor );
t.deepEqual( y, expected, 'returns `y` unchanged' );
t.end();
});
tape( 'the function supports negative strides', function test( t ) {
var expected;
var x;
var y;
var N;
x = [
rand(), // 2
rand(),
rand(), // 1
rand(),
rand() // 0
];
y = [
0.0,
0.0, // 2
0.0, // 1
0.0, // 0
0.0
];
N = 3;
acoversinBy( N, x, -2, x.length-1, y, -1, y.length-2, accessor );
expected = [
0.0,
acoversin( x[ 0 ] ),
acoversin( x[ 2 ] ),
acoversin( x[ 4 ] ),
0.0
];
t.deepEqual( y, expected, 'deep equal' );
t.end();
});
tape( 'the function supports complex access patterns', function test( t ) {
var expected;
var x;
var y;
var N;
x = [
rand(),
rand(), // 0
rand(),
rand(), // 1
rand(),
rand() // 2
];
y = [
0.0,
0.0,
0.0,
0.0, // 2
0.0, // 1
0.0 // 0
];
N = 3;
acoversinBy( N, x, 2, 1, y, -1, y.length-1, accessor );
expected = [
0.0,
0.0,
0.0,
acoversin( x[ 5 ] ),
acoversin( x[ 3 ] ),
acoversin( x[ 1 ] )
];
t.deepEqual( y, expected, 'deep equal' );
t.end();
});
tape( 'the function supports providing a callback execution context', function test( t ) {
var ctx;
var x;
var y;
x = [ rand(), rand(), rand(), rand(), rand() ];
y = [ 0.0, 0.0, 0.0, 0.0, 0.0 ];
ctx = {
'count': 0
};
acoversinBy( x.length, x, 1, 0, y, 1, 0, accessor, ctx );
t.strictEqual( ctx.count, x.length, 'returns expected value' );
t.end();
function accessor( v ) {
this.count += 1; // eslint-disable-line no-invalid-this
return v;
}
});
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/math/strided/special/acoversin-by/test/test.ndarray.js
|
JavaScript
|
apache-2.0
| 6,288
|
/**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CLASS({
package: 'foam.u2',
name: 'DAOUpdateController',
extends: 'foam.u2.View',
documentation: 'Expects $$DOC{ref:".data"} to be either: (a) the object to ' +
'view, or (b) the ID to view. Either way, this will do a find.',
requires: [
'foam.persistence.ObjectReplicator',
'foam.u2.md.DetailView',
'foam.u2.md.Toolbar',
'foam.u2.md.ToolbarAction'
],
imports: [
'document',
'stack'
],
exports: [
'myControllerMode as controllerMode'
],
properties: [
'model',
{
name: 'data',
postSet: function(old, nu) {
this.body_.removeAllChildren();
var replicator = this.ObjectReplicator.create({
dao: this.dao,
model: this.dao.model,
id: nu.id || nu
});
replicator.future.get(function(obj) {
this.body_.add( ( obj && obj.toE ) ? obj.toE(this.Y) : this.DetailView.create({ data: obj }) );
}.bind(this));
},
},
{
name: 'dao',
factory: function() {
return this.X[daoize(this.model.name)];
}
},
{
name: 'title',
factory: function() {
return 'Edit ' + this.data.model_.name;
}
},
{
name: 'body_',
factory: function() {
return this.Y.E('div').cls(this.myCls('body'));
}
},
{
name: 'toolbar_',
factory: function() {
var t = this.Toolbar.create({ title$: this.title$ });
t.addLeftActions([
this.ToolbarAction.create({ data: this, action: this.BACK }),
]);
t.addRightActions([
this.ToolbarAction.create({ data: this, action: this.DELETE })
]);
return t;
}
},
['myControllerMode', 'update']
],
actions: [
{
name: 'back',
ligature: 'arrow_back',
code: function() {
var active = this.document.activeElement;
active && active.blur();
// The blur above might have triggered data to update, so we call
// doBack(), which is framed. That gives the data time to settle.
this.doBack();
}
},
{
name: 'delete',
ligature: 'delete',
code: function() {
this.dao.remove(this.data.id, {
remove: function() {
this.stack.popView();
}.bind(this),
error: function() {
// TODO:
}
});
}
}
],
listeners: [
{
name: 'doBack',
framed: true,
code: function() { this.stack.popView(); }
}
],
methods: [
function initE() {
this.cls(this.myCls()).add(this.toolbar_).add(this.body_);
}
],
templates: [
function CSS() {/*
^ {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}
^body {
overflow-x: hidden;
overflow-y: auto;
}
*/}
]
});
|
jlhughes/foam
|
js/foam/u2/DAOUpdateController.js
|
JavaScript
|
apache-2.0
| 3,527
|
import { setPropertiesFromJSON } from '../../json-helper';
/**
* Generated class for shr.entity.LanguageQualifier.
*/
class LanguageQualifier {
/**
* Get the value (aliases codeableConcept).
* @returns {CodeableConcept} The shr.core.CodeableConcept
*/
get value() {
return this._codeableConcept;
}
/**
* Set the value (aliases codeableConcept).
* @param {CodeableConcept} value - The shr.core.CodeableConcept
*/
set value(value) {
this._codeableConcept = value;
}
/**
* Get the CodeableConcept.
* @returns {CodeableConcept} The shr.core.CodeableConcept
*/
get codeableConcept() {
return this._codeableConcept;
}
/**
* Set the CodeableConcept.
* @param {CodeableConcept} codeableConcept - The shr.core.CodeableConcept
*/
set codeableConcept(codeableConcept) {
this._codeableConcept = codeableConcept;
}
/**
* Deserializes JSON data to an instance of the LanguageQualifier class.
* The JSON must be valid against the LanguageQualifier JSON schema, although this is not validated by the function.
* @param {object} json - the JSON data to deserialize
* @returns {LanguageQualifier} An instance of LanguageQualifier populated with the JSON data
*/
static fromJSON(json={}) {
const inst = new LanguageQualifier();
setPropertiesFromJSON(inst, json);
return inst;
}
}
export default LanguageQualifier;
|
standardhealth/flux
|
src/model/shr/entity/LanguageQualifier.js
|
JavaScript
|
apache-2.0
| 1,412
|
export default function updateEntityChart (actionContext, payload, done) {
actionContext.dispatch('UPDATE_ENTITY_CHART');
done();
}
|
ecesena/oscars2016
|
www/src/javascript/actions/updateEntityChart.js
|
JavaScript
|
apache-2.0
| 141
|
/* @flow */
import Locale from './locale'
import defaultLocale from './locale/default'
import Router from './router'
import createError from './createError'
import Token from './token'
import User from './user'
import Application from './application'
import Role from './role'
import Authorize from './authorize'
import Verification from './verification'
import Message from './message'
export {
Router,
Locale,
defaultLocale,
createError,
Token,
User,
Application,
Role,
Authorize,
Verification,
Message,
}
if (module.hot) {
module.hot.accept()
}
|
lian-yue/accounts
|
app/models/index.js
|
JavaScript
|
apache-2.0
| 574
|
function NavbarController($scope, $location, $timeout, AlertService, SettingsService) {
$scope.settings_service = SettingsService;
$scope.new_refresh = $scope.settings_service.getRefreshInterval();
$scope.connectToHost=function(event) {
if (event.keyCode == 13) {
if (isDefined($scope.new_host) && $scope.new_host.length > 0) {
$scope.setHost($scope.new_host);
$scope.refreshClusterState();
}
}
};
$scope.changeRefresh=function() {
$scope.settings_service.setRefreshInterval($scope.new_refresh);
};
}
|
fhuitfeldt/logstash-cartridge
|
elasticsearch-1.1.0/plugins/kopf/_site/src/kopf/controllers/navbar.js
|
JavaScript
|
apache-2.0
| 538
|
'use strict';
/*
* Generic require login routing middleware
*/
exports.requiresLogin = function (req, res, next) {
if (req.isAuthenticated()) return next();
if (req.method == 'GET') req.session.returnTo = req.originalUrl;
console.log('not authorized');
res.status(401);
res.send();
};
/*
* User authorization routing middleware
*/
exports.user = {
hasAuthorization: function (req, res, next) {
if (req.profile.id != req.user.id) {
req.flash('info', 'You are not authorized');
return res.redirect('/users/' + req.profile.id);
}
next();
}
};
/*
* Article authorization routing middleware
*/
exports.article = {
hasAuthorization: function (req, res, next) {
if (req.article.user.id != req.user.id) {
req.flash('info', 'You are not authorized');
return res.redirect('/articles/' + req.article.id);
}
next();
}
};
/**
* Comment authorization routing middleware
*/
exports.comment = {
hasAuthorization: function (req, res, next) {
// if the current user is comment owner or article owner
// give them authority to delete
if (req.user.id === req.comment.user.id || req.user.id === req.article.user.id) {
next();
} else {
req.flash('info', 'You are not authorized');
res.redirect('/articles/' + req.article.id);
}
}
};
|
muhammad-saleh/weightlyio
|
server/config/middlewares/authorization.js
|
JavaScript
|
apache-2.0
| 1,446
|
/*
* Copyright 2017 Alexander Pustovalov
*
* 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 { createStructuredSelector } from 'reselect';
export const modelSelector = createStructuredSelector({
componentModel: state => state.pageListControls,
deskPageModel: state => state.deskPage,
deskModel: state => state.desk
});
|
ipselon/structor
|
src-client/modules/workspace/containers/PageListControls/selectors.js
|
JavaScript
|
apache-2.0
| 844
|
var filterSongBySinger = filterModule.filter('filterSongBySinger', function () {
return function (songs, singer) {
if (singer == null || singer === '' || singer.id == -1)
return songs;
var filtered = _.reduce(songs, function (filteredList, song) {
if (_.findWhere(song.searchableCriteria.singers, {id: singer.id}) != null)
filteredList.push(song);
return filteredList;
}, []);
return filtered;
};
});
|
AjabShahar/Ajab-Shahar-TW
|
web/app/user/js/common/filters/filterSongBySinger.js
|
JavaScript
|
apache-2.0
| 495
|
function pageTextClosure() {
var root = $('#pageContent');
$.getJSON('/services/pagetext').done(function(data) {
var lines = data.pageText || [];
$.each(lines, function(index, line) {
var paragraph = $('<p/>');
paragraph.text(line);
root.append(paragraph);
});
}).fail(function(jqXHR, status, errorText) {
var paragraph = $('<p/>');
paragraph.addClass('error');
paragraph.text(errorText);
});
}
|
mdcarlson/cloud-launch-demo-stackato
|
src/main/webapp/js/pagetext.js
|
JavaScript
|
apache-2.0
| 431
|
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.id');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Tambahkan Komentar";
Blockly.Msg.CHANGE_VALUE_TITLE = "Ubah nilai:";
Blockly.Msg.CLEAN_UP = "Bersihkan Blok";
Blockly.Msg.COLLAPSE_ALL = "Ciutkan Blok";
Blockly.Msg.COLLAPSE_BLOCK = "Ciutkan Blok";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "warna 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "warna 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/";
Blockly.Msg.COLOUR_BLEND_RATIO = "rasio";
Blockly.Msg.COLOUR_BLEND_TITLE = "campur";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Campur dua warna secara bersamaan dengan perbandingan (0.0 - 1.0).";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/Color";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Pilih warna dari daftar warna.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "Warna acak";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Pilih warna secara acak.";
Blockly.Msg.COLOUR_RGB_BLUE = "biru";
Blockly.Msg.COLOUR_RGB_GREEN = "hijau";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "merah";
Blockly.Msg.COLOUR_RGB_TITLE = "Dengan warna";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Buatlah warna dengan jumlah yang ditentukan dari merah, hijau dan biru. Semua nilai harus antarai 0 sampai 100.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "keluar dari perulangan";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "lanjutkan dengan langkah perulangan berikutnya";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Keluar dari perulangan.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Abaikan sisa dari perulangan ini, dan lanjutkan dengan langkah berikutnya.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Peringatan: Blok ini hanya dapat digunakan dalam perulangan.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_TITLE = "untuk setiap item %1 di dalam list %2";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Untuk tiap-tiap item di dalam list, tetapkan variabel '%1' ke dalam item, selanjutnya kerjakan beberapa statement.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_TITLE = "Cacah dengan %1 dari %2 ke %3 dengan step / penambahan %4";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Menggunakan variabel \"%1\" dengan mengambil nilai dari batas awal hingga ke batas akhir, dengan interval tertentu, dan mengerjakan block tertentu.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Tambahkan prasyarat ke dalam blok IF.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Terakhir, tambahkan kondisi tangkap-semua kedalam blok IF.";
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Tambahkan, hapus, atau susun kembali bagian untuk mengkonfigurasi blok IF ini.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "lainnya";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "atau jika";
Blockly.Msg.CONTROLS_IF_MSG_IF = "jika";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Jika nilainya benar, maka lakukan beberapa perintah.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Jika nilainya benar, maka kerjakan perintah blok pertama. Jika tidak, kerjakan perintah blok kedua.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Jika nilai pertama benar, maka kerjakan perintah blok pertama. Sebaliknya, jika nilai kedua benar, kerjakan perintah blok kedua.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Jika nilai pertama benar, maka kerjakan perintah blok pertama. Sebaliknya, jika nilai kedua benar, kerjakan perintah blok kedua. Jika dua-duanya tidak benar, kerjakan perintah blok terakhir.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://en.wikipedia.org/wiki/For_loop";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "kerjakan";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "ulangi %1 kali";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Lakukan beberapa perintah beberapa kali.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "ulangi sampai";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "ulangi jika";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Selagi nilainya salah, maka lakukan beberapa perintah.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Selagi nilainya benar, maka lakukan beberapa perintah.";
Blockly.Msg.DELETE_ALL_BLOCKS = "Hapus semua %1 blok?";
Blockly.Msg.DELETE_BLOCK = "Hapus Blok";
Blockly.Msg.DELETE_VARIABLE = "Hapus variabel '%1'";
Blockly.Msg.DELETE_VARIABLE_CONFIRMATION = "Hapus %1 yang digunakan pada variabel '%2'?";
Blockly.Msg.DELETE_X_BLOCKS = "Hapus %1 Blok";
Blockly.Msg.DICTS_CREATE_EMPTY_TITLE = "empty dictionary"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_CONTAINER_TITLE_ADD = "Create Dictionary"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_CONTAINER_TOOLTIP = ""; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_INPUT_WITH = "create dict with"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_KEY = "key"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_MAPPING = ":"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_TITLE = "key/value"; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_ITEM_TOOLTIP = ""; // untranslated
Blockly.Msg.DICTS_CREATE_WITH_TOOLTIP = ""; // untranslated
Blockly.Msg.DICT_GET = "get key"; // untranslated
Blockly.Msg.DICT_GET_TO = "of"; // untranslated
Blockly.Msg.DICT_KEYS = "get all keys from"; // untranslated
Blockly.Msg.DISABLE_BLOCK = "Nonaktifkan Blok";
Blockly.Msg.DUPLICATE_BLOCK = "Duplikat";
Blockly.Msg.ENABLE_BLOCK = "Aktifkan Blok";
Blockly.Msg.EXPAND_ALL = "Kembangkan Blok";
Blockly.Msg.EXPAND_BLOCK = "Kembangkan Blok";
Blockly.Msg.EXTERNAL_INPUTS = "Input Eksternal";
Blockly.Msg.HELP = "Bantuan";
Blockly.Msg.INLINE_INPUTS = "Input Inline";
Blockly.Msg.LISTS_APPEND = "append item"; // untranslated
Blockly.Msg.LISTS_APPEND_HELPURL = "http://google.com"; // untranslated
Blockly.Msg.LISTS_APPEND_TO = "to list"; // untranslated
Blockly.Msg.LISTS_APPEND_TOOLTIP = "Append an element to a list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list";
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "buat list kosong";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Kembalikan list, dengan panjang 0, tidak berisi data";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "list";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Tambahkan, hapus, atau susun ulang bagian untuk mengkonfigurasi blok list ini.";
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "buat list dengan";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Tambahkan sebuah item ke list.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Buat sebuah list dengan sejumlah item.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "pertama";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# dari akhir";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#";
Blockly.Msg.LISTS_GET_INDEX_GET = "dapatkan";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "dapatkan dan hapus";
Blockly.Msg.LISTS_GET_INDEX_LAST = "terakhir";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "acak";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "Hapus";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Kembalikan item pertama dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM = "Kembalikan item di posisi tertentu dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Kembalikan item terakhir dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Kembalikan item acak dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Hapus dan kembalikan item pertama dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM = "Hapus dan kembalikan item di posisi tertentu dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Hapus dan kembalikan item terakhir dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Hapus dan kembalikan item acak dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Hapus item pertama dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM = "Hapus item di posisi tertentu dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Hapus item terakhir dalam list.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Hapus sebuah item acak dalam list.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "ke # dari akhir";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "ke #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "ke yang paling akhir";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "dapatkan sub-list dari pertama";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "dapatkan sub-list dari nomor # dari akhir";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "dapatkan sub-list dari #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Buat salinan bagian tertentu dari list.";
Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP = "%1 adalah item terakhir.";
Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP = "%1 adalah item pertama.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "cari kejadian pertama item";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "cari kejadian terakhir item";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Kembalikan indeks dari item pertama/terakhir kali muncul dalam list. Kembalikan %1 jika item tidak ditemukan.";
Blockly.Msg.LISTS_INLIST = "dalam list";
Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 kosong";
Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "Kembalikan benar jika list kosong.";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "panjang dari %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Kembalikan panjang list.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "buat list dengan item %1 diulang %2 kali";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Buat sebuah list yang terdiri dari nilai yang diberikan diulang sebanyak jumlah yang ditentukan.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "sebagai";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "sisipkan di";
Blockly.Msg.LISTS_SET_INDEX_SET = "tetapkan";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Sisipkan item di bagian awal dari list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM = "Sisipkan item ke dalam posisi yang telah ditentukan di dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Tambahkan item ke bagian akhir list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Sisipkan item secara acak ke dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Tetapkan item pertama di dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM = "Tetapkan item ke dalam posisi yang telah ditentukan di dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Menetapkan item terakhir dalam list.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Tetapkan secara acak sebuah item dalam list.";
Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list";
Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "menaik";
Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "menurun";
Blockly.Msg.LISTS_SORT_TITLE = "urutkan %1 %2 %3";
Blockly.Msg.LISTS_SORT_TOOLTIP = "Urutkan salinan dari daftar";
Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "sesuai abjad, abaikan kasus";
Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "sesuai nomor";
Blockly.Msg.LISTS_SORT_TYPE_TEXT = "sesuai abjad";
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "buat list dari teks";
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "buat teks dari list";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Gabung daftar teks menjadi satu teks, yang dipisahkan oleh pembatas.";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Membagi teks ke dalam daftar teks, pisahkan pada setiap pembatas.";
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "dengan pembatas";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "salah";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Kembalikan benar atau salah.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "benar";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://en.wikipedia.org/wiki/Inequality_(mathematics)";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Kembalikan benar jika kedua input sama satu dengan lainnya.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Kembalikan benar jika input pertama lebih besar dari input kedua.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Kembalikan benar jika input pertama lebih besar dari atau sama dengan input kedua.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Kembalikan benar jika input pertama lebih kecil dari input kedua.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Kembalikan benar jika input pertama lebih kecil atau sama dengan input kedua .";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Kembalikan benar jika kedua input tidak sama satu dengan lainnya.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "bukan (not) %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Kembalikan benar jika input salah. Kembalikan salah jika input benar.";
Blockly.Msg.LOGIC_NULL = "null";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type";
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Kembalikan null.";
Blockly.Msg.LOGIC_OPERATION_AND = "dan";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "atau";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Kembalikan benar jika kedua input adalah benar.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Kembalikan benar jika minimal satu input nilainya benar.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "test";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:";
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "jika salah";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "jika benar";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Periksa kondisi di 'test'. Jika kondisi benar, kembalikan nilai 'if true'; jika sebaliknya kembalikan nilai 'if false'.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+";
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://id.wikipedia.org/wiki/Aritmetika";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Kembalikan jumlah dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Kembalikan hasil bagi dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Kembalikan selisih dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Kembalikan perkalian dari kedua angka.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Kembalikan angka pertama pangkat angka kedua.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter";
Blockly.Msg.MATH_CHANGE_TITLE = "ubah %1 oleh %2";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Tambahkan angka kedalam variabel '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Kembalikan salah satu konstanta: π (3,141…), e (2,718…), φ (1,618…), akar(2) (1,414…), akar(½) (0.707…), atau ∞ (tak terhingga).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "Batasi %1 rendah %2 tinggi %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Batasi angka antara batas yang ditentukan (inklusif).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷";
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "dapat dibagi oleh";
Blockly.Msg.MATH_IS_EVEN = "adalah bilangan genap";
Blockly.Msg.MATH_IS_NEGATIVE = "adalah bilangan negatif";
Blockly.Msg.MATH_IS_ODD = "adalah bilangan ganjil";
Blockly.Msg.MATH_IS_POSITIVE = "adalah bilangan positif";
Blockly.Msg.MATH_IS_PRIME = "adalah bilangan pokok";
Blockly.Msg.MATH_IS_TOOLTIP = "Periksa apakah angka adalah bilangan genap, bilangan ganjil, bilangan pokok, bilangan bulat, bilangan positif, bilangan negatif, atau apakan bisa dibagi oleh angka tertentu. Kembalikan benar atau salah.";
Blockly.Msg.MATH_IS_WHOLE = "adalah bilangan bulat";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation";
Blockly.Msg.MATH_MODULO_TITLE = "sisa dari %1 ÷ %2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "Kembalikan sisa dari pembagian ke dua angka.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×";
Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Suatu angka.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "rata-rata dari list";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "maksimum dari list";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "median dari list";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "minimum dari list";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "mode-mode dari list";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "item acak dari list";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "deviasi standar dari list";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "jumlah dari list";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Kembalikan rata-rata (mean aritmetik) dari nilai numerik dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Kembalikan angka terbesar dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Kembalikan median dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Kembalikan angka terkecil dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Kembalikan list berisi item yang paling umum dari dalam list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Kembalikan elemen acak dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Kembalikan standard deviasi dari list.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Kembalikan jumlah dari seluruh bilangan dari list.";
Blockly.Msg.MATH_POWER_SYMBOL = "^";
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "nilai pecahan acak";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Kembalikan nilai pecahan acak antara 0.0 (inklusif) dan 1.0 (eksklusif).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "acak bulat dari %1 sampai %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Kembalikan bilangan acak antara dua batas yang ditentukan, inklusif.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "membulatkan";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "membulatkan kebawah";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "membulatkan keatas";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Bulatkan suatu bilangan naik atau turun.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "mutlak";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "akar";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Kembalikan nilai absolut angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Kembalikan 10 pangkat angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Kembalikan logaritma natural dari angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Kembalikan dasar logaritma 10 dari angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Kembalikan penyangkalan terhadap angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Kembalikan 10 pangkat angka.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Kembalikan akar dari angka.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-";
Blockly.Msg.MATH_TRIG_ACOS = "acos";
Blockly.Msg.MATH_TRIG_ASIN = "asin";
Blockly.Msg.MATH_TRIG_ATAN = "atan";
Blockly.Msg.MATH_TRIG_COS = "cos";
Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions";
Blockly.Msg.MATH_TRIG_SIN = "sin";
Blockly.Msg.MATH_TRIG_TAN = "tan";
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Kembalikan acosine dari angka.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Kembalikan asin dari angka.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Kembalikan atan dari angka.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Kembalikan cosinus dari derajat (bukan radian).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Kembalikan sinus dari derajat (bukan radian).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Kembalikan tangen dari derajat (bukan radian).";
Blockly.Msg.NEW_VARIABLE = "Buat variabel...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Nama variabel baru:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "memungkinkan pernyataan";
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "dengan:";
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Menjalankan fungsi '%1' yang ditetapkan pengguna.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Menjalankan fungsi '%1' yang ditetapkan pengguna dan menggunakan outputnya.";
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "dengan:";
Blockly.Msg.PROCEDURES_CREATE_DO = "Buat '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Jelaskan fungsi ini...";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "buat sesuatu";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "untuk";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Buat sebuah fungsi tanpa output.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "kembali";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Buat sebuah fungsi dengan satu output.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Peringatan: Fungsi ini memiliki parameter duplikat.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Sorot definisi fungsi";
Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause"; // untranslated
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Jika nilai yang benar, kemudian kembalikan nilai kedua.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Peringatan: Blok ini dapat digunakan hanya dalam definisi fungsi.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "masukan Nama:";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Tambahkan masukan ke fungsi.";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "input";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Menambah, menghapus, atau menyusun ulang masukan untuk fungsi ini.";
Blockly.Msg.REDO = "Lakukan ulang";
Blockly.Msg.REMOVE_COMMENT = "Hapus Komentar";
Blockly.Msg.RENAME_VARIABLE = "Ubah nama variabel...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Ubah nama semua variabel '%1' menjadi:";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "tambahkan teks";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "untuk";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Tambahkan beberapa teks ke variabel '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "menjadi huruf kecil";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "menjadi huruf pertama kapital";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "menjadi huruf kapital";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Kembalikan kopi dari text dengan kapitalisasi yang berbeda.";
Blockly.Msg.TEXT_CHARAT_FIRST = "ambil huruf pertama";
Blockly.Msg.TEXT_CHARAT_FROM_END = "ambil huruf nomor # dari belakang";
Blockly.Msg.TEXT_CHARAT_FROM_START = "ambil huruf ke #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "dalam teks";
Blockly.Msg.TEXT_CHARAT_LAST = "ambil huruf terakhir";
Blockly.Msg.TEXT_CHARAT_RANDOM = "ambil huruf secara acak";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Kembalikan karakter dari posisi tertentu.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Tambahkan suatu item ke dalam teks.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "join";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Tambah, ambil, atau susun ulang teks blok.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "pada huruf nomer # dari terakhir";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "pada huruf #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "pada huruf terakhir";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "in teks";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "ambil bagian teks (substring) dari huruf pertama";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "ambil bagian teks (substring) dari huruf ke # dari terakhir";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "ambil bagian teks (substring) dari huruf no #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Kembalikan spesifik bagian dari teks.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "dalam teks";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "temukan kejadian pertama dalam teks";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "temukan kejadian terakhir dalam teks";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Kembalikan indeks pertama dan terakhir dari kejadian pertama/terakhir dari teks pertama dalam teks kedua. Kembalikan %1 jika teks tidak ditemukan.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 kosong";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Kembalikan benar jika teks yang disediakan kosong.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "buat teks dengan";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Buat teks dengan cara gabungkan sejumlah item.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "panjang dari %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Kembalikan sejumlah huruf (termasuk spasi) dari teks yang disediakan.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "cetak %1";
Blockly.Msg.TEXT_PRINT_TITLE_PRINT = "print"; // untranslated
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Cetak teks yant ditentukan, angka atau ninlai lainnya.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Meminta pengguna untuk memberi sebuah angka.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Meminta pengguna untuk memberi beberapa teks.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "Meminta angka dengan pesan";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "meminta teks dengan pesan";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Huruf, kata atau baris teks.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "pangkas ruang dari kedua belah sisi";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "pangkas ruang dari sisi kiri";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "pangkas ruang dari sisi kanan";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Kembali salinan teks dengan spasi dihapus dari satu atau kedua ujungnya.";
Blockly.Msg.TODAY = "Hari ini";
Blockly.Msg.TYPE_CHECK = "type of"; // untranslated
Blockly.Msg.UNDO = "Urungkan";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "item";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Buat 'set %1'";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Kembalikan nilai variabel ini.";
Blockly.Msg.VARIABLES_SET = "tetapkan %1 untuk %2";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Buat 'get %1'";
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TAIL = "="; // untranslated
Blockly.Msg.VARIABLES_SET_TITLE = "set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "tetapkan variabel ini dengan input yang sama.";
Blockly.Msg.VARIABLE_ALREADY_EXISTS = "Sebuah variabel dengan nama '%1' sudah ada.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT;
|
RealTimeWeb/blockly
|
msg/js/id.js
|
JavaScript
|
apache-2.0
| 31,453
|
module.exports = {
username: function (str) {
return typeof str === 'string' && str.length >= 6 && str.length <= 12 && str.indexOf(' ') === -1
},
password: function (str) {
return typeof str === 'string' && str.length >= 8
},
poll: function (obj) {
return obj.title.length > 6 && obj.title.length < 250 && obj.options.length >= 2
}
}
|
mubaidr/Voting-App
|
api/models/validators.js
|
JavaScript
|
apache-2.0
| 358
|
var searchData=
[
['accrange',['AccRange',['../group__acc.html#ga3d56e56c162b045de727006a11880324',1,'acc.h']]],
['adcref',['ADCRef',['../group__adc.html#ga7fc3dc0de11790b4393b4be70d79a02f',1,'adc.h']]]
];
|
xythobuz/xyControl
|
doc/html/search/enums_61.js
|
JavaScript
|
bsd-2-clause
| 210
|
(function() {
var FieldOperator, NamingRule, QueryContext, RelationFieldOperator, SelectQuery, ToOneRelation, Utils, _, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_ref = require('./../utils'), _ = _ref._, Utils = _ref.Utils;
FieldOperator = require('../query/FieldOperator');
QueryContext = require('../query/QueryContext');
SelectQuery = require('../query/SelectQuery');
NamingRule = require('./NamingRule');
ToOneRelation = (function() {
function ToOneRelation($source, $target, options) {
var f, name, rel, self, _i, _len, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6,
_this = this;
this.$source = $source;
this.$target = $target;
if (options == null) {
options = {};
}
this.$name = (_ref1 = options.as) != null ? _ref1 : this.$target.$name;
this.$alias = (_ref2 = options.alias) != null ? _ref2 : this.$name;
this.$targetKey = (_ref3 = options.keyOnTarget) != null ? _ref3 : this.$target.$primaryKey.columnName;
this.$foreignKey = this._getForeignKey(options);
this._targetKeyField = (function() {
var f, _i, _len, _ref4;
_ref4 = _this.$target.$fields;
for (_i = 0, _len = _ref4.length; _i < _len; _i++) {
f = _ref4[_i];
if (f.name === _this.$targetKey) {
return f;
}
}
})();
this._sourceAlias = (_ref4 = options.sourceAlias) != null ? _ref4 : this.$source.$tableName;
this._dependency = options.dependsOn;
self = this;
this._loader = this.$target.$compiledQuery(function() {
return this.where(self.$targetKey).eq(this.$('id'));
});
_ref5 = this.$target.$fields;
for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
f = _ref5[_i];
name = f.name === 'name' ? '_name' : f.name;
this[name] = new RelationFieldOperator(this, null, this.$alias, f.columnName);
}
_ref6 = this.$target.$toOneRelations;
for (name in _ref6) {
rel = _ref6[name];
this[rel.$name] = new ToOneRelation(rel.$source, rel.$target, {
as: rel.$name,
alias: this.$name + '_' + rel.$name,
sourceAlias: this.$alias,
foreignKey: rel.$foreignKey,
keyOnTarget: rel.$targetKey,
dependsOn: this
});
}
}
ToOneRelation.prototype._getForeignKey = function(options) {
var namingRule, prefix, suffix, _ref1;
if (options.foreignKey != null) {
return options.foreignKey;
} else {
prefix = this.$source.$options.columnNamingRule.toDatabase(this.$target.$name);
suffix = this.$targetKey.replace(prefix, '');
namingRule = (_ref1 = options.columnNamingRule) != null ? _ref1 : NamingRule.ColumnDefault;
return namingRule.toDatabase(this.$alias + ' ' + _.ltrim(suffix, '_'));
}
};
ToOneRelation.prototype._ensureQueryComponents = function(query) {
var _this = this;
query.select(new SelectQuery.SelectField(this._sourceAlias, this.$foreignKey));
if (this._dependency != null) {
this._dependency._ensureQueryComponents(query);
}
if (!_.any(query._leftJoin != null, function(j) {
return j.targetAlias === _this.$alias;
})) {
return query.leftJoin(this.$target.$tableName, this.$alias).on(this.$targetKey).eq(this._sourceAlias, this.$foreignKey);
}
};
ToOneRelation.prototype.__getSelectFields = function() {
var field;
return (function() {
var _i, _len, _ref1, _results;
_ref1 = this.$target.$fields;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
field = _ref1[_i];
_results.push(new SelectQuery.SelectField(this.$alias, field.columnName));
}
return _results;
}).call(this);
};
ToOneRelation.prototype._extractInstance = function(row) {
var fieldName, name, rel, values, _ref1;
if (row[this._sourceAlias + '.' + this.$foreignKey] == null) {
return null;
}
values = this.$target.$instanceFactory.readRow(row, this.$alias);
_ref1 = this.$target.$toOneRelations;
for (name in _ref1) {
rel = _ref1[name];
rel = this[name];
fieldName = rel.$source.$options.columnNamingRule.fromDatabase(rel.$name);
values[fieldName] = rel._extractInstance(row);
}
return new this.$target(values);
};
ToOneRelation.prototype._setLoader = function(instance) {
var fk,
_this = this;
fk = (function() {
var f, _i, _len, _ref1;
_ref1 = _this.$source.$fields;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
f = _ref1[_i];
if (f.columnName === _this.$foreignKey) {
return f;
}
}
})();
return instance['get' + this.$name] = function(callback) {
return _this._loader.execute({
id: instance[fk.name]
}, callback);
};
};
ToOneRelation.prototype.isNull = function() {
return this.eq(null);
};
ToOneRelation.prototype.isNotNull = function() {
return this.neq(null);
};
ToOneRelation.prototype.eq = function(value) {
if ((this._targetKeyField != null) && value instanceof this.$target) {
value = value[this._targetKeyField.name];
}
return QueryContext.current.where(this._sourceAlias, this.$foreignKey).eq(value);
};
ToOneRelation.prototype.neq = function(value) {
if ((this._targetKeyField != null) && value instanceof this.$target) {
value = value[this._targetKeyField.name];
}
return QueryContext.current.where(this._sourceAlias, this.$foreignKey).neq(value);
};
return ToOneRelation;
})();
RelationFieldOperator = (function(_super) {
__extends(RelationFieldOperator, _super);
function RelationFieldOperator(relation, queryContext, table, field) {
var base, method, name, _fn,
_this = this;
RelationFieldOperator.__super__.constructor.call(this, queryContext, table, field);
this.relation = relation;
base = {};
_fn = function(name, method) {
return _this[name] = function() {
_this.relation._ensureQueryComponents(_this.queryContext);
return base[name].apply(_this, arguments);
};
};
for (name in this) {
method = this[name];
if (!(_.isFunction(method) && name !== 'constructor' && name.indexOf('_' !== 0))) {
continue;
}
base[name] = method;
_fn(name, method);
}
}
return RelationFieldOperator;
})(FieldOperator);
module.exports = ToOneRelation;
}).call(this);
|
candril/tavola
|
lib/schema/ToOneRelation.js
|
JavaScript
|
bsd-2-clause
| 7,023
|
(function(module) {
"use strict";
var EmbedVideo = {},
//embed_vimeo = '<div class="embed-container"><iframe src="//player.vimeo.com/video/$1" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>',
embed_youtube = '<div class="embed-container"><iframe src="//www.youtube.com/embed/$1" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>',
//embed_facebook = '<div class="embed-container"><iframe src="https://www.facebook.com/video/embed?video_id=$1" width="640" height="360" frameborder="0" allowfullscreen ></iframe></div>',
//embed_dailymotion = '<div class="embed-container"><iframe src="http://www.dailymotion.com/embed/video/$1" width="640" height="360" frameborder="0" allowfullscreen></iframe></div>',
embed_vine = '<div class="video" style="width: 500px; height: 500px; overflow: hidden; position: relative;"><iframe frameborder="0" scrolling="no" seamless="seamless" webkitallowfullscreen="webkitAllowFullScreen" mozallowfullscreen="mozallowfullscreen" allowfullscreen="allowfullscreen" id="okplayer" width="500" height="500" src="https://vine.co/v/$1/card?mute=0" style="position: absolute; top: 0px; left: 0px; width: 500px; height: 500px;"></iframe></div>',
//embed_mixcloud = '<iframe src="https://www.mixcloud.com/widget/iframe/?embed_type=widget_standard&embed_uuid=ecd38451-4abc-4c37-85a9-065b45fd8850&feed=https%3A%2F%2Fwww.mixcloud.com%2F$1%2F$2%2F&hide_artwork=1&hide_cover=1&hide_tracklist=1&replace=0" width="" height="180" frameborder="0"></iframe>',
embed_spotify = '<iframe src="https://embed.spotify.com/?uri=spotify:artist:$1" width="300" height="380" frameborder="0" allowtransparency="true"></iframe>',
embed_spotify_track = '<iframe src="https://embed.spotify.com/?uri=spotify:track:$1" width="300" height="380" frameborder="0" allowtransparency="true"></iframe>',
embed_spotify_album = '<iframe src="https://embed.spotify.com/?uri=spotify:user:erebore:playlist:$1&theme=white&view=coverart" frameborder="0" allowtransparency="true"></iframe>',
embed_pinterest_pin = '<a data-pin-do="embedPin" href="http://de.pinterest.com/pin/$1/"></a><script type="text/javascript" async defer src="//assets.pinterest.com/js/pinit.js"></script>',
//embedUrl_vimeo = /<a href="(?:https?:\/\/)?(?:www\.)?(?:vimeo\.com\/)(?:\D*|).*(\w{9})<\/a>/g,
embedUrl_youtube = /<a href="http.?:.*(?:youtube.com\/|youtu.be\/)(?!channel)(?:watch\?v=|watch\?t=.*v=|embed\/|)(.*)<\/a>/g,
//embedUrl_facebook = /<a href="http.?:\/\/.+facebook.com\/\w+\.?\w+\/videos\/(\w+).*<\/a>/ig,
//embedUrl_dailymotion = /<a href="(?:https?:\/\/)?(?:www\.)dailymotion\.com\/video\/(.*)" .*<\/a>/g,
embedUrl_vine = /<a href="(?:https?:\/\/)?(?:vine\.co)\/\w*\/(\w*).*<\/a>/g,
//embedUrl_mixcloud = /<a href="http.?:\/\/?.*\.mixcloud\.com\/(\w*)\/(.*)?\/<\/a>/g,
embedUrl_spotify = /<a href="http.?:.*play.spotify.com\/artist\/(.*)<\/a>/g,
embedUrl_spotify_track = /<a href="http.?:.*play.spotify.com\/track\/(.*)<\/a>/g,
embedUrl_spotify_album = /<a href="http.?:.*play.spotify.com\/album\/(.*)<\/a>/g,
embedUrl_pinterest_pin = /<a href="http.?:.*pinterest.com\/pin\/(\w*).*<\/a>/g;
EmbedVideo.parse = function(data, callback) {
if (!data || !data.postData || !data.postData.content) {
return callback(null, data);
}
/*if (data.postData.content.match(embedUrl_vimeo)) {
data.postData.content = data.postData.content.replace(embedUrl_vimeo, embed_vimeo);
} else */if (data.postData.content.match(embedUrl_youtube)) {
data.postData.content = data.postData.content.replace(embedUrl_youtube, embed_youtube);
}/* else if (data.postData.content.match(embedUrl_facebook)) {
data.postData.content = data.postData.content.replace(embedUrl_facebook, embed_facebook);
} else if (data.postData.content.match(embedUrl_dailymotion)) {
data.postData.content = data.postData.content.replace(embedUrl_dailymotion, embed_dailymotion);
}*/ else if (data.postData.content.match(embedUrl_vine)) {
data.postData.content = data.postData.content.replace(embedUrl_vine, embed_vine);
}/* else if (data.postData.content.match(embedUrl_mixcloud)) {
data.postData.content = data.postData.content.replace(embedUrl_mixcloud, embed_mixcloud);
}*/ else if (data.postData.content.match(embedUrl_spotify)) {
data.postData.content = data.postData.content.replace(embedUrl_spotify, embed_spotify);
} else if (data.postData.content.match(embedUrl_spotify_track)) {
data.postData.content = data.postData.content.replace(embedUrl_spotify_track, embed_spotify_track);
} else if (data.postData.content.match(embedUrl_spotify_album)) {
data.postData.content = data.postData.content.replace(embedUrl_spotify_album, embed_spotify_album);
} else if (data.postData.content.match(embedUrl_pinterest_pin)) {
data.postData.content = data.postData.content.replace(embedUrl_pinterest_pin, embed_pinterest_pin);
}
callback(null, data);
};
module.exports = EmbedVideo;
}(module));
|
Linux-statt-Windows/nodebb-plugin-embed-videos
|
library.js
|
JavaScript
|
bsd-2-clause
| 5,530
|
const fs = require('fs');
const ESCAPE_SEQUENCE = {
'\\': '\\\\',
'\n': '\\n',
'\t': '\\t'
};
function js_escape(s) {
return s.split('').map(function(c) {
return ESCAPE_SEQUENCE[c] || c;
}).join('');
}
function glsl_compress(s, shortNames) {
// strip leading whitespace
s = s.replace(/^\s+/g, '');
// strip trailing whitespace
s = s.replace(/\s+$/g, '');
// strip multi-line comments
s = s.replace(/\/\*[\s\S]*?\*\//g, '');
// strip single line comments
s = s.replace(/\/\/.*?\n/, '');
// replace multiple whitespace with a single space
s = s.replace(/\s+/g, ' ');
// remove whitespace between non-word tokens
s = s.replace(/(\S)\s+([^\w])/g, '$1$2')
.replace(/([^\w])\s+(\S)/g, '$1$2');
// replace original names with short names
for (const originalName in shortNames) {
s = s.replace(new RegExp(originalName, 'gm'), shortNames[originalName]);
}
return s;
}
function main(argv) {
const options = {};
for (let i = 2, ii = argv.length; i < ii; i += 2) {
options[argv[i].replace(/^../, '')] = argv[i + 1];
}
if (!options.input) {
process.stdout.write('--input option missing\n');
return 1;
}
const json = {};
let nextShortName = 'a'.charCodeAt(0);
const shortNames = {};
const attributes = {};
const uniforms = {};
const varyings = {};
const blocks = {
common: '',
vertex: '',
fragment: ''
};
let block = undefined;
const inFile = fs.readFileSync(options.input, 'utf-8');
const lines = inFile.split('\n');
let m, shortName;
lines.forEach(function(line, i) {
if (line.indexOf('//!') == 0) {
m = line.match(/\/\/!\s+NAMESPACE=(\S+)\s*$/);
if (m) {
json.namespace = m[1];
return;
}
m = line.match(/\/\/!\s+COMMON\s*$/);
if (m) {
block = 'common';
return;
}
m = line.match(/\/\/!\s+VERTEX\s*$/);
if (m) {
block = 'vertex';
return;
}
m = line.match(/\/\/!\s+FRAGMENT\s*$/);
if (m) {
block = 'fragment';
return;
}
} else {
if (block === undefined) {
if (line.replace(/\s+$/g, '') != '') {
process.stdout.write(`Error parsing ${options.input}\n`);
return;
}
} else {
blocks[block] += line + (i == lines.length - 1 ? '' : '\n');
}
m = line.match(/attribute\s+\S+\s+(\S+);\s*$/);
if (m) {
const attribute = m[1];
if (!(attribute in attributes)) {
shortName = String.fromCharCode(nextShortName++);
attributes[attribute] = {
originalName: attribute,
shortName: shortName
};
shortNames[attribute] = shortName;
}
}
m = line.match(/uniform\s+\S+\s+(\S+);\s*$/);
if (m) {
const uniform = m[1];
if (!(uniform in uniforms)) {
shortName = String.fromCharCode(nextShortName++);
uniforms[uniform] = {
originalName: uniform,
shortName: shortName
};
shortNames[uniform] = shortName;
}
}
m = line.match(/varying\s+\S+\s+(\S+);\s*$/);
if (m) {
const varying = m[1];
if (!(varying in varyings)) {
shortName = String.fromCharCode(nextShortName++);
shortNames[varying] = shortName;
}
}
}
});
json.originalFragmentSource = js_escape(blocks.common + blocks.fragment);
json.originalVertexSource = js_escape(blocks.common + blocks.vertex);
json.fragmentSource = glsl_compress(blocks.common + blocks.fragment, shortNames);
json.vertexSource = glsl_compress(blocks.common + blocks.vertex, shortNames);
json.attributes = Object.keys(attributes).map(a => attributes[a]);
json.uniforms = Object.keys(uniforms).map(u => uniforms[u]);
if (options.output && options.output != '-') {
fs.writeFileSync(options.output, JSON.stringify(json));
} else {
process.stdout.write(JSON.stringify(json));
}
return 0;
}
if (require.main === module) {
process.exit(main(process.argv));
}
|
planetlabs/ol3
|
tasks/glslunit.js
|
JavaScript
|
bsd-2-clause
| 4,072
|
define('html!test.Child', ['doT'], function(doT){
var markup = '<div class="test-Child"><ul>{{ for(var i = 0, l = it.list.length; i < l; i++){ }}<li>{{=it.list[i]}}</li>{{}}}</ul></div>';
return doT.template(markup);
});
define('js!test.Child', ['js!BaseComponent', 'html!test.Child'], function(BaseComponent, dotTplFn){
return BaseComponent.extend({
_dotTplFn: dotTplFn,
getElemCount: function(){
return this._container.getElementsByTagName('li').length;
},
getList: function(){
return this._options.list;
},
callFn: function(){
return this._options.fn();
}
});
});
define('html!test.Parent', ['doT'], function(doT){
var markup = '<div class="test-Parent"><component data-component="test.Child" name="child"><list:ref>{{@it.list}}</list><fn:ref>{{@it.fn}}</fn></component></div>';
return doT.template(markup);
});
define('js!test.Parent', ['js!CompoundComponent', 'html!test.Parent', 'js!test.Child'], function(CompoundComponent, dotTplFn){
return CompoundComponent.extend({
_dotTplFn: dotTplFn,
getChild: function(){
return this._components['child'];
}
});
});
define(['js!test.Parent'], function(Parent){
describe('useParentOptions', function(){
it('simple', function(){
var
list = [1,2,3,4,5,6,7,8,9],
parent = new Parent({
list : list
}),
child = parent.getChild();
expect(child.getList()).toEqual(list);
expect(child.getElemCount()).toEqual(list.length);
});
it('fn', function(){
var
list = [],
fn = function(){
return 42;
};
var parent = new Parent({
list : list,
fn : fn
}),
child = parent.getChild();
expect(child.callFn()).toEqual(42);
});
});
});
|
ershov-konst/sailfish
|
test/specs/useParentOptionsSpec.js
|
JavaScript
|
bsd-2-clause
| 1,935
|
// basic stream
function InputStream(text) {
this.pos = 0;
this.line = 0;
this.col = 0;
this.text = text;
this.len = text.length;
};
InputStream.prototype = {
peek: function() {
if (this.pos < this.len)
return this.text.charAt(this.pos);
return null;
},
next: function() {
if (this.pos < this.len) {
var ch = this.text.charAt(this.pos++);
if (ch == "\n") {
++this.line;
this.col = 0;
} else {
++this.col;
}
return ch;
}
return null;
}
};
////////////////// basic parser
function lisp_reader(code) {
var input = new InputStream(code);
var list = LispCons.fromArray;
function next() { return input.next(); };
function peek() { return input.peek(); };
function croak(msg) {
throw new Error(msg
+ " / line: " + input.line
+ ", col: " + input.col
+ ", pos: " + input.pos);
};
function read_while(pred) {
var buf = "", ch;
while ((ch = peek()) && pred(ch)) {
buf += next();
}
return buf;
};
function skip_ws() {
read_while(function(ch){
switch (ch) {
case " ":
case "\n":
case "\t":
case "\x0C":
case "\u2028":
case "\u2029":
case "\xA0":
return true;
}
});
};
function skip(expected) {
if (next() != expected)
croak("Expecting " + expected);
};
function read_escaped(start, end, inces) {
skip(start);
var escaped = false;
var str = "";
while (peek()) {
var ch = next();
if (escaped) {
str += ch;
escaped = false;
} else if (ch == "\\") {
if (inces) str += ch;
escaped = true;
} else if (ch == end) {
break;
} else {
str += ch;
}
}
return str;
};
function read_string() {
return read_escaped("\"", "\"");
};
function read_regexp() {
var str = read_escaped("/", "/", true);
var mods = read_while(function(ch){
switch (ch.toLowerCase()) {
case "y":
case "m":
case "g":
case "i":
return true;
}
}).toLowerCase();
return new RegExp(str, mods);
};
function skip_comment() {
read_while(function(ch){ return ch && ch != "\n" });
};
function read_symbol() {
var str = read_while(function(ch){
if (UNICODE.letter.test(ch) ||
(ch >= "0" && ch <= "9"))
return true;
switch (ch) {
case "%": case "$": case "_": case "-":
case ":": case ".": case "+": case "*":
case "@": case "!": case "?": case "&":
case "=": case "<": case ">":
case "[": case "]":
case "{": case "}":
case "/":
return true;
}
});
if (str.length > 0 && /^-?[0-9]*\.?[0-9]*$/.test(str)) {
var ret = parseFloat(str);
if (!isNaN(ret)) return ret;
}
str = str.toUpperCase();
var m = /^(.*?)::?(.*)$/.exec(str);
if (m) {
var pak = LispPackage.get(m[1] || "KEYWORD");
return pak.find_or_intern(m[2]);
}
var pak = LispPackage.get("%").intern("*PACKAGE*");
if (pak.value) return pak.value.find_or_intern(str);
return LispSymbol.get(str);
};
function read_char() {
var ch = next() + read_while(function(ch){
return (ch >= "a" && ch <= "z") ||
(ch >= "A" && ch <= "z") ||
(ch >= "0" && ch <= "9") ||
ch == "-" || ch == "_";
});
if (ch.length > 1) {
if (/^U[0-9a-f]{4}$/i.test(ch)) {
ch = LispChar.fromCode(parseInt(ch.substr(1), 16));
} else {
ch = LispChar.fromName(ch);
if (ch == null)
croak("Unknown character name: " + ch);
}
return ch;
}
return LispChar.get(ch);
};
function read_sharp() {
skip("#");
switch (peek()) {
case "\\": next(); return read_char();
case "/": return read_regexp();
case "(": return new LispCons(LispSymbol.get("VECTOR"), read_list());
case "'": next(); return LispCons.fromArray([ LispSymbol.get("FUNCTION"), read_token() ]);
default:
croak("Unsupported sharp syntax: #" + peek());
}
};
function read_quote() {
skip("'");
return list([ LispSymbol.get("QUOTE"), read_token() ]);
};
var in_qq = 0;
function read_quasiquote() {
skip("`");
skip_ws();
// if (peek() != "(")
// return list([ LispSymbol.get("QUOTE"), read_token() ]);
++in_qq;
var ret = list([ LispSymbol.get("QUASIQUOTE"), read_token() ]);
--in_qq;
return ret;
};
function read_comma() {
if (in_qq == 0) croak("Comma outside quasiquote");
skip(",");
skip_ws();
var ret;
--in_qq;
if (peek() == "@") {
next();
ret = list([ LispSymbol.get("QQ-SPLICE"), read_token() ]);
}
else ret = list([ LispSymbol.get("QQ-UNQUOTE"), read_token() ]);
++in_qq;
return ret;
};
function read_token() {
out: while (true) {
skip_ws();
switch (peek()) {
case ";" : skip_comment(); continue out;
case "\"" : return read_string();
case "(" : return read_list();
case "#" : return read_sharp();
case "`" : return read_quasiquote();
case "," : return read_comma();
case "'" : return read_quote();
case null : return false; // EOF
}
return read_symbol();
}
};
function read_list() {
var ret = null, p;
skip("(");
out: while (true) {
skip_ws();
switch (peek()) {
case ")": break out;
case null: break out;
case ";": skip_comment(); continue out;
case ".":
next();
p.cdr = read_token();
skip_ws();
break out;
default:
var tok = read_token();
var cell = new LispCons(tok, null);
if (ret) p.cdr = cell;
else ret = cell;
p = cell;
}
}
skip(")");
return ret;
};
return read_token;
};
///////////////// compiler
(function(LC){
var cons = LC.cons
, car = LC.car
, cdr = LC.cdr
, cadr = LC.cadr
, caddr = LC.caddr
, cadddr = LC.cadddr
, cddr = LC.cddr
, cdddr = LC.cdddr
, length = LC.len
, list = LC.fromArray;
function find_var(name, type, env) {
env = env.stuff;
for (var i = 0; i < env.length; ++i) {
var frame = env[i];
for (var j = 0; j < frame.length; ++j) {
var el = frame[j];
if (el.name == name && el.type == type)
return [ i, j ];
}
}
};
var LABEL_NUM = 0;
var S_LAMBDA = LispSymbol.get("LAMBDA");
var S_FN = LispSymbol.get("%FN");
var S_FUNCTION = LispSymbol.get("FUNCTION");
var S_IF = LispSymbol.get("IF");
var S_PROGN = LispSymbol.get("PROGN");
var S_QUOTE = LispSymbol.get("QUOTE");
var S_SET = LispSymbol.get("SETQ");
var S_T = LispSymbol.get("T");
var S_NIL = LispSymbol.get("NIL");
var S_CC = LispSymbol.get("C/C");
var S_NOT = LispSymbol.get("NOT");
var S_LET = LispSymbol.get("LET");
var S_LET$ = LispSymbol.get("LET*");
var S_LABELS = LispSymbol.get("LABELS");
var S_FLET = LispSymbol.get("FLET");
var PAK_KEYWORD = LispPackage.get("KEYWORD");
function append() {
var ret = [];
for (var i = 0; i < arguments.length; ++i) {
var el = arguments[i];
if (el.length > 0)
ret.push.apply(ret, el);
}
return ret;
};
function gen_label() {
return new LispSymbol;
};
var seq = append;
function gen() {
return [ slice(arguments) ];
};
function nullp(x) {
return x === S_NIL || x == null || (x instanceof Array && x.length == 0);
};
function arg_count(form, min, max) {
if (max == null) max = min;
var len = length(cdr(form));
if (len < min) throw new Error("Expecting at least " + min + " arguments");
if (len > max) throw new Error("Expecting at most " + max + " arguments");
};
function assert(cond, error) {
if (!cond) throw new Error(error);
};
function comp(x, env, VAL, MORE) {
if (nullp(x)) return comp_const(null, VAL, MORE);
if (LispSymbol.is(x)) {
switch (x) {
case S_NIL: return comp_const(null, VAL, MORE);
case S_T: return comp_const(true, VAL, MORE);
}
if (x.pak === PAK_KEYWORD)
return comp_const(x, VAL, MORE);
return comp_var(x, env, VAL, MORE);
}
else if (LispMachine.constantp(x)) {
return comp_const(x, VAL, MORE);
}
else switch (car(x)) {
case S_QUOTE:
arg_count(x, 1);
return comp_const(cadr(x), VAL, MORE);
case S_PROGN:
return comp_seq(cdr(x), env, VAL, MORE);
case S_SET:
arg_count(x, 2);
assert(LispSymbol.is(cadr(x)), "Only symbols can be set");
return seq(comp(caddr(x), env, true, true),
gen_set(cadr(x), env),
VAL ? [] : gen("POP"),
MORE ? [] : gen("RET"));
case S_IF:
arg_count(x, 2, 3);
return comp_if(cadr(x), caddr(x), cadddr(x), env, VAL, MORE);
case S_NOT:
arg_count(x, 1);
return VAL ? seq(
comp(cadr(x), env, true, true),
gen("NOT"),
MORE ? [] : gen("RET")
) : comp(cadr(x), env, VAL, MORE);
case S_CC:
arg_count(x, 0);
return VAL ? seq(gen("CC")) : [];
case S_LET:
return comp_let(cadr(x), cddr(x), env, VAL, MORE);
case S_LET$:
return comp_let$(cadr(x), cddr(x), env, VAL, MORE);
case S_LABELS:
return comp_flets(cadr(x), cddr(x), env, true, VAL, MORE);
case S_FLET:
return comp_flets(cadr(x), cddr(x), env, false, VAL, MORE);
case S_FN:
assert(LispSymbol.is(cadr(x)), "%FN requires a symbol name for the function");
return VAL ? seq(
comp_lambda(cadr(x), caddr(x), cdddr(x), env),
MORE ? [] : gen("RET")
) : [];
case S_LAMBDA:
return VAL ? seq(
comp_lambda(null, cadr(x), cddr(x), env),
MORE ? [] : gen("RET")
) : [];
case S_FUNCTION:
arg_count(x, 1);
assert(LispSymbol.is(cadr(x)), "FUNCTION requires a symbol");
if (VAL) {
var localfunc = find_var(cadr(x), "func", env);
if (localfunc) return gen("LVAR", localfunc[0], localfunc[1]);
return gen("FGVAR", cadr(x));
}
return [];
default:
if (LispSymbol.is(car(x)) && car(x).macro())
return comp_macroexpand(car(x), cdr(x), env, VAL, MORE);
return comp_funcall(car(x), cdr(x), env, VAL, MORE);
}
};
function gen_set(name, env) {
if (!name.special()) {
var p = find_var(name, "var", env);
if (p) return gen("LSET", p[0], p[1]);
}
return gen("GSET", name);
};
function gen_var(name, env) {
if (!name.special()) {
var pos = find_var(name, "var", env);
if (pos) return gen("LVAR", pos[0], pos[1]);
}
return gen("GVAR", name);
};
function comp_const(x, VAL, MORE) {
return VAL ? seq(
gen("CONST", x === S_NIL ? null : x === S_T ? true : x),
MORE ? [] : gen("RET")
) : [];
};
function comp_var(x, env, VAL, MORE) {
return VAL ? seq(
gen_var(x, env),
MORE ? [] : gen("RET")
) : [];
};
function comp_seq(exps, env, VAL, MORE) {
if (nullp(exps)) return comp_const(null, VAL, MORE);
if (nullp(cdr(exps))) return comp(car(exps), env, VAL, MORE);
return seq(comp(car(exps), env, false, true),
comp_seq(cdr(exps), env, VAL, MORE));
};
function comp_list(exps, env) {
if (!nullp(exps)) return seq(
comp(car(exps), env, true, true),
comp_list(cdr(exps), env)
);
return [];
};
function comp_if(pred, tthen, telse, env, VAL, MORE) {
var pcode = comp(pred, env, true, true);
var tcode = comp(tthen, env, VAL, MORE);
var ecode = comp(telse, env, VAL, MORE);
var l1 = gen_label(), l2 = gen_label();
return seq(
pcode,
gen("FJUMP", l1),
tcode,
MORE ? gen("JUMP", l2) : [],
[ l1 ],
ecode,
MORE ? [ l2 ] : []
);
};
function get_bindings(bindings, flet) {
var names = [], vals = [], specials = [];
LispCons.forEach(bindings, function(el, i, dot){
if (dot) throw new Error("Improper list in LET");
if (LC.is(el)) {
vals.push(flet ? cdr(el) : cadr(el));
el = car(el);
} else {
vals.push(S_NIL);
}
if (names.indexOf(el) >= 0)
throw new Error("Duplicate name in LET");
names.push(el);
if (el.special()) specials.push(i);
});
return { names: names, vals: vals, specials: specials, len: names.length };
};
function comp_let(bindings, body, env, VAL, MORE) {
if (nullp(bindings)) return comp_seq(body, env, VAL, MORE);
var b = get_bindings(bindings);
var ret = seq(
seq.apply(null, b.vals.map(function(x){
return comp(x, env, true, true);
})),
gen("LET", b.len),
b.specials.map(function(i){
return gen("BIND", b.names[i], i)[0];
}),
comp_seq(body, env.extend("var", b.names), VAL, true),
gen("UNFR", 1, b.specials.length, 0),
MORE ? [] : gen("RET")
);
return ret;
};
function comp_let$(bindings, body, env, VAL, MORE) {
if (nullp(bindings)) return comp_seq(body, env, VAL, MORE);
var b = get_bindings(bindings);
var newargs = [];
var ret = seq(
seq.apply(null, b.vals.map(function(x, i){
var name = b.names[i];
x = seq(
comp(x, env, true, true),
i == 0 ? gen("FRAME") : [],
gen("VAR"),
name.special() ? gen("BIND", name, i) : []
);
if (i == 0) {
env = env.extend("var", newargs);
}
env.add(name, "var");
return x;
})),
comp_seq(body, env, VAL, true),
gen("UNFR", 1, b.specials.length, 0),
MORE ? [] : gen("RET")
);
return ret;
};
function comp_flets(bindings, body, env, is_labels, VAL, MORE) {
if (nullp(bindings)) return comp_seq(body, env, VAL, MORE);
var b = get_bindings(bindings, true);
if (is_labels) env = env.extend("func", b.names);
return seq(
is_labels ? gen("FRAME") : [],
seq.apply(null, b.names.map(function(name, i){
return comp_lambda(name, car(b.vals[i]), cdr(b.vals[i]), env)
})),
is_labels ? [] : gen("FRAME"),
b.len > 1 ? gen("VARS", b.len) : gen("VAR"),
comp_seq(body, is_labels ? env : env.extend("func", b.names), VAL, true),
gen("UNFR", 1, 0),
MORE ? [] : gen("RET")
);
};
function comp_funcall(f, args, env, VAL, MORE) {
function mkret(the_function) {
if (MORE) {
var k = gen_label();
return seq(
gen("SAVE", k),
comp_list(args, env),
the_function,
gen("CALL", length(args)),
[ k ],
VAL ? [] : gen("POP")
);
}
return seq(
comp_list(args, env),
the_function,
gen("CALL", length(args))
);
};
if (LispSymbol.is(f)) {
var localfun = find_var(f, "func", env);
if (localfun) return mkret(gen("LVAR", localfun[0], localfun[1]));
if (f.primitive()) {
if (!VAL && !f.getv("primitive-side-effects")) {
return comp_seq(args, env, false, MORE);
}
return seq(comp_list(args, env),
gen("PRIM", f, length(args)),
VAL ? [] : gen("POP"),
MORE ? [] : gen("RET"));
}
if (!f.func()) console.warn("Undefined function", f);
return mkret(gen("FGVAR", f));
}
if (LC.is(f) && car(f) === S_LAMBDA && nullp(cadr(f))) {
assert(nullp(args), "Too many arguments");
return comp_seq(cddr(f), env, VAL, MORE);
}
return mkret(comp(f, env, true, true));
};
function comp_lambda(name, args, body, env) {
if (LC.isList(args)) {
var dot = LC.isDotted(args);
var a = LC.toArray(args);
if (dot) a.push([ a.pop(), a.pop() ][0]);
var dyn = [];
for (var i = a.length; --i >= 0;) {
if (a[i].special())
dyn.push([ "BIND", a[i], i ]);
}
if (!dot) {
return gen("FN",
seq(a.length > 0 ? gen("ARGS", a.length) : [],
dyn,
comp_seq(body, a.length > 0 ? env.extend("var", a) : env, true, false)),
name);
}
return gen("FN",
seq(gen("ARG_", dot),
dyn,
comp_seq(body, env.extend("var", a), true, false)),
name);
} else {
return gen("FN",
seq(gen("ARG_", 0),
args.special() ? gen("BIND", args, 0) : [],
comp_seq(body, env.extend("var", [ args ]), true, false)),
name);
}
};
function comp_macroexpand(name, args, env, VAL, MORE) {
var m = new LispMachine();
var ast = m._call(name.macro(), args);
var ret = comp(ast, env, VAL, MORE);
return ret;
};
this.lisp_compile = function(x) {
return comp_seq(x, new Environment(), true, true);
};
var Environment = DEFCLASS("Environment", null, function(D, P){
P.INIT = function() {
this.stuff = [];
};
P.extend = function(type, val) {
var env = new Environment();
env.stuff = [ val.map(function(name){
return { name: name, type: type };
}) ].concat(this.stuff);
return env;
};
P.add = function(name, type) {
this.stuff[0].push({ name: name, type: type });
};
});
})(LispCons);
|
mishoo/SLip
|
js/compiler.js
|
JavaScript
|
bsd-2-clause
| 26,479
|
// This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-empty.case
// - src/dstr-binding/default/for-of-let.template
/*---
description: No iteration occurs for an "empty" array binding pattern (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
es6id: 13.7.5.11
features: [generators, destructuring-binding]
flags: [generated]
info: |
IterationStatement :
for ( ForDeclaration of AssignmentExpression ) Statement
[...]
3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
3. Let destructuring be IsDestructuring of lhs.
[...]
5. Repeat
[...]
h. If destructuring is false, then
[...]
i. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.6 Runtime Semantics: IteratorBindingInitialization
ArrayBindingPattern : [ ]
1. Return NormalCompletion(empty).
---*/
var iterations = 0;
var iter = function*() {
iterations += 1;
}();
var iterCount = 0;
for (let [] of [iter]) {
assert.sameValue(iterations, 0);
iterCount += 1;
}
assert.sameValue(iterCount, 1, 'Iteration occurred as expected');
|
sebastienros/jint
|
Jint.Tests.Test262/test/language/statements/for-of/dstr-let-ary-ptrn-empty.js
|
JavaScript
|
bsd-2-clause
| 1,668
|
$(function() {
$("#cancel").click(function() {
$(".resettable").addClass('hidden');
var form = $(this).parent("form");
form.find("[readonly]").removeAttr('readonly');
form.find("[disabled]").removeAttr('disabled');
form.find('[name="email"]').focus();
form.find('button[type="submit"]').val("Email me authorization link");
});
$("#login_form").submit(function(e) {
var form = $(this),
button = form.find('[type="submit"]'),
cancel = form.find('#cancel'),
email = form.find('[name="email"]'),
code = form.find('[name="code"]'),
message = form.find('.response_status'),
errorCallback = function(error) {
message.removeClass('hidden');
form.get(0).reset();
email.focus();
message.text(error.response || error.responseText).addClass('error');
};
if (!form.data('processing')) {
form.data('processing', true);
button.attr('disabled', 'disabled');
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json",
success: function(data) {
console.log(data)
form.data('processing', false);
if (!!data.success) {
if (data.reload) setTimeout(location.reload, 1000);
message.text(data.response).removeClass('error').removeClass('hidden');
email.attr('readonly', 'readonly');
code.removeClass('hidden');
cancel.removeClass('hidden');
button.val('Send code');
} else errorCallback(data);
},
error: errorCallback,
complete: function(data) {
button.removeAttr('disabled');
form.removeData('processing');
}
});
e.preventDefault();
};
});
});
|
rozzy/LosslessDJ
|
public/script.js
|
JavaScript
|
bsd-2-clause
| 1,805
|
module.exports = {
tankSize: 5,
port: 3009,
tick: 100,
fire: 1000,
respawn: 10, // Количество тиков от смерти до появления в новом месте
immortal: 25, // Максимальное время бессмертия после респавна
aiTimeout: 10, // Максимально допустимое время на 1 тик для бота
maxPlayers: 10, // Максимальное число игроков на арене
saveBestPlayersNum: 0 // Число лучших игроков которые не вылетают при рестарте арены
};
|
2gis/Battlegis
|
config.js
|
JavaScript
|
bsd-2-clause
| 648
|
/**
* IrisObject class
* Create by Hui on 2016-11-29
* Modified by DaraW on 2016-1-15
*/
import IrisMethod from "./iris_method";
import IrisValue from "./iris_value";
import $dev_util from "../util/iris_dev";
import {
class_sym,
instance_variables_sym,
instance_methods_sym,
native_object_sym,
object_id_sym
} from "../util/iris_symbol";
let inline_OBJECT_COUNT = 0;
export default class IrisObject {
constructor() {
this[instance_methods_sym] = new Map();
this[instance_variables_sym] = new Map();
this[class_sym] = null;
this[native_object_sym] = null;
this[object_id_sym] = ++inline_OBJECT_COUNT;
}
/*
* parameter of *thread_info* is NO USE currently
*/
call_instance_method(method_name, parameter_list, context, thread_info, callside) {
let method = null;
let is_current_method = false;
if (this[instance_methods_sym].has(method_name)) {
// Object's instance method
method = this[instance_methods_sym].get(method_name);
is_current_method = true;
} else {
// instance method in class
let result = new IrisClass.SearchResult();
this[class_sym].get_method(method_name, result);
method = result.method;
is_current_method = result.is_current_class_method;
}
if (method === null) {
return $dev_util.nil;
}
let call_result = null;
let caller = IrisValue.wrap_object(this);
if (callside === IrisMethod.CallSide.Inside) {
if (is_current_method) {
// Inside Call
call_result = method.call(caller, parameter_list, context, thread_info);
} else {
// Outside Call
if (method.get_authority() === IrisMethod.MethodAuthority.Personal) {
call_result = $dev_util.nil;
} else {
call_result = method.call(caller, parameter_list, context, thread_info);
}
}
}
return call_result;
}
add_instance_method(method) {
this[instance_methods_sym].set(method.get_method_name(), method);
}
add_instance_variable(name, value) {
this[instance_variables_sym].set(name, value);
}
get_instance_variable(name) {
return this[instance_variables_sym].get(name);
}
reset_all_methods_object() {
for (let [method_name, method] of this[instance_methods_sym].entries()) {
method.reset_methods_object();
}
}
// Getters and Setters
set class(new_class) {
this[class_sym] = new_class;
}
get class() {
return this[class_sym];
}
set native_object(new_native_object) {
this[native_object_sym] = new_native_object;
}
get native_object() {
return this[native_object_sym];
}
get object_id() {
return this[object_id_sym];
}
}
|
CodeDaraW/Iris.js
|
src/irislang/core/iris_object.js
|
JavaScript
|
bsd-2-clause
| 3,076
|
/*
* jQuery Plugin: Tokenizing Autocomplete Text Entry
* Version 1.6.1
*
* Copyright (c) 2009 James Smith (http://loopj.com)
* Licensed jointly under the GPL and MIT licenses,
* choose which one suits your project best!
*
*/
(function ($) {
// Default settings
var DEFAULT_SETTINGS = {
// Search settings
method: "GET",
queryParam: "q",
searchDelay: 300,
minChars: 1,
propertyToSearch: "name",
jsonContainer: null,
contentType: "json",
// Prepopulation settings
prePopulate: null,
processPrePopulate: false,
// Display settings
hintText: "Type in a search term",
noResultsText: "No results",
searchingText: "Searching...",
deleteText: "×",
animateDropdown: true,
placeholder: null,
theme: null,
zindex: 999,
resultsLimit: null,
enableHTML: false,
resultsFormatter: function(item) {
var string = item[this.propertyToSearch];
return "<li>" + (this.enableHTML ? string : _escapeHTML(string)) + "</li>";
},
tokenFormatter: function(item) {
var string = item[this.propertyToSearch];
return "<li><p>" + (this.enableHTML ? string : _escapeHTML(string)) + "</p></li>";
},
// Tokenization settings
tokenLimit: null,
tokenDelimiter: ",",
preventDuplicates: false,
tokenValue: "id",
// Behavioral settings
allowFreeTagging: false,
allowTabOut: false,
// Callbacks
onResult: null,
onCachedResult: null,
onAdd: null,
onFreeTaggingAdd: null,
onDelete: null,
onReady: null,
// Other settings
idPrefix: "token-input-",
// Keep track if the input is currently in disabled mode
disabled: false
};
// Default classes to use when theming
var DEFAULT_CLASSES = {
tokenList: "token-input-list",
token: "token-input-token",
tokenReadOnly: "token-input-token-readonly",
tokenDelete: "token-input-delete-token",
selectedToken: "token-input-selected-token",
highlightedToken: "token-input-highlighted-token",
dropdown: "token-input-dropdown",
dropdownItem: "token-input-dropdown-item",
dropdownItem2: "token-input-dropdown-item2",
selectedDropdownItem: "token-input-selected-dropdown-item",
inputToken: "token-input-input-token",
focused: "token-input-focused",
disabled: "token-input-disabled"
};
// Input box position "enum"
var POSITION = {
BEFORE: 0,
AFTER: 1,
END: 2
};
// Keys "enum"
var KEY = {
BACKSPACE: 8,
TAB: 9,
ENTER: 13,
ESCAPE: 27,
SPACE: 32,
PAGE_UP: 33,
PAGE_DOWN: 34,
END: 35,
HOME: 36,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
NUMPAD_ENTER: 108,
COMMA: 188
};
var HTML_ESCAPES = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
var HTML_ESCAPE_CHARS = /[&<>"'\/]/g;
function coerceToString(val) {
return String((val === null || val === undefined) ? '' : val);
}
function _escapeHTML(text) {
return coerceToString(text).replace(HTML_ESCAPE_CHARS, function(match) {
return HTML_ESCAPES[match];
});
}
// Additional public (exposed) methods
var methods = {
init: function(url_or_data_or_function, options) {
var settings = $.extend({}, DEFAULT_SETTINGS, options || {});
return this.each(function () {
$(this).data("settings", settings);
$(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
});
},
clear: function() {
this.data("tokenInputObject").clear();
return this;
},
add: function(item) {
this.data("tokenInputObject").add(item);
return this;
},
remove: function(item) {
this.data("tokenInputObject").remove(item);
return this;
},
get: function() {
return this.data("tokenInputObject").getTokens();
},
toggleDisabled: function(disable) {
this.data("tokenInputObject").toggleDisabled(disable);
return this;
},
setOptions: function(options){
$(this).data("settings", $.extend({}, $(this).data("settings"), options || {}));
return this;
},
destroy: function () {
if(this.data("tokenInputObject")){
this.data("tokenInputObject").clear();
var tmpInput = this;
var closest = this.parent();
closest.empty();
tmpInput.show();
closest.append(tmpInput);
return tmpInput;
}
}
};
// Expose the .tokenInput function to jQuery as a plugin
$.fn.tokenInput = function (method) {
// Method calling and initialization logic
if(methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
return methods.init.apply(this, arguments);
}
};
// TokenList class for each input
$.TokenList = function (input, url_or_data, settings) {
//
// Initialization
//
// Configure the data source
if($.type(url_or_data) === "string" || $.type(url_or_data) === "function") {
// Set the url to query against
$(input).data("settings").url = url_or_data;
// If the URL is a function, evaluate it here to do our initalization work
var url = computeURL();
// Make a smart guess about cross-domain if it wasn't explicitly specified
if($(input).data("settings").crossDomain === undefined && typeof url === "string") {
if(url.indexOf("://") === -1) {
$(input).data("settings").crossDomain = false;
} else {
$(input).data("settings").crossDomain = (location.href.split(/\/+/g)[1] !== url.split(/\/+/g)[1]);
}
}
} else if(typeof(url_or_data) === "object") {
// Set the local data to search through
$(input).data("settings").local_data = url_or_data;
}
// Build class names
if($(input).data("settings").classes) {
// Use custom class names
$(input).data("settings").classes = $.extend({}, DEFAULT_CLASSES, $(input).data("settings").classes);
} else if($(input).data("settings").theme) {
// Use theme-suffixed default class names
$(input).data("settings").classes = {};
$.each(DEFAULT_CLASSES, function(key, value) {
$(input).data("settings").classes[key] = value + "-" + $(input).data("settings").theme;
});
} else {
$(input).data("settings").classes = DEFAULT_CLASSES;
}
// Save the tokens
var saved_tokens = [];
// Keep track of the number of tokens in the list
var token_count = 0;
// Basic cache to save on db hits
var cache = new $.TokenList.Cache();
// Keep track of the timeout, old vals
var timeout;
var input_val;
// Create a new text input an attach keyup events
var input_box = $("<input type=\"text\" autocomplete=\"off\" autocapitalize=\"off\">")
.css({
outline: "none"
})
.attr("id", $(input).data("settings").idPrefix + input.id)
.focus(function () {
if ($(input).data("settings").disabled) {
return false;
} else
if ($(input).data("settings").tokenLimit === null || $(input).data("settings").tokenLimit !== token_count) {
show_dropdown_hint();
}
token_list.addClass($(input).data("settings").classes.focused);
})
.blur(function () {
hide_dropdown();
if ($(input).data("settings").allowFreeTagging) {
add_freetagging_tokens();
}
$(this).val("");
token_list.removeClass($(input).data("settings").classes.focused);
})
.bind("keyup keydown blur update", resize_input)
.keydown(function (event) {
var previous_token;
var next_token;
switch(event.keyCode) {
case KEY.LEFT:
case KEY.RIGHT:
case KEY.UP:
case KEY.DOWN:
if(!$(this).val()) {
previous_token = input_token.prev();
next_token = input_token.next();
if((previous_token.length && previous_token.get(0) === selected_token) || (next_token.length && next_token.get(0) === selected_token)) {
// Check if there is a previous/next token and it is selected
if(event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) {
deselect_token($(selected_token), POSITION.BEFORE);
} else {
deselect_token($(selected_token), POSITION.AFTER);
}
} else if((event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) && previous_token.length) {
// We are moving left, select the previous token if it exists
select_token($(previous_token.get(0)));
} else if((event.keyCode === KEY.RIGHT || event.keyCode === KEY.DOWN) && next_token.length) {
// We are moving right, select the next token if it exists
select_token($(next_token.get(0)));
}
} else {
var dropdown_item = null;
if(event.keyCode === KEY.DOWN || event.keyCode === KEY.RIGHT) {
dropdown_item = $(selected_dropdown_item).next();
} else {
dropdown_item = $(selected_dropdown_item).prev();
}
if(dropdown_item.length) {
select_dropdown_item(dropdown_item);
}
}
return false;
break;
case KEY.BACKSPACE:
previous_token = input_token.prev();
if(!$(this).val().length) {
if(selected_token) {
delete_token($(selected_token));
hidden_input.change();
} else if(previous_token.length) {
select_token($(previous_token.get(0)));
}
return false;
} else if($(this).val().length === 1) {
hide_dropdown();
} else {
// set a timeout just long enough to let this function finish.
setTimeout(function(){do_search();}, 5);
}
break;
case KEY.TAB:
case KEY.ENTER:
case KEY.NUMPAD_ENTER:
case KEY.COMMA:
if(selected_dropdown_item) {
add_token($(selected_dropdown_item).data("tokeninput"));
hidden_input.change();
} else {
if ($(input).data("settings").allowFreeTagging) {
if($(input).data("settings").allowTabOut && $(this).val() === "") {
return true;
} else {
add_freetagging_tokens();
}
} else {
$(this).val("");
if($(input).data("settings").allowTabOut) {
return true;
}
}
event.stopPropagation();
event.preventDefault();
}
return false;
case KEY.ESCAPE:
hide_dropdown();
return true;
default:
if(String.fromCharCode(event.which)) {
// set a timeout just long enough to let this function finish.
setTimeout(function(){do_search();}, 5);
}
break;
}
});
// Keep reference for placeholder
if (settings.placeholder)
input_box.attr("placeholder", settings.placeholder)
// Keep a reference to the original input box
var hidden_input = $(input)
.hide()
.val("")
.focus(function () {
focus_with_timeout(input_box);
})
.blur(function () {
input_box.blur();
//return the object to this can be referenced in the callback functions.
return hidden_input;
});
// Keep a reference to the selected token and dropdown item
var selected_token = null;
var selected_token_index = 0;
var selected_dropdown_item = null;
// The list to store the token items in
var token_list = $("<ul />")
.addClass($(input).data("settings").classes.tokenList)
.click(function (event) {
var li = $(event.target).closest("li");
if(li && li.get(0) && $.data(li.get(0), "tokeninput")) {
toggle_select_token(li);
} else {
// Deselect selected token
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
// Focus input box
focus_with_timeout(input_box);
}
})
.mouseover(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.addClass($(input).data("settings").classes.highlightedToken);
}
})
.mouseout(function (event) {
var li = $(event.target).closest("li");
if(li && selected_token !== this) {
li.removeClass($(input).data("settings").classes.highlightedToken);
}
})
.insertBefore(hidden_input);
// The token holding the input box
var input_token = $("<li />")
.addClass($(input).data("settings").classes.inputToken)
.appendTo(token_list)
.append(input_box);
// The list to store the dropdown items in
var dropdown = $("<div>")
.addClass($(input).data("settings").classes.dropdown)
.appendTo("body")
.hide();
// Magic element to help us resize the text input
var input_resizer = $("<tester/>")
.insertAfter(input_box)
.css({
position: "absolute",
top: -9999,
left: -9999,
width: "auto",
fontSize: input_box.css("fontSize"),
fontFamily: input_box.css("fontFamily"),
fontWeight: input_box.css("fontWeight"),
letterSpacing: input_box.css("letterSpacing"),
whiteSpace: "nowrap"
});
// Pre-populate list if items exist
hidden_input.val("");
var li_data = $(input).data("settings").prePopulate || hidden_input.data("pre");
if($(input).data("settings").processPrePopulate && $.isFunction($(input).data("settings").onResult)) {
li_data = $(input).data("settings").onResult.call(hidden_input, li_data);
}
if(li_data && li_data.length) {
$.each(li_data, function (index, value) {
insert_token(value);
checkTokenLimit();
input_box.attr("placeholder", null)
});
}
// Check if widget should initialize as disabled
if ($(input).data("settings").disabled) {
toggleDisabled(true);
}
// Initialization is done
if($.isFunction($(input).data("settings").onReady)) {
$(input).data("settings").onReady.call();
}
//
// Public functions
//
this.clear = function() {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
delete_token($(this));
}
});
};
this.add = function(item) {
add_token(item);
};
this.remove = function(item) {
token_list.children("li").each(function() {
if ($(this).children("input").length === 0) {
var currToken = $(this).data("tokeninput");
var match = true;
for (var prop in item) {
if (item[prop] !== currToken[prop]) {
match = false;
break;
}
}
if (match) {
delete_token($(this));
}
}
});
};
this.getTokens = function() {
return saved_tokens;
};
this.toggleDisabled = function(disable) {
toggleDisabled(disable);
};
// Resize input to maximum width so the placeholder can be seen
resize_input();
//
// Private functions
//
function escapeHTML(text) {
return $(input).data("settings").enableHTML ? text : _escapeHTML(text);
}
// Toggles the widget between enabled and disabled state, or according
// to the [disable] parameter.
function toggleDisabled(disable) {
if (typeof disable === 'boolean') {
$(input).data("settings").disabled = disable
} else {
$(input).data("settings").disabled = !$(input).data("settings").disabled;
}
input_box.attr('disabled', $(input).data("settings").disabled);
token_list.toggleClass($(input).data("settings").classes.disabled, $(input).data("settings").disabled);
// if there is any token selected we deselect it
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
hidden_input.attr('disabled', $(input).data("settings").disabled);
}
function checkTokenLimit() {
if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) {
input_box.hide();
hide_dropdown();
return;
}
}
function resize_input() {
if(input_val === (input_val = input_box.val())) {return;}
// Get width left on the current line
var width_left = token_list.width() - input_box.offset().left - token_list.offset().left;
// Enter new content into resizer and resize input accordingly
input_resizer.html(_escapeHTML(input_val) || _escapeHTML(settings.placeholder));
// Get maximum width, minimum the size of input and maximum the widget's width
input_box.width(Math.min(token_list.width(),
Math.max(width_left, input_resizer.width() + 30)));
}
function is_printable_character(keycode) {
return ((keycode >= 48 && keycode <= 90) || // 0-1a-z
(keycode >= 96 && keycode <= 111) || // numpad 0-9 + - / * .
(keycode >= 186 && keycode <= 192) || // ; = , - . / ^
(keycode >= 219 && keycode <= 222)); // ( \ ) '
}
function add_freetagging_tokens() {
var value = $.trim(input_box.val());
var tokens = value.split($(input).data("settings").tokenDelimiter);
$.each(tokens, function(i, token) {
if (!token) {
return;
}
if ($.isFunction($(input).data("settings").onFreeTaggingAdd)) {
token = $(input).data("settings").onFreeTaggingAdd.call(hidden_input, token);
}
var object = {};
object[$(input).data("settings").tokenValue] = object[$(input).data("settings").propertyToSearch] = token;
add_token(object);
});
}
// Inner function to a token to the list
function insert_token(item) {
var $this_token = $($(input).data("settings").tokenFormatter(item));
var readonly = item.readonly === true ? true : false;
if(readonly) $this_token.addClass($(input).data("settings").classes.tokenReadOnly);
$this_token.addClass($(input).data("settings").classes.token).insertBefore(input_token);
// The 'delete token' button
if(!readonly) {
$("<span>" + $(input).data("settings").deleteText + "</span>")
.addClass($(input).data("settings").classes.tokenDelete)
.appendTo($this_token)
.click(function () {
if (!$(input).data("settings").disabled) {
delete_token($(this).parent());
hidden_input.change();
return false;
}
});
}
// Store data on the token
var token_data = item;
$.data($this_token.get(0), "tokeninput", item);
// Save this token for duplicate checking
saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index));
selected_token_index++;
// Update the hidden input
update_hidden_input(saved_tokens, hidden_input);
token_count += 1;
// Check the token limit
if($(input).data("settings").tokenLimit !== null && token_count >= $(input).data("settings").tokenLimit) {
input_box.hide();
hide_dropdown();
}
return $this_token;
}
// Add a token to the token list based on user input
function add_token (item) {
var callback = $(input).data("settings").onAdd;
// See if the token already exists and select it if we don't want duplicates
if(token_count > 0 && $(input).data("settings").preventDuplicates) {
var found_existing_token = null;
token_list.children().each(function () {
var existing_token = $(this);
var existing_data = $.data(existing_token.get(0), "tokeninput");
if(existing_data && existing_data[settings.tokenValue] === item[settings.tokenValue]) {
found_existing_token = existing_token;
return false;
}
});
if(found_existing_token) {
select_token(found_existing_token);
input_token.insertAfter(found_existing_token);
focus_with_timeout(input_box);
return;
}
}
// Squeeze input_box so we force no unnecessary line break
input_box.width(0);
// Insert the new tokens
if($(input).data("settings").tokenLimit == null || token_count < $(input).data("settings").tokenLimit) {
insert_token(item);
// Remove the placeholder so it's not seen after you've added a token
input_box.attr("placeholder", null)
checkTokenLimit();
}
// Clear input box
input_box.val("");
// Don't show the help dropdown, they've got the idea
hide_dropdown();
// Execute the onAdd callback if defined
if($.isFunction(callback)) {
callback.call(hidden_input,item);
}
}
// Select a token in the token list
function select_token (token) {
if (!$(input).data("settings").disabled) {
token.addClass($(input).data("settings").classes.selectedToken);
selected_token = token.get(0);
// Hide input box
input_box.val("");
// Hide dropdown if it is visible (eg if we clicked to select token)
hide_dropdown();
}
}
// Deselect a token in the token list
function deselect_token (token, position) {
token.removeClass($(input).data("settings").classes.selectedToken);
selected_token = null;
if(position === POSITION.BEFORE) {
input_token.insertBefore(token);
selected_token_index--;
} else if(position === POSITION.AFTER) {
input_token.insertAfter(token);
selected_token_index++;
} else {
input_token.appendTo(token_list);
selected_token_index = token_count;
}
// Show the input box and give it focus again
focus_with_timeout(input_box);
}
// Toggle selection of a token in the token list
function toggle_select_token(token) {
var previous_selected_token = selected_token;
if(selected_token) {
deselect_token($(selected_token), POSITION.END);
}
if(previous_selected_token === token.get(0)) {
deselect_token(token, POSITION.END);
} else {
select_token(token);
}
}
// Delete a token from the token list
function delete_token (token) {
// Remove the id from the saved list
var token_data = $.data(token.get(0), "tokeninput");
var callback = $(input).data("settings").onDelete;
var index = token.prevAll().length;
if(index > selected_token_index) index--;
// Delete the token
token.remove();
selected_token = null;
// Show the input box and give it focus again
focus_with_timeout(input_box);
// Remove this token from the saved list
saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1));
if (saved_tokens.length == 0) {
input_box.attr("placeholder", settings.placeholder)
}
if(index < selected_token_index) selected_token_index--;
// Update the hidden input
update_hidden_input(saved_tokens, hidden_input);
token_count -= 1;
if($(input).data("settings").tokenLimit !== null) {
input_box
.show()
.val("");
focus_with_timeout(input_box);
}
// Execute the onDelete callback if defined
if($.isFunction(callback)) {
callback.call(hidden_input,token_data);
}
}
// Update the hidden input box value
function update_hidden_input(saved_tokens, hidden_input) {
var token_values = $.map(saved_tokens, function (el) {
if(typeof $(input).data("settings").tokenValue == 'function')
return $(input).data("settings").tokenValue.call(this, el);
return el[$(input).data("settings").tokenValue];
});
hidden_input.val(token_values.join($(input).data("settings").tokenDelimiter));
}
// Hide and clear the results dropdown
function hide_dropdown () {
dropdown.hide().empty();
selected_dropdown_item = null;
}
function show_dropdown() {
dropdown
.css({
position: "absolute",
top: token_list.offset().top + token_list.outerHeight(),
left: token_list.offset().left,
width: token_list.width(),
'z-index': $(input).data("settings").zindex
})
.show();
}
function show_dropdown_searching () {
if($(input).data("settings").searchingText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").searchingText) + "</p>");
show_dropdown();
}
}
function show_dropdown_hint () {
if($(input).data("settings").hintText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").hintText) + "</p>");
show_dropdown();
}
}
var regexp_special_chars = new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\-]', 'g');
function regexp_escape(term) {
return term.replace(regexp_special_chars, '\\$&');
}
// Highlight the query part of the search term
function highlight_term(value, term) {
return value.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(term) + ")(?![^<>]*>)(?![^&;]+;)",
"gi"
), function(match, p1) {
return "<b>" + escapeHTML(p1) + "</b>";
}
);
}
function find_value_and_highlight_term(template, value, term) {
return template.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + regexp_escape(value) + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term));
}
// Populate the results dropdown with some results
function populate_dropdown (query, results) {
if(results && results.length) {
dropdown.empty();
var dropdown_ul = $("<ul>")
.appendTo(dropdown)
.mouseover(function (event) {
select_dropdown_item($(event.target).closest("li"));
})
.mousedown(function (event) {
add_token($(event.target).closest("li").data("tokeninput"));
hidden_input.change();
return false;
})
.hide();
if ($(input).data("settings").resultsLimit && results.length > $(input).data("settings").resultsLimit) {
results = results.slice(0, $(input).data("settings").resultsLimit);
}
$.each(results, function(index, value) {
var this_li = $(input).data("settings").resultsFormatter(value);
this_li = find_value_and_highlight_term(this_li ,value[$(input).data("settings").propertyToSearch], query);
this_li = $(this_li).appendTo(dropdown_ul);
if(index % 2) {
this_li.addClass($(input).data("settings").classes.dropdownItem);
} else {
this_li.addClass($(input).data("settings").classes.dropdownItem2);
}
if(index === 0) {
select_dropdown_item(this_li);
}
$.data(this_li.get(0), "tokeninput", value);
});
show_dropdown();
if($(input).data("settings").animateDropdown) {
dropdown_ul.slideDown("fast");
} else {
dropdown_ul.show();
}
} else {
if($(input).data("settings").noResultsText) {
dropdown.html("<p>" + escapeHTML($(input).data("settings").noResultsText) + "</p>");
show_dropdown();
}
}
}
// Highlight an item in the results dropdown
function select_dropdown_item (item) {
if(item) {
if(selected_dropdown_item) {
deselect_dropdown_item($(selected_dropdown_item));
}
item.addClass($(input).data("settings").classes.selectedDropdownItem);
selected_dropdown_item = item.get(0);
}
}
// Remove highlighting from an item in the results dropdown
function deselect_dropdown_item (item) {
item.removeClass($(input).data("settings").classes.selectedDropdownItem);
selected_dropdown_item = null;
}
// Do a search and show the "searching" dropdown if the input is longer
// than $(input).data("settings").minChars
function do_search() {
var query = input_box.val();
if(query && query.length) {
if(selected_token) {
deselect_token($(selected_token), POSITION.AFTER);
}
if(query.length >= $(input).data("settings").minChars) {
show_dropdown_searching();
clearTimeout(timeout);
timeout = setTimeout(function(){
run_search(query);
}, $(input).data("settings").searchDelay);
} else {
hide_dropdown();
}
}
}
// Do the actual search
function run_search(query) {
var cache_key = query + computeURL();
var cached_results = null; // cache.get(cache_key);
if(cached_results) {
if ($.isFunction($(input).data("settings").onCachedResult)) {
cached_results = $(input).data("settings").onCachedResult.call(hidden_input, cached_results);
}
populate_dropdown(query, cached_results);
} else {
// Are we doing an ajax search or local data search?
if($(input).data("settings").url) {
var url = computeURL();
// Extract exisiting get params
var ajax_params = {};
ajax_params.data = {};
if(url.indexOf("?") > -1) {
var parts = url.split("?");
ajax_params.url = parts[0];
var param_array = parts[1].split("&");
$.each(param_array, function (index, value) {
var kv = value.split("=");
ajax_params.data[kv[0]] = kv[1];
});
} else {
ajax_params.url = url;
}
// Prepare the request
ajax_params.data[$(input).data("settings").queryParam] = query;
ajax_params.type = $(input).data("settings").method;
ajax_params.dataType = $(input).data("settings").contentType;
if($(input).data("settings").crossDomain) {
ajax_params.dataType = "jsonp";
}
// Attach the success callback
ajax_params.success = function(results) {
cache.add(cache_key, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
if($.isFunction($(input).data("settings").onResult)) {
results = $(input).data("settings").onResult.call(hidden_input, results);
}
// only populate the dropdown if the results are associated with the active search query
if(input_box.val() === query) {
populate_dropdown(query, $(input).data("settings").jsonContainer ? results[$(input).data("settings").jsonContainer] : results);
}
};
// Provide a beforeSend callback
if (settings.onSend) {
settings.onSend(ajax_params);
}
// Make the request
$.ajax(ajax_params);
} else if($(input).data("settings").local_data) {
// Do the search through local data
var results = $.grep($(input).data("settings").local_data, function (row) {
return row[$(input).data("settings").propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1;
});
cache.add(cache_key, results);
if($.isFunction($(input).data("settings").onResult)) {
results = $(input).data("settings").onResult.call(hidden_input, results);
}
populate_dropdown(query, results);
}
}
}
// compute the dynamic URL
function computeURL() {
var url = $(input).data("settings").url;
if(typeof $(input).data("settings").url == 'function') {
url = $(input).data("settings").url.call($(input).data("settings"));
}
return url;
}
// Bring browser focus to the specified object.
// Use of setTimeout is to get around an IE bug.
// (See, e.g., http://stackoverflow.com/questions/2600186/focus-doesnt-work-in-ie)
//
// obj: a jQuery object to focus()
function focus_with_timeout(obj) {
setTimeout(function() { obj.focus(); }, 50);
}
};
// Really basic cache for the results
$.TokenList.Cache = function (options) {
var settings = $.extend({
max_size: 500
}, options);
var data = {};
var size = 0;
var flush = function () {
data = {};
size = 0;
};
this.add = function (query, results) {
if(size > settings.max_size) {
flush();
}
if(!data[query]) {
size += 1;
}
data[query] = results;
};
this.get = function (query) {
return data[query];
};
};
}(jQuery));
|
ceari/whyattend
|
whyattend/static/js/jquery.tokeninput.js
|
JavaScript
|
bsd-2-clause
| 36,291
|
import LazyWrapper from '../internal/LazyWrapper';
import LodashWrapper from '../internal/LodashWrapper';
import thru from './thru';
/**
* Reverses the wrapped array so the first element becomes the last, the
* second element becomes the second to last, and so on.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @category Chain
* @returns {Object} Returns the new reversed `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
if (this.__actions__.length) {
value = new LazyWrapper(this);
}
return new LodashWrapper(value.reverse(), this.__chain__);
}
return this.thru(function(value) {
return value.reverse();
});
}
export default wrapperReverse;
|
wushuyi/remoteMultiSketchpad
|
frontend/assets/libs/lodash-3.6.0-es/chain/wrapperReverse.js
|
JavaScript
|
bsd-2-clause
| 940
|
// Copyright (C) 2018 Caio Lima. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: Relational comparison of BigInt and boolean values
esid: sec-abstract-relational-comparison
features: [BigInt]
---*/
assert.sameValue(0n > false, false, 'The result of (0n > false) is false');
assert.sameValue(false > 0n, false, 'The result of (false > 0n) is false');
assert.sameValue(0n > true, false, 'The result of (0n > true) is false');
assert.sameValue(true > 0n, true, 'The result of (true > 0n) is true');
assert.sameValue(1n > false, true, 'The result of (1n > false) is true');
assert.sameValue(false > 1n, false, 'The result of (false > 1n) is false');
assert.sameValue(1n > true, false, 'The result of (1n > true) is false');
assert.sameValue(true > 1n, false, 'The result of (true > 1n) is false');
assert.sameValue(31n > true, true, 'The result of (31n > true) is true');
assert.sameValue(true > 31n, false, 'The result of (true > 31n) is false');
assert.sameValue(-3n > true, false, 'The result of (-3n > true) is false');
assert.sameValue(true > -3n, true, 'The result of (true > -3n) is true');
assert.sameValue(-3n > false, false, 'The result of (-3n > false) is false');
assert.sameValue(false > -3n, true, 'The result of (false > -3n) is true');
|
sebastienros/jint
|
Jint.Tests.Test262/test/language/expressions/greater-than/bigint-and-boolean.js
|
JavaScript
|
bsd-2-clause
| 1,310
|
import { $http } from '@/services/ng';
function processTags(data) {
return data.tags || [];
}
export default function getTags(url) {
return $http.get(url).then(response => processTags(response.data));
}
|
chriszs/redash
|
client/app/services/getTags.js
|
JavaScript
|
bsd-2-clause
| 209
|
/**
* 弹层预览
* @file LightBox.js
* @author liwei
*/
define(function (require) {
var esui = require('esui');
var lib = require('esui/lib');
var u = require('underscore');
var eoo = require('eoo');
var Control = require('esui/Control');
var painters = require('esui/painters');
var $ = require('jquery');
var previewHelper = require('./helper/previewHelper');
require('./FlashObject');
require('esui/Dialog');
var LightBox = eoo.create(
Control,
{
/**
* 资源预览弹出框控件
*
* @extends Control
* @constructor
*/
constructor: function () {
this.$super(arguments);
this.dialog = null;
},
type: 'LightBox',
/**
* 初始化配置
*
* @protected
* @override
*/
initOptions: function (options) {
var properties = {
currentIndex: 0,
width: 'auto',
height: 'auto',
dialogVariants: 'lightbox',
loadingStyle: this.helper.getPartClassName('media-loading'),
loadFailedStyle: this.helper.getPartClassName('media-load-failed'),
group: null,
groupContainerId: null
};
u.extend(properties, LightBox.defaultProperties, options);
this.setProperties(properties);
},
/**
* 初始化DOM结构
*
* @protected
* @override
*/
initStructure: function () {
var properties = {
content: '',
closeButton: true,
mask: true,
alwaysTop: true,
closeOnHide: false,
width: 'auto'
};
u.extend(
properties,
{
title: this.title || '',
foot: this.foot || '',
draggable: this.draggable || false,
needfoot: this.needfoot || false,
variants: this.dialogVariants
}
);
var dialog = esui.create('Dialog', properties);
dialog.appendTo(document.body);
this.dialog = dialog;
},
/**
* 初始化事件交互
*
* @protected
* @override
*/
initEvents: function () {
this.initCarousel();
var leftLink = lib.g(this.dialog.helper.getId('link-left'));
var rightLink = lib.g(this.dialog.helper.getId('link-right'));
var me = this;
this.dialog.helper.addDOMEvent(
leftLink,
'click',
function (e) {
me.showPreviousMedia();
}
);
this.dialog.helper.addDOMEvent(
rightLink,
'click',
function (e) {
me.showNextMedia();
}
);
this.dialog.on('close', function () {
$(this.mediaContainer()).html('');
}, this);
if (this.group) {
var container = this.groupContainerId ? lib.g(this.groupContainerId) : document.body;
me.helper.addDOMEvent(
container,
'click',
'[data-lightbox-group]',
function (e) {
var target = e.currentTarget;
e.preventDefault();
var $groupElements = $(container).find('[data-lightbox-group="' + me.group + '"]');
var i = $groupElements.index(target);
var datasource = [];
$groupElements.each(function (i, element) {
var $el = $(element);
var item = {
url: $el.attr('href')
};
var dataType = $el.attr('data-lightbox-type');
item.width = $el.attr('data-lightbox-width');
item.height = $el.attr('data-lightbox-height');
dataType && (item.type = dataType);
datasource.push(item);
});
me.datasource = datasource;
me.show({
currentIndex: i
});
}
);
}
},
/**
* 初始化图片/视频轮播
*
* @protected
*/
initCarousel: function () {
var tpl = [
'<div id="${mediaId}" class="${mediaStyle}"></div>',
'<div id="${linkId}" class="${linkStyle}">',
'<a href="javascript:;" id="${leftLinkId}" class="${leftLinkStyle}"></a>',
'<a href="javascript:;" id="${rightLinkId}" class="${rightLinkStyle}"></a>',
'</div>'
].join('');
var body = this.dialog.getBody();
var dialogHelper = this.dialog.helper;
var leftIcon = dialogHelper.getPartClassName('lightbox-content-link-left')
+ ' '
+ dialogHelper.getIconClass();
var rightIcon = dialogHelper.getPartClassName('lightbox-content-link-right')
+ ' '
+ dialogHelper.getIconClass();
body.setContent(
lib.format(
tpl,
{
mediaId: dialogHelper.getId('media'),
mediaStyle: dialogHelper.getPartClassName('lightbox-content-media'),
linkId: dialogHelper.getId('link'),
linkStyle: dialogHelper.getPartClassName('lightbox-content-link'),
leftLinkId: dialogHelper.getId('link-left'),
leftLinkStyle: leftIcon,
rightLinkId: dialogHelper.getId('link-right'),
rightLinkStyle: rightIcon
}
)
);
},
mediaContainer: function () {
return lib.g(this.dialog.helper.getId('media'));
},
/**
* 显示图片/视频对话框容器
*
* @param {Object} args 显示对话框时传入的参数
* @protected
*/
show: function (args) {
args && this.setProperties(args);
var link = lib.g(this.dialog.helper.getId('link'));
link.style.display = this.datasource.length <= 1 ? 'none' : '';
this.showMedia();
},
/**
* 隐藏图片/视频对话框容器
*
* @protected
*/
hide: function () {
this.dialog.hide();
},
/**
* 填充内容
*
* @param {Array} list 图片或视频数据列表
* @protected
*/
setContent: function (list) {
this.setProperties(
{
datasource: list
}
);
},
/**
* 显示图片/视频
*
* @protected
*/
showMedia: function () {
var data = this.datasource[this.currentIndex];
this.showLoading();
if (!data.type) {
if (/\.(?:jpg|png|gif|jpeg|bmp)$/i.test(data.url)) {
data.type = 'image';
}
else if (/\.swf/i.test(data.url)) {
data.type = 'flash';
}
else if (/\.(?:mp4|flv|mov|mkv|mpg|avi|rmvb|rm|ogg|wmv|mp3|wma|mid)/i.test(data.url)) {
data.type = 'video';
}
}
this.preview(data);
},
/**
* 显示加载状态
*
* @protected
*/
showLoading: function () {
$(this.dialog.main).addClass(this.helper.getPartClassName('loading'));
},
/**
* 取消加载状态
*
* @protected
*/
hideLoading: function () {
$(this.dialog.main).removeClass(this.helper.getPartClassName('loading'));
},
/**
* 预览图片/视频/flash
*
* @protected
* @param {Object} options 预览参数
*/
preview: function (options) {
if (options) {
if (options.type === 'flv') {
options.type = 'video';
}
var type = options.type;
options.id = options.id || 'preiew-' + Math.random();
options.width = options.width || this.width;
options.height = options.height || this.height;
type = type.charAt(0).toUpperCase() + type.slice(1).toLowerCase();
(this['preview' + type] || this.previewNotSupported).call(this, options);
}
},
/**
* 预览图片
*
* @param {Object} options 图片数据
* @protected
*/
previewImage: function (options) {
var me = this;
options.width += 'px';
options.height += 'px';
var img = previewHelper.preview(options);
img.onload = function () {
me.hideLoading();
me.mediaContainer().innerHTML = '';
me.mediaContainer().appendChild(img);
me.dialog.show();
img.onload = img.onerror = null;
};
img.onerror = function () {
me.hideLoading();
me.mediaContainer().innerHTML = lib.format(this.LOAD_FAILED_TPL, me);
img.onload = img.onerror = null;
me.dialog.show();
};
},
/**
* 预览Flash
*
* @param {Object} options flash数据
* @protected
*/
previewFlash: function (options) {
var flashObj = previewHelper.preview(options);
if (!flashObj) {
this.previewNotSupported();
return;
}
this.hideLoading();
this.mediaContainer().innerHTML = '';
this.addChild(flashObj, 'FlashObject');
flashObj.appendTo(this.mediaContainer());
this.dialog.show();
},
/**
* 预览视频
*
* @param {Object} options 视频数据
* @protected
*/
previewVideo: function (options) {
var url = options.url;
var html = '';
if (/\.flv/.test(url)) {
options.type = 'flv';
}
else if (/\.mp4|\.mov/.test(url)) {
options.type = 'video';
}
options.swfPath = this.swfPath;
html = previewHelper.preview(options);
if (!html) {
this.previewNotSupported();
return;
}
var $container = $(this.mediaContainer());
this.hideLoading();
$container.html('');
if (typeof html === 'string') {
$container.append($(html));
}
else if (html.getCategory) {
this.addChild(html, 'VideoObject');
html.appendTo($container[0]);
}
this.dialog.show();
},
previewNotSupported: function () {
this.hideLoading();
this.mediaContainer().innerHTML = this.NOT_SUPPORT_MESSAGE;
this.dialog.show();
},
/**
* 显示下一个图片/视频
*
* @protected
*/
showNextMedia: function () {
this.currentIndex = ++this.currentIndex % this.datasource.length;
this.showMedia();
},
/**
* 显示上一个图片/视频
*
* @protected
*/
showPreviousMedia: function () {
this.currentIndex = (--this.currentIndex + this.datasource.length) % this.datasource.length;
this.showMedia();
},
/**
* 重渲染
*
* @method
* @protected
* @override
*/
repaint: painters.createRepaint(
Control.prototype.repaint,
{
name: ['title'],
paint: function (control, title) {
control.dialog.setTitle(title || '');
}
}
)
}
);
LightBox.defaultProperties = {
NOT_SUPPORT_MESSAGE: '暂不支持该格式预览',
LOAD_FAILED_TPL: '<div class="${loadFailedStyle}">加载图片失败</div>'
};
esui.register(LightBox);
return LightBox;
});
|
yanghuabei/ub-ria-ui
|
src/LightBox.js
|
JavaScript
|
bsd-2-clause
| 14,597
|
"use strict";
const Ajv2020 = require("ajv/dist/2020");
const addFormats = require("ajv-formats");
var ajv = new Ajv2020({ strict: false });
addFormats(ajv);
var fs = require('fs');
var http = require('http');
var jsonlint = require('jsonlint');
var selectObjectFromJson = require('./selectObjectFromJson');
var localize = require('ajv-i18n');
var validate = function() { return false; }
var languages = {
"en" : localize.en,
"de" : localize.de
}
function doValidate(json, validated_version, file, success, failure, language) {
var retval = false;
var version = json.X3D["@version"];
var error = ""
var chosenLanguage = languages[language];
if (typeof validated_version !== 'undefined') {
var valid = validated_version(json);
if (!valid) {
chosenLanguage(validated_version.errors);
console.error("================================================================================");
console.error("File:", file);
var errs = validated_version.errors;
for (var e in errs) {
error += "\r\n keyword: " + errs[e].keyword + "\r\n";
var instancePath = errs[e].instancePath.replace(/^\./, "").replace(/[\.\[\]']+/g, " > ").replace(/ >[ \t]*$/, "");
error += " instancePath: " + instancePath+ "\r\n";
/*
var selectedObject = selectObjectFromJson(json, instancePath);
error += " value: " + JSON.stringify(selectedObject,
function(k, v) {
var v2 = JSON.parse(JSON.stringify(v));
if (typeof v2 === 'object') {
for (var o in v2) {
if (typeof v2[o] === 'object') {
v2[o] = "|omitted|";
}
}
}
return v2;
}) + "\r\n";
*/
error += " message: " + errs[e].message + "\r\n";
error += " params: " + JSON.stringify(errs[e].params) + "\r\n";
error += " file: " + file + "\r\n";
error += " version: " + version + "\r\n";
}
failure(error);
} else {
if (typeof success == 'function') {
success();
} else {
failure("No success function");
}
}
} else {
failure("Schema not loaded");
}
}
function loadSchema(json, file, doValidate, success, failure, language) {
var versions = { "4.0":true }
var version = json.X3D["@version"];
if (!versions[version]) {
console.error("Can only validate version 4.0 presently. Switching version to 4.0.");
version = "4.0";
}
var validated_version = validate[version];
if (typeof validated_version === 'undefined') {
/*
console.error("Loading meta schema");
var metaschema = fs.readFileSync('draft-07-JSONSchema.json');
console.error("Parsing meta schema");
var metaschemajson = JSON.parse(metaschema.toString());
console.error("Adding meta schema");
ajv.addMetaSchema(metaschemajson);
*/
console.error("Loading schema");
var schema = fs.readFileSync("x3d-"+version+"-JSONSchema.json");
// var schema = fs.readFileSync("X3dXml4.0SchemaConvertedToJson2020-12Schema.json");
console.error("Parsing schema");
var schemajson = JSON.parse(schema.toString());
console.error("Adding schema");
ajv.addSchema(schemajson);
console.error("Schema", version, "added");
validated_version = ajv.compile(schemajson);
validate[version] = validated_version;
if (typeof validated_version === 'undefined') {
console.error("Schema", version, "not compiled");
} else {
console.error("Schema", version, "compiled");
}
doValidate(json, validated_version, file, success, failure, language);
} else {
doValidate(json, validated_version, file, success, failure, language);
}
}
function validateJSON(language, files) {
for (var f in files) {
var file = files[f];
var str = fs.readFileSync(file).toString();
if (typeof str === 'undefined') {
throw("Read nothing, or possbile error");
}
try {
var json = jsonlint.parse(str);
var version = json.X3D["@version"];
loadSchema(json, file, doValidate, function() {
console.error("Success reading", file);
}, function(e) {
console.error("Error reading", file, e);
}, language);
} catch (e) {
console.error("================================================================================");
console.error("File:", file);
console.error(e);
}
}
}
function exchangeajvmessage(msg) {
var str = fs.readFileSync("wordMap2.json").toString();
var json = jsonlint.parse(str);
var newString="";
var object = json;
var k=0;
var flag=false;
var begin,value,values=[],m=0;
for (var i=0; i < msg.length ; i++) {
newString+=msg[i];
if ( newString=="" && object[newString].prototype.keys()[0]=="(*)" && !flag) {
object=object[newString];
flag=true;
begin=i;
}
if (flag) {
if (msg[i]==' ') {
newString="";
}
value+=msg[i];
}
if (object[newString]!=undefined) {
object=object[newString];
newString="";
i++;
k++;
values.push(value);
flag=false;
m=i;
}
}
return object['en'] + '' + ',to stand X3D json validation requirements.'+ values[0]+ ' ' + values[1];
}
//alx:
//console.log('alx: '+exchangeajvmessage('should NOT have 123 then abc'));
module.exports = validateJSON
|
coderextreme/x3dvalidate
|
index.js
|
JavaScript
|
bsd-2-clause
| 5,702
|
jaxon.dialogs.jconfirm = {
dialog: null,
show: function(args) {
// Add buttons
for(key in args.data.buttons)
{
button = args.data.buttons[key];
if(button.action == "close")
{
button.action = function(){jaxon.dialogs.jconfirm.dialog.close();};
}
else
{
button.action = new Function(button.action);
}
}
args.data.closeIcon = true;
if((jaxon.dialogs.jconfirm.dialog))
{
jaxon.dialogs.jconfirm.dialog.close();
}
jaxon.dialogs.jconfirm.dialog = $.confirm(args.data);
},
hide: function(args) {
if((jaxon.dialogs.jconfirm.dialog))
{
jaxon.dialogs.jconfirm.dialog.close();
}
jaxon.dialogs.jconfirm.dialog = null;
},
success: function(content, title) {
$.alert({content: content, title: title, type: 'green', icon: 'fa fa-success'});
},
info: function(content, title) {
$.alert({content: content, title: title, type: 'blue', icon: 'fa fa-info'});
},
warning: function(content, title) {
$.alert({content: content, title: title, type: 'orange', icon: 'fa fa-warning'});
},
error: function(content, title) {
$.alert({content: content, title: title, type: 'red', icon: 'fa fa-error'});
},
confirm: function(question, title, yesCallback, noCallback) {
if(noCallback == undefined)
noCallback = function(){};
$.confirm({
title: title,
content: question,
buttons: {
yes: {
btnClass: "btn-blue",
text: "<?php echo $this->yes ?>",
action: yesCallback
},
no: {
text: "<?php echo $this->no ?>",
action: noCallback
}
}
});
}
};
|
jaxon-php/jaxon-dialogs
|
templates/jqueryconfirm/alert.js
|
JavaScript
|
bsd-3-clause
| 1,990
|
//= require spree/frontend/instagram_feed
function Home() {
var $window, link_el, links, $resize_me, $get;
$window = $(window),
links = document.querySelector('#home').querySelectorAll('a'),
$resize_me = $('.resize-me'),
$video_wrap = $('.video-wrap', '#home'),
$get = $('.get-ratio img:visible').first();
for(var i = 0; i < links.length; i++) {
sanitize_link(links.item(i));
}
$window.on('resize load', function(){
requestAnimationFrame(resize_video);
});
$(function(){
resize_video();
});
new InstagramFeed('.instagram-feed');
var $images = $('img:visible', '#home'),
countdown = $images.length;
$images.each(function(index, el) {
$(el).on('load', function() {
countdown--;
console.log(countdown--, index, el);
if(countdown === 0)
$window.trigger('uiRequestFadeInContent');
// alert('hai');
});
});
setTimeout(function(){ $window.trigger('uiRequestFadeInContent') }, 2000);
function sanitize_link(link_el) {
if(link_el.href !== '' && window.location.host !== link_el.host)
link_el.target = "_blank"
}
function resize_video() {
$video_wrap.css({
'width' : $get.width(),
'height': $get.height()
});
}
}
|
human-nyc/spree_obesityandspeed
|
app/assets/javascripts/spree/frontend/home.js
|
JavaScript
|
bsd-3-clause
| 1,248
|
function Consultas() {
this._consultas = [];
}
Consultas.prototype = {
agregarConsulta: function(consulta,callback) {
this._consultas.push(consulta);
callback.onSuccess();
},
sacarConsulta: function(callback) {
if(!this._consultas.length)
{
callback.onError();
}
else
{
var consulta = this._consultas.pop();
callback.onSuccess(consulta);
}
},
getConsultas: function() {
return this._consultas;
}
}
module.exports = Consultas;
|
juanmjacobs/iasc
|
consultas.js
|
JavaScript
|
bsd-3-clause
| 501
|
import React from 'react';
const NotFound = () => (
<div>
<h1>The page you requested is not available</h1>
</div>
);
export default NotFound;
|
dhanushuUzumaki/Journal
|
react-client/src/components/NotFound.js
|
JavaScript
|
bsd-3-clause
| 152
|
$.datepicker.setDefaults($.datepicker.regional[document.documentElement.lang]);
var getval = function (val) {
if ((typeof(val) === 'object') && val && val.id) return val.id;
else if ((val == null) || (val == '')) return null;
else return val;
};
var extraMods = [];
if (window.ngKeopsExtraModules) extraMods = window.ngKeopsExtraModules;
var keopsApp = angular.module('keopsApp', ['ngRoute', 'ngCookies', 'ngSanitize', 'ui.validate', 'ui.erp', 'ui.bootstrap', 'ui.mask'].concat(extraMods), function ($routeProvider, $locationProvider, $httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
}).config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/content/show/:app/:content/', {
templateUrl: function (params) {
var u = '/client/content/show/' + params.app + '/' + params.content + '/';
if (params.mode)
u += '?' + $.param({mode: params.mode});
return u;
}
})
.when('/', {
templateUrl: '/client/home/dashboard/'
})
}
]).run(['$http', '$cookies', function ($http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
}]);
// SharedData factory
keopsApp.factory('SharedData', function ($rootScope, $sce, $timeout) {
var sharedData = {alerts: []};
sharedData.addAlert = function (type, msg) {
msg = $sce.trustAsHtml(msg);
console.log(msg);
if (type == 'error') type = 'danger';
sharedData.alerts.push({
type: type, msg: msg, timer: $timeout(function () {
sharedData.alerts.splice(0, 1);
}, 10000)
});
};
sharedData.closeAlert = function (index) {
var alert = sharedData.alerts[index];
$timeout.cancel(alert.timer);
$rootScope.alerts.splice(index, 1);
};
return sharedData;
});
// List factory/controller
keopsApp.factory('List', function ($http, SharedData, $location) {
var List = function () {
this.items = [];
this.loading = false;
this.start = 0;
this.total = null;
this.loaded = false;
this.index = 0;
this.selection = 0;
this.selItems = [];
SharedData.list = this;
};
List.prototype.nextPage = function (query) {
if (this.loading || this.loaded) return;
this.loading = true;
var params = {
p: this.start,
l: 25
};
if (query) params['q'] = query;
var url = "/api/content/" + this.model.replace('.', '/') + '/';
if (this.total === null) {
params['t'] = 1;
params['p'] = 1;
}
$http({
url: url,
method: 'GET',
params: params
}).success(function (data) {
this.total = data.total;
rows = data.items;
for (var i = 0; i < rows.length; i++)
this.items.push(rows[i].data);
this.start = this.items.length;
this.loading = false;
this.loaded = this.items.length == this.total;
}.bind(this));
};
List.prototype.query = function (query) {
this.q = query;
this.total = null;
this.start = 0;
this.loaded = false;
this.items = [];
this.nextPage(query);
};
List.prototype.deleteSelection = function () {
if (confirm("Confirma a exclusão do(s) registro(s) selecionado(s)?")) {
var delItems = [];
var selItems = this.selItems;
var items = this.items;
var self = this;
for (var i = 0; i < this.selItems.length; i++) {
var row = this.selItems[i];
delItems.push(row.id);
}
var params = {model: this.model, id: delItems};
$http({
url: '/api/content/' + this.model.replace('.', '/') + '/',
method: 'DELETE',
params: params
}).success(function (data) {
if (data.success) {
SharedData.addAlert("success", data.message);
for (var i=0;i<selItems.length;i++) {
items.splice(items.indexOf(selItems[i]), 1);
}
selItems.length = 0;
self.selection = 0;
}
});
}
};
List.prototype.init = function (model, q) {
this.model = model;
this.query(q);
};
List.prototype.itemClick = function (item, search, index) {
if (item.id) $location.search({mode: 'form', id: item.id});
};
return List;
});
keopsApp.controller('AppController', function ($scope, $rootScope, $location, SharedData, $http) {
$scope.alerts = SharedData.alerts;
$scope.authenticate = function (user, password) {
$http({
method: 'POST',
url: '/api/auth/login/',
headers: {'Content-Type': 'application/json'},
data: { user: user, password: password }
}).success(function (data) {
if (!angular.isDefined($scope.alerts)) $scope.alerts = [];
else $scope.alerts.splice(0, $scope.alerts.length);
if (data.success) {
$scope.alerts.push({ type: 'success', message: katrid.gettext('Please wait, redirecting page...')});
window.location.href = '/';
}
else $scope.alerts.push({ type: 'danger', 'message': data.message });
});
}
});
keopsApp.controller('ListController', function ($scope, $location, List) {
$scope.list = new List();
$scope.itemClick = function (url, search, index) {
window.location.href = $scope.controllerUrl + url;
};
$scope.toggleCheckAll = function () {
var c = $('#action-toggle')[0].checked;
$('.action-select').each(function () {
$(this).checked = true;
$(this).prop('checked', c);
});
$scope.list.selection = $('.action-select:checked').length;
if (c)
$scope.list.selItems = $scope.list.items;
else
$scope.list.selItems = [];
};
$scope.selectItem = function (item) {
if (item) {
var idx = $scope.list.selItems.indexOf(item);
if (idx === -1)
$scope.list.selItems.push(item);
else
$scope.list.selItems.splice(idx, 1);
}
$('#action-toggle').prop('checked', $('.action-select:not(:checked)').length === 0);
$scope.list.selection = $('.action-select:checked').length;
};
$scope.goto = function (url, target) {
window.location.href = url;
};
$scope.newItem = function () {
var params = $location.search();
params['mode'] = 'form';
params['state'] = 'new';
$location.search(params);
};
$scope.showForm = function (id) {
var params = $location.search();
params['mode'] = 'form';
params['id'] = id;
$location.search(params);
}
});
// Form factory/controller
keopsApp.factory('Form', function ($http, SharedData, $location, $routeParams) {
var Form = function () {
this.data = {};
this.item = {};
this.subItems = {};
this.children = [];
this.deleted = [];
this.loading = false;
this.start = -1;
this.total = null;
this.loaded = false;
this.write = false;
this.model = null;
this.element = null;
this.readonly = null;
this.state = null;
this.pk = $location.search().id;
this.url = "/api/content/";
if (SharedData.list) {
this.start = SharedData.list.index - 1;
this.total = SharedData.list.total;
}
};
Form.prototype.addChild = function (obj) {
this.children.push(obj);
};
Form.prototype.addSubItem = function (obj) {
var cf = obj.name;
if (!this.subItems[cf]) this.subItems[cf] = [];
var s = this.subItems[cf];
if (s.indexOf(obj) === -1) s.push(obj);
};
Form.prototype.removeSubItem = function (obj) {
var cf = obj.name;
if (!this.subItems[cf]) this.subItems[cf] = [];
var s = this.subItems[cf];
if (s && (s.indexOf(obj))) s.splice(s.indexOf(obj), 1);
};
Form.prototype.newItem = function (pk) {
var params = {model: this.model};
var url = '/db/read';
if (pk) {
params['action'] = 'duplicate_selected';
params['pk'] = pk;
}
$http({
method: 'POST',
url: url,
params: params
}).success(function (data) {
this.write = true;
this.item = data;
this.item.__str__ = katrid.gettext('<New>')
}.bind(this));
};
Form.prototype.loadFormset = function (field) {
if (this.pk) {
var fname = field.split('.');
var m, f;
if (fname.length === 1) {
m = this.model + '.' + fname[0];
} else {
m = fname[0] + '.' + fname[1];
f = fname[2];
}
var vData = [];
this.subitems[field.replace(/\./g, '_')] = vData;
var params = {model: m, field: f, pk: this.pk};
var url = '/db/read/';
/*$http({
method: 'GET',
url: url,
params: params
}).success(function (data) {
for (var i in data.items) {
var d = data.items[i].data;
d.__model__ = m;
vData.push(d);
}
}.bind(this));*/
}
};
Form.prototype.nextPage = function () {
if (this.loading || this.loaded) return;
this.loading = true;
var model = this.model;
var url = this.url + model.replace('.', '/') + '/';
var params = {mode: 'form'};
if (this.state === 'new') params.state = 'new';
else if (this.pk) params.id = this.pk;
$http({
method: 'GET',
url: url,
params: params
}).success(function (data) {
this.data = data.items[0].data;
if (this.state === 'new') {
var d = data.items[0].data;
for (var i in d) if (this.scope.dataForm[i]) this.scope.dataForm[i].$setDirty();
}
var id = data.items[0].id;
if (!this.pk) $location.search('id', id);
this.pk = id;
this.loading = false;
this.loaded = this.start == this.total - 1;
//this.masterChangeNotification();
delete SharedData.list;
}.bind(this));
};
Form.prototype.prevPage = function () {
if (this.start === 0) return;
this.loading = true;
this.loaded = false;
var model = this.model;
this.start--;
var url = this.url + 'p=' + this.start;
$http.get(url).success(function (data) {
if (this.total === null) this.total = data.total;
this.item = data.items[0];
$location.search('pk', this.item.pk);
this.loading = false;
//this.masterChange();
}.bind(this));
};
Form.prototype.masterChangeNotification = function () {
// notify nested form remote items
var formItem = this.item;
formItem.subItems = {};
var items = this.element.find('[remote]');
var remoteitems = [];
for (var i = 0; i < items.length; i++) remoteitems.push(angular.element(items[i]).attr('name'));
// make params
var data = {model: this.model, pk: this.item.pk, items: angular.toJson(remoteitems)};
// load remote data
$http({
method: 'GET',
url: '/db/read/items',
params: data
}).
success(function (data) {
for (var i = 0; i < items.length; i++) {
var item = angular.element(items[i]);
var name = item.attr('name');
if (data[name].items) formItem[name] = data[name].items;
else formItem[name] = data[name];
}
});
};
Form.prototype.cancel = function () {
this.write = false;
this.refresh();
};
Form.prototype.refresh = function () {
var pk = $location.search()['pk'];
if (pk)
$http({
method: 'GET',
url: '/db/read',
params: {limit: 1, model: this.model, pk: $location.search()['pk']}
}).success(function (data) {
jQuery.extend(this.item, data.items[0]);
this.masterChange();
}.bind(this));
};
Form.prototype.getGridFields = function () {
var items = this.element.find('[grid-field]');
var r = {};
// check item changes
for (var i = 0; i < items.length; i++) {
var item = angular.element(items[i]);
var name = item.attr('name');
r[name] = this.item[name];
}
;
return r;
};
Form.prototype.getNestedForm = function (data) {
var r = {};
var b = false;
if (data.$name)
for (var i in data) {
if (i[0] !== '$') {
var v = data[i];
if (v.$modelValue !== undefined) {
r[i] = v.$modelValue;
b = true;
}
}
}
if (b) {
var fname = data.$name.split('.');
var model = fname[0] + '.' + fname[1];
var field = fname[2];
r['__model__'] = model;
r['__key__'] = field;
r[field] = null;
return r;
}
};
Form.prototype.deleteItem = function (data, index) {
if (confirm("Confirma a exclusão do item?")) {
item = data[index];
if (item.pk)
this.deleted.push(item);
data.splice(index, 1);
}
};
Form.prototype.init = function (model) {
this.model = model;
var src = $location.search();
if ($routeParams["id"]) this.pk = $routeParams["id"];
else this.pk = $location.search()["id"];
if (src.state === 'new') this.state = 'new';
this.nextPage();
};
return Form;
});
keopsApp.controller('FormController', function ($scope, $http, Form, $location, $element, $modal, $timeout, $sce, SharedData) {
$scope.form = new Form();
$scope._counters = {};
$scope.form.scope = $scope;
$scope.form.element = $element;
$scope.search = function (url, search) {
$location.path(url).search(search);
};
$scope.lookupData = function (url, model, query) {
var promise = $http({
method: 'GET',
url: url,
params: {query: query, model: model}
})
.then(function (response) {
return response.data;
});
promise.$$v = promise;
return promise;
};
$scope.openResource = function (url, search) {
$location.path(url).search(search).replace();
};
$scope.fieldChangeNotification = function (field) {
var data = this.collectData(false, false);
$http({
method: 'POST',
url: '/api/change/' + $scope.form.model.replace('.', '/') + '/',
params: {field: field},
headers: {'Content-Type': 'application/json'},
data: data
}).
success(function (data) {
//jQuery.extend($scope.form.item, data.values);
});
};
$scope.showDetail = function (model, detail, item) {
var field = $scope.form.item[detail];
var options = {
controller: 'DialogController',
resolve: {
data: function () {
form = {item: {}}
if (item) {
jQuery.extend(form.item, item);
form.ref = item;
}
form.field = field;
form.instance = $scope.form;
return form;
}
},
templateUrl: '/admin/detail/?model=' + model + '&field=' + detail
};
var dialog = $modal.open(options);
dialog.result.then(function (form) {
form.instance.nestedDirty = true;
if (form.ref) {
if (!form.item.__state__) form.item.__state__ = 'modified';
jQuery.extend(form.ref, form.item);
}
else {
form.item.__state__ = 'created';
form.field.push(form.item);
}
}, function () {
});
};
$scope.confirmDelete = function (message) {
var options = {
controller: 'DialogController',
resolve: {
data: function () {
return $scope.form;
}
},
templateUrl: '/static/katrid/html/confirm_delete.html'
};
var dialog = $modal.open(options);
dialog.result.then(function (form) {
$http({
method: 'POST',
url: '/admin/action/?action=delete_selected',
params: {pk: form.item.pk, model: form.model}
}).success(function (data) {
for (var i in data) {
var i = data[i];
SharedData.addAlert(i.alert, i.message);
}
if (data[data.length - 1].success) $scope.form.nextPage();
}).error(function (data) {
window.open('error').document.write(data);
});
}, function () {
});
};
$scope.sum = function (item, attr) {
var r = 0;
if (item)
for (var i=0;i<item.length;i++) {
var obj = item[i];
r += obj[attr] || 0;
}
return r;
};
$scope.tableRowFilter = function (obj) {
return obj.__state__ !== 'deleted';
};
$scope.collectData = function (dirtyOnly, validOnly) {
var form = this.dataForm;
if (validOnly && !form.$valid) return;
var data = {};
// formset items
var getSubItemObj = function (self, nm) {
var subitem = self.form.data[nm];
var r = [];
if (subitem.length)
for (var i = 0; i < subitem.length; i++) {
var s = subitem[i];
var obj = {};
var modified = false;
var frm = form[nm + '-' + i.toString()];
if (frm) {
for (var x in s) if (x[0] !== '$') {
var f = frm[x];
//if (f && f.$dirty) obj[x] = f.$modelValue;
modified = true;
// TODO apply modified fields only
if (f) obj[x] = getval(f.$modelValue);
}
if (frm.id) obj.id = frm.id.$modelValue;
}
if (modified) r.push(obj);
}
if (r.length) return r;
};
// save data
for (var i in this.form.data) {
var field = form[i];
if (field && (!dirtyOnly || field.$dirty)) data[i] = getval(field.$modelValue);
// check children (formsets)
else if (this.form.children.indexOf(i) > -1) {
s = getSubItemObj(this, i);
if (s) data[i] = s;
}
}
// grid items
var subItems = this.form.subItems;
var collect = function (obj) {
if (obj.op === 'delete') return obj;
var r = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (i[0] !== '_') r[i] = obj[i];
}
}
if (obj._modifiedFields.length) {
var data = {};
for (var i in obj._modifiedFields) {
var s = obj._modifiedFields[i];
data[s] = getval(obj.data[s]);
}
r.data = data;
return r;
}
};
for (i in subItems) {
var rows = subItems[i];
var items = [];
for (var x=0;x<rows.length;x++) {
var childObj = collect(rows[x]);
if (childObj) items.push(childObj);
}
if (items.length) data[i] = items;
}
if (this.form.pk) data['id'] = this.form.pk;
return [data];
};
$scope.submit = function () {
$scope.dataForm.$setSubmitted();
if (!$scope.dataForm.$valid) return false;
var data = this.collectData(true, true);
var postUrl = '/api/content/' + this.form.model.replace('.', '/') + '/';
var params = {};
console.log(data);
return $http({
method: 'POST',
url: postUrl,
data: data,
headers: {'Content-Type': 'application/json'},
params: params
}).success(function (data) {
if (data.success) $scope.showList();
});
/* var i, item;
var form = this.dataForm;
if (form.$dirty) {
var data = {};
for (i in form) {
item = form[i];
if ((i[0] !== '$') && (i.indexOf('.') === -1) && item.$dirty) {
data[i] = item.$modelValue;
}
}
};
if (data || this.form.deleted.length) {
//var nested = $element.find('[ng-form]');
// check item changes
data = { data: data, nested: [] }
for (i in this.form.deleted) {
data.nested.push({ pk: this.form.deleted[i].pk, __action__: 'delete', __model__: this.form.deleted[i].__model__ });
}
for (i in form) {
item = form[i];
if (item && item.$$parentForm && item.$dirty) {
data.nested.push(this.form.getNestedForm(item));
}
}
var postUrl = '/api/content/' + this.form.model.replace('.', '/') + '/';
var params = {};
if ($scope.form.data && this.form.data.pk) params['id'] = this.form.data.pk;
return $http(
{
url: postUrl,
data: data,
params: params
}
).success(function (data, status, headers, config) {
if (data.success) {
console.log(data.message);
SharedData.addAlert('success', data['message']);
if ($scope.backUrl) window.location.href = $scope.backUrl;
else {
var params = $location.search();
params['mode'] = 'list';
$location.search(params);
}
}
}.bind(this)).
error(function (data) {
window.open('error').document.write(data);
});
}
else {
SharedData.addAlert('warning', 'Não existem dados penendetes de gravação!');
var search = $location.search();
search['mode'] = 'list';
$location.search(search);
}*/
};
$scope.adminAction = function (action, data) {
$scope.alerts.length = 0;
var params = {model: this.model};
var url = '/admin/action/';
var pk = this.form.pk;
params['action'] = action;
params['pk'] = this.form.pk;
params['model'] = this.form.model;
params['data'] = data;
$http.post(url, params).success(function (data) {
$scope._evalData(data);
});
};
$scope._evalData = function (data) {
for (var i in data) {
i = data[i];
var s = i.message;
if (i.success && (typeof i.message === 'object')) {
$scope.form.nestedDirty = false;
form.$setPristine();
$scope.form.write = false;
jQuery.extend($scope.form.item, data.data);
}
else if (!i.success) {
$scope.addAlert(i.alert, s);
}
else $scope.addAlert(i.alert, s);
}
};
$scope.showList = function () {
var params = $location.search();
params['mode'] = 'list';
params['id'] = null;
$location.search(params);
}
});
|
katrid/keops
|
keops/static/assets/keops.js
|
JavaScript
|
bsd-3-clause
| 21,503
|
const async = require( 'async' );
// --------------------------------------------------------------------------------------
var exp = {}
// --------------------------------------------------------------------------------------
// perform shared mac counting
// --------------------------------------------------------------------------------------
exp.process_old_data = function (database, callback) {
// find the lowest date in database and go from that date to present
var date;
var current = new Date();
var curr_min = new Date(current.getFullYear(), current.getMonth(), current.getUTCDate(), 0, 0, 0, 0); // current day hh:mm:ss:ms set to 00:00:00:000
// find all, sort by timestamp, display only timestamp, display one document only
database.logs.find({}).sort({"timestamp" : 1}).limit(1).select({"timestamp" : 1, "_id" : 0}).exec(
function(err, doc) {
var date = doc;
date = String(date[0]["timestamp"]); // get only string representation of date
var fields = date.split(" ");
var months = { // months dict for date constructor
"Jan" : 0,
"Feb" : 1,
"Mar" : 2,
"Apr" : 3,
"May" : 4,
"Jun" : 5,
"Jul" : 6,
"Aug" : 7,
"Sep" : 8,
"Oct" : 9,
"Nov" : 10,
"Dec" : 11
}
var min = new Date(fields[3], months[fields[1]], fields[2], 0, 0, 0, 0); // hh:mm:ss:ms set to 0
var max = new Date(fields[3], months[fields[1]], Number(fields[2]) + 1, 0, 0, 0, 0); // next day, hh:mm:ss:ms set to 0
// search uses lower than max condition !
// this date handling should guarantee correct interval for all processed records
async.whilst(function () {
return min < curr_min;
},
function(next) {
async.series([
function(done) {
search(database, min, max, done); // calls done when finished
},
function(done) {
min.setDate(min.getDate() + 1); // continue
max.setDate(max.getDate() + 1); // continue
done(null); // done
}
],
function(err, results) {
next(); // next whilst iteration
});
},
function(err) {
if(err)
console.error(err);
else
console.log("cron task shared_mac finished processing old data");
callback(null, null);
});
});
};
// --------------------------------------------------------------------------------------
// perform shared mac counting
// --------------------------------------------------------------------------------------
exp.process_current_data = function (database) {
var curr = new Date(); // current day
curr.setHours(0);
curr.setMinutes(0);
curr.setSeconds(0);
curr.setMilliseconds(0);
var prev_min = new Date(curr);
prev_min.setDate(prev_min.getDate() -1); // previous day hh:mm:ss:ms set to 00:00:00:000
var prev_max = new Date(curr); // current day hh:mm:ss:ms set to 00:00:00:000
// search uses lower than max condition !
search(database, prev_min, prev_max);
};
// --------------------------------------------------------------------------------------
// perform database search
// --------------------------------------------------------------------------------------
function search(database, min, max, done) {
database.logs.aggregate([
{ $match : {
timestamp : { $gte : min, $lt : max }, // get only data for one day
pn : { $ne : "" }, result : "OK" } }, // match non empty userames and only successfully authenticated users
{ $group : { _id : { username : "$pn", mac_address: "$csi" } } }, // group by pair [ username, mac address ]
// group again only by mac address, add users to array, count number of users
{ $group : { _id : { mac_address : "$_id.mac_address" }, users : { $addToSet : "$_id.username" }, count : { $sum : 1 } } },
{ $match : { count : { $gt : 1 } } }, // match only more than 1 user per 1 mac address
{ $project : { mac_address : "$_id.mac_address", users : 1, count : 1, _id : 0 } } // transform output structure
], function (err, items) {
if(err == null) {
if(done) // processing older data
save_to_db_callback(database, transform(items, min), done);
else // current data processing, no callback is needed
save_to_db(database, transform(items, min)); // add timestamp in transform
}
else
console.error(err);
});
}
// --------------------------------------------------------------------------------------
// save data to database
// --------------------------------------------------------------------------------------
function save_to_db(database, items) {
for(var item in items) { // any better way to do this ?
database.shared_mac.update(items[item], items[item], { upsert : true },
function(err, result) {
if(err)
console.error(err);
});
}
}
// --------------------------------------------------------------------------------------
// save data to database with callback
// --------------------------------------------------------------------------------------
function save_to_db_callback(database, items, done) {
async.forEachOf(items, function (value, key, callback) {
database.shared_mac.update(items[key], items[key], { upsert : true },
function(err, result) {
if(err)
console.error(err);
callback(null); // save next item
});
}, function (err) {
if (err)
console.error(err);
done(null, null); // all items are saved
});
}
// --------------------------------------------------------------------------------------
// transform item structure
// only appends timestamp to record
// --------------------------------------------------------------------------------------
function transform(items, db_date) {
var arr = [];
var dict = {};
for(var item in items) {
var dict = items[item];
dict.timestamp = db_date;
arr.push(dict);
}
return arr;
}
// --------------------------------------------------------------------------------------
module.exports = exp;
|
CESNET/etlog
|
cron/shared_mac.js
|
JavaScript
|
bsd-3-clause
| 6,271
|
/**
* Create France Map
* @param container
* @param width
* @param height
*/
function createViewMapItalia(container, width, height) {
var view = new JenScript.View({
name : container,
width : 800,
height : 800,
holders : 20,
});
var proj = new JenScript.MapProjection({
level : 6,
centerPosition :new JenScript.GeoPosition(42.5,13)
});
view.registerProjection(proj);
var geojsonPlugin = new JenScript.GeoJSONPlugin({});
proj.registerPlugin(geojsonPlugin);
geojsonPlugin.addGeoListener('register', function(event){
console.log('register feature');
var feature = event.feature;
feature.fillColor = JenScript.RosePalette.EMERALD;
feature.fillOpacity = 0.8;
feature.strokeColor = JenScript.RosePalette.CORALRED;
feature.strokeWidth = 1;
//on register you can prepare your feature rendering property
},'map demo');
var transform = new JenScript.AffineTranformPlugin({
slaves : [geojsonPlugin]
});
proj.registerPlugin(transform);
var loader = new MapLoader(['ITA/country-states.json'],function(geoJSON){
geojsonPlugin.addGeoJSON(geoJSON);
});
var outline = new JenScript.DeviceOutlinePlugin({
color : 'black'
});
proj.registerPlugin(outline);
geojsonPlugin.addGeoListener('press', function(event){
console.log('press '+event.type);
//on event you can remote your feature
var remote = event.remote;
remote.fill('purple');
remote.fillOpacity(0.4);
remote.stroke('white');
},'map demo');
geojsonPlugin.addGeoListener('release', function(event){
//console.log('release '+event.feature.Id);
},'map demo');
geojsonPlugin.addGeoListener('enter', function(event){
//console.log('enter '+event.feature.Id);
var remote = event.remote;
remote.fill('orange');
remote.fillOpacity(0.4);
remote.stroke('white');
remote.strokeWidth(0.5);
},'map demo');
geojsonPlugin.addGeoListener('exit', function(event){
//console.log('exit '+event.feature.Id);
// var feature = event.feature;
// feature.fillColor = JenScript.RosePalette.TURQUOISE;
// feature.fillOpacity = 0.3;
// feature.strokeColor = JenScript.RosePalette.MANDARIN;
// feature.strokeWidth = 0;
// geojsonPlugin.repaintPlugin();
//or remote
var remote = event.remote;
remote.fill(JenScript.RosePalette.TURQUOISE);
remote.fillOpacity(0.3);
remote.stroke('none');
remote.strokeWidth(0);
},'map demo');
geojsonPlugin.addGeoListener('move', function(event){
var feature = event.feature;
},'map demo');
var images = new JenScript.ImagePlugin({});
images.addImage({x : 650,y: 10, url : '/site/images/flags-iso/shiny/64/IT.png'});
proj.registerPlugin(images);
}
|
sjanaud/jenscript
|
catalog/views/map/map-italia.js
|
JavaScript
|
bsd-3-clause
| 2,767
|
/*
Copyright (c) 2011, Cosnita Radu Viorel <radu.cosnita@1and1.ro>
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 <organization> 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 <COPYRIGHT HOLDER> 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.
*/
/**
* @author Radu Viorel Cosnita
* @version 1.0
* @since 17.11.2011
* @description Module used to provide custom exception that can occur when working
* with errors.
*/
var sys = require("sys");
/**
* Exception thrown when an intent category is missing.
*/
function IntentCategoryNotFound(message) {
this.message = message;
}
sys.inherits(IntentCategoryNotFound, Error);
/**
* Exception thrown when an intent action is missing.
*/
function IntentActionNotFound(message) {
this.message = message;
}
/**
* Exception thrown when an intent provider is missing.
*/
function IntentProviderNotFound(message) {
this.message = message;
}
sys.inherits(IntentActionNotFound, Error);
sys.inherits(IntentCategoryNotFound, Error);
sys.inherits(IntentProviderNotFound, Error);
exports.IntentCategoryNotFound = IntentCategoryNotFound;
exports.IntentActionNotFound = IntentActionNotFound;
exports.IntentProviderNotFound = IntentProviderNotFound;
|
juxtapos/Rain
|
lib/intents/intents_exceptions.js
|
JavaScript
|
bsd-3-clause
| 2,502
|
/**
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
window.WebComponents = window.WebComponents || {};
// process flags
(function(scope){
// import
var flags = scope.flags || {};
var file = 'webcomponents.js';
var script = document.querySelector('script[src*="' + file + '"]');
// Flags. Convert url arguments to flags
if (!flags.noOpts) {
// from url
location.search.slice(1).split('&').forEach(function(o) {
o = o.split('=');
o[0] && (flags[o[0]] = o[1] || true);
});
// from script
if (script) {
for (var i=0, a; (a=script.attributes[i]); i++) {
if (a.name !== 'src') {
flags[a.name] = a.value || true;
}
}
}
// log flags
if (flags.log && flags.log.split) {
var parts = flags.log.split(',');
flags.log = {};
parts.forEach(function(f) {
flags.log[f] = true;
});
} else {
flags.log = {};
}
}
// Determine default settings.
// If any of these flags match 'native', then force native ShadowDOM; any
// other truthy value, or failure to detect native
// ShadowDOM, results in polyfill
flags.shadow = (flags.shadow || flags.shadowdom || flags.polyfill);
if (flags.shadow === 'native') {
flags.shadow = false;
} else {
flags.shadow = flags.shadow || !HTMLElement.prototype.createShadowRoot;
}
// forward flags
if (flags.register) {
window.CustomElements = window.CustomElements || {flags: {}};
window.CustomElements.flags.register = flags.register;
}
// export
scope.flags = flags;
})(WebComponents);
|
rkupniewski/rkupniewski.github.io
|
src/WebComponents/build/boot.js
|
JavaScript
|
bsd-3-clause
| 2,058
|
import { hash } from "../src";
it("replace value with a hash", () => {
expect(
hash(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
)
).toMatchSnapshot();
});
|
newsuk/times-components
|
packages/test-utils/__tests__/hash.test.js
|
JavaScript
|
bsd-3-clause
| 579
|
/*
* Safely prints to the console
*/
/*
(function ($) {
"use strict";
$.fn.stdout = function(){
var message,source,lineNo;
};
}
*/
function stdout(message){
if(window.console){
console.log(message);
}
}
function stdout(message,source){
if(window.console){
if(source){
console.log(source + " : " + message);
} else {
console.log(message);
}
}
}
function stdout(message, source, lineNo){
if(window.console){
if(source){
if(lineNo){
console.log(source + " --> " + lineNo + " : "+ message);
} else {
console.log(source + " : " + message);
}
} else {
console.log(message);
}
}
}
|
SanaMobile/sana.mds
|
src/mds/web/static/web/js/console.js
|
JavaScript
|
bsd-3-clause
| 784
|
var fs = require('fs'),
sys = require('sys');
parser = require('./couchapp/aimpl/_attachments/parser');
var data = fs.readFileSync('resources/sample/braidgroupsX.tex');
var o = parser.parse(data);
sys.puts(JSON.stringify(o, null, 2));
|
davidfarmer/AIMProblemLists
|
scripts/parser-test.js
|
JavaScript
|
bsd-3-clause
| 244
|
var LegendViewBase = require('../base/legend-view-base');
var template = require('./legend-template.tpl');
var ChoroplethLegendView = LegendViewBase.extend({
_getCompiledTemplate: function () {
return template({
colors: this.model.get('colors'),
prefix: this.model.get('prefix'),
suffix: this.model.get('suffix'),
hasCustomLabels: this._hasCustomLabels(),
leftLabel: this.model.get('leftLabel'),
rightLabel: this.model.get('rightLabel')
});
},
_hasCustomLabels: function () {
var leftLabel = this.model.get('leftLabel');
var rightLabel = this.model.get('rightLabel');
return ((leftLabel != null && leftLabel !== '') || (rightLabel != null && rightLabel !== ''));
}
});
module.exports = ChoroplethLegendView;
|
splashblot/cartodb.js
|
src/geo/ui/legends/custom-choropleth/legend-view.js
|
JavaScript
|
bsd-3-clause
| 775
|
/**
* Created by Albo on 11/05/2015.
*/
// gera o conteudo para dados pessoa via ajax
var dadosPessoa = {
aplicarEventos: function () {
dadosPessoa.bindPessoaForm();
},
bindPessoaForm: function () {
$('#pessoa-form').submit(function (e) {
e.preventDefault();
//console.log($('#dados-pessoa').serialize());
$.ajax({
data: $('#pessoa-form').serialize(),
type: 'POST',
url:'/pessoa/dados-pessoa',
success: function (retorno) {
$('#conteudo').html(retorno);
}
});
})
}
}
$(document).ready(function () {
dadosPessoa.aplicarEventos();
});
|
AlboVieira/PA2015
|
public/js/doacao/dados-pessoa.js
|
JavaScript
|
bsd-3-clause
| 726
|
/**
* Created by zhangpeng on 2015/12/1.
*/
var http = require('http');
var querystring = require('querystring');
var util = require('util');
http.createServer(function(req, res){
var post = ''; //定义了一个post变量,用于暂存请求体的信息
req.on('data', function(chunk){ //通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
post += chunk;
});
req.on('end', function(){ //在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
post = querystring.parse(post);
res.end(util.inspect(post));
});
}).listen(3000);
|
duolew/project-zhp
|
Nodejs/model/GET-POST/POST.js
|
JavaScript
|
bsd-3-clause
| 695
|
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/**
* @fileoverview Principal stub for vanadium principals
* @private
*/
var Deferred = require('../lib/deferred');
var BlessingStore = require('./blessingstore');
var verror = require('../gen-vdl/v.io/v23/verror');
/**
* A callback that is called with either an error or a
* [Blessings]{@link module:vanadium.security~Blessings} object.
* @callback module:vanadium.security~Principal~blessingsCb
* @param {Error} err If set, the error that occurred
* @param {module:vanadium.security~Blessings} blessings The blessings result.
*/
/**
* @summary Principal represents an entity capable of making or receiving RPCs.
* @description <p>Principal represents an entity capable of making or receiving
* RPCs. Principals have a unique (public, private) key pair, have blessings
* bound to them and can bless other principals.</p>
* <p>This constructor should not be used explicitly. Instead, use the
* principal property on the [runtime]{@link module:vanadium~Runtime}.
* @constructor
* @property {module:vanadium.security~BlessingStore} blessingStore The
* blessing store.
* @inner
* @memberof module:vanadium.security
*/
function Principal(ctx, controller) {
this._controller = controller;
this._ctx = ctx;
this.blessingStore = new BlessingStore(controller);
}
/**
* <p>Bless binds extensions of blessings held by this principal to
* another principal (represented by its public key).</p>
*
* <p>For example, a principal with the blessings "google:alice"
* and "v23:alice" can bind the blessings "google:alice:friend"
* and "v23:alice:friend" to another principal using:</p>
* <pre>
* bless(ctx, <other public key>, <google:alice, v23:alice>, 'friend', ...)
* </pre>
* @param {module:vanadium.context.Context} ctx The context.
* @param {string} publicKey The public key to bless.
* @param {module:vanadium.security~Blessings} blessing The blessings.
* @param {string} extension The extension for the blessing.
* @param {...module:vanadium.security.Caveat} caveats An array of Caveats to
* restrict the blessing.
* @param {module:vanadium.security~Principal~blessingsCb} cb An optional
* callback that will return the blessing.
* @return {Promise<module:vanadium.security~Blessings>} A promise that will be
* resolved with the blessing.
*/
Principal.prototype.bless = function(ctx, publicKey, blessings,
extension, firstCaveat /*, ...moreCaveats, cb*/) {
// Extract the callback.
var cb;
var args = Array.prototype.slice.call(arguments);
if (args.length > 0 &&
typeof args[args.length - 1] === 'function') {
cb = args[args.length - 1];
args.pop();
}
var def = new Deferred(cb);
// We must have at least one caveat.
if (typeof firstCaveat !== 'object') {
def.reject('At least one caveat must be specified. To bless without ' +
'adding restrictions, use UnconstrainedUseCaveat');
return def.promise;
}
var caveats = args.slice(4);
this._controller.bless(ctx, publicKey, blessings, extension, caveats)
.then(function(blessings) {
def.resolve(blessings);
}).catch(function(err) {
def.reject(err);
});
return def.promise;
};
/**
* BlessSelf creates a blessing with the provided name for this principal.
* @param {module:vanadium.context.Context} ctx The context.
* @param {string} name The name for the blessing.
* @param {...module:vanadium.security.Caveat} caveats An array of Caveats to
* restrict the blessing.
* @param {module:vanadium.security~Principal~blessingsCb} cb An optional
* callback that will return the blessing.
* @return {Promise<module:vanadium.security~Blessings>} A promise that will be
* resolved with the blessing.
*/
Principal.prototype.blessSelf = function(ctx, name /*, ...caveats, cb*/) {
// Extract the callback.
var cb;
var args = Array.prototype.slice.call(arguments);
if (args.length > 0 &&
typeof args[args.length - 1] === 'function') {
cb = args[args.length - 1];
args.pop();
}
var def = new Deferred(cb);
var caveats = args.slice(2);
var controller = this._controller;
controller.blessSelf(ctx, name, caveats)
.then(function(blessings) {
def.resolve(blessings);
}).catch(function(err) {
def.reject(err);
});
return def.promise;
};
/**
* Add the provided blessing as a root.
* @param {module:vanadium.context.Context} ctx The context.
* @param {module:vanadium.security~Blessings} blessings The blessings object.
* @param {module:vanadium~voidCb} cb If provided, the function
* will be called on completion.
* @return {Promise<void>} A promise that will be resolved/reject on completion.
*/
Principal.prototype.addToRoots = function(
ctx, blessings, cb) {
var def;
if (blessings === undefined) {
def = new Deferred(cb);
def.reject(new verror.InternalError(this._ctx,
'Blessings handle not specified'));
return def.promise;
}
return this._controller.addToRoots(ctx, blessings, cb);
};
module.exports = Principal;
|
vanadium/js
|
src/security/principal.js
|
JavaScript
|
bsd-3-clause
| 5,118
|
$(function ()
{
'use strict'
var BentoChat = require('./chat.js');
/**
*
* Set the initial active menu item on page load.
*
*/
var pageRel = window.location.href.split('/').splice(3)[0];
$('.main-navigation a[rel="' + pageRel + '"]').parent('li').addClass('active');
/**
*
* Perform initial load of page-specific JS scripts.
*
*/
if ($('#js').length)
{
$.getScript('/js/' + $('#js').val() + '.js');
}
/**
*
* Handle clicks on the nav sidebar, switching active highlight.
*
*/
var onNavLinkClicked = function(event)
{
$('body').removeClass('maximized-chat');
$(this).parent('li').addClass('active');
$("a:not([rel=" + $(this).attr('rel') + "])").parent('li').removeClass('active');
};
/**
*
* Update content styles and functionality on successful pjax load.
*
*/
var onPjaxSuccess = function(event)
{
if ($('#js').length)
{
$.getScript('/js/' + $('#js').val() + '.js');
$('[title]').tooltip({ placement: 'right' });
}
};
$(document).pjax('a', '.main-content');
$(document).on('pjax:success', onPjaxSuccess);
$(document).on('pjax:start', function () { NProgress.start(); });
$(document).on('pjax:end', function () { NProgress.done(); });
$('.main-navigation a').on('click', onNavLinkClicked);
$('.scroll-container').slimScroll({ height: '100vh' });
$('[title]').tooltip({ placement: 'right' });
$('#chat-maximize').on('click', window.ui.chat.maximize);
$('#chat-font-up').on('click', window.ui.chat.fontSizeUp);
$('#chat-font-down').on('click', window.ui.chat.fontSizeDown);
});
window.ui = {
chat: {
maximize: function (e)
{
e.preventDefault();
$('body').toggleClass('maximized-chat');
},
fontSizeUp: function (e)
{
e.preventDefault();
var size = parseInt($('.chat-messages').css('font-size')) + 3;
$('.chat-messages').css({'font-size': size + 'px'});
if (size > 20)
{
$('.chat-emote.default').each(function () {
this.src = this.src.replace(/\/\d\.0/, '/2.0');
});
}
},
fontSizeDown: function (e)
{
e.preventDefault();
var size = parseInt($('.chat-messages').css('font-size')) - 3;
$('.chat-messages').css({'font-size': size + 'px'});
if (size <= 20)
{
$('.chat-emote.default').each(function () {
this.src = this.src.replace(/\/\d\.0/, '/1.0');
});
}
}
}
}
|
chefhasteeth/BentoBot-PHP
|
resources/assets/js/app.js
|
JavaScript
|
bsd-3-clause
| 2,807
|
import UIObject from '../../src/base/ui_object'
import $ from 'clappr-zepto'
describe('UIObject', function() {
beforeEach(function(){
this.uiObject = new UIObject()
})
it('is a div tag by default', function(){
expect(this.uiObject.tagName).to.be.equal('div')
})
it('can be any tag', function(){
class MyButton extends UIObject { get tagName() { return 'button' } }
const myButton = new MyButton()
expect(myButton.tagName).to.be.equal('button')
})
it('has an unique id', function(){
const uiObjectA = new UIObject()
const uiObjectB = new UIObject()
expect(uiObjectA.cid).to.be.not.equal(uiObjectB.cid)
})
it('creates element for a given ui component', function(){
const component = $('<div></div>')
expect(this.uiObject.el).to.be.not.equal(component[0])
expect(this.uiObject.$el).to.be.not.equal(component)
})
it('can set element', function(){
const element = $('<section></section>')
this.uiObject.setElement(element)
expect(this.uiObject.el).to.be.equal(element[0])
expect(this.uiObject.$el).to.be.equal(element)
})
it('creates an element with attributes', function() {
class MyButton extends UIObject {
constructor(options) { super(options) }
get attributes() { return { class: 'my-button'} }
}
const myButton = new MyButton()
expect(myButton.el.className).to.be.equal('my-button')
})
it('binds events of an element to methods', function(){
class MyButton extends UIObject {
constructor(options) {
super(options)
this.myId = 0
}
get events() { return { 'click': 'myClick' } }
myClick(){ this.myId = 42 }
}
const myButton = new MyButton()
expect(myButton.myId).to.be.equal(0)
myButton.$el.trigger('click')
expect(myButton.myId).to.be.equal(42)
})
it('selects elements within the component', function(){
const insideComponent = $('<p id="special-id">here</p>')[0]
class MySpecialButton extends UIObject {
constructor(options) {
super(options)
}
render() { this.$el.append(insideComponent) }
}
const myButton = new MySpecialButton()
myButton.render()
expect(myButton.$('#special-id')[0]).to.be.equal(insideComponent)
})
it('removes it from DOM', function(){
class FullscreenButton extends UIObject {
constructor(options) {
super(options)
}
get attributes() { return { id: 'my-0-button'} }
}
const myButton = new FullscreenButton()
$(document.body).append(myButton.$el)
expect($('#my-0-button').length).to.be.equal(1)
myButton.remove()
expect($('#my-0-button').length).to.be.equal(0)
})
it('stops listening', function(){
class FullscreenButton extends UIObject {
constructor(options) {
super(options)
this.myId = 0
}
get events() { return { 'click': 'myClick' } }
myClick(){ this.myId += 1 }
}
const myButton = new FullscreenButton()
myButton.$el.trigger('click')
expect(myButton.myId).to.be.equal(1)
myButton.remove()
myButton.$el.trigger('click')
myButton.$el.trigger('click')
expect(myButton.myId).to.be.equal(1)
})
})
|
flavioribeiro/clappr
|
test/base/ui_object_spec.js
|
JavaScript
|
bsd-3-clause
| 3,225
|
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World')
});
app.get('/login', function (req, res) {
console.log(req["a"]);
res.send(JSON.stringify({a:"",bU:"cs"}))
});
app.listen(3000);
|
C0618C/NodeWS
|
Test/exp.js
|
JavaScript
|
bsd-3-clause
| 256
|
var Events = _.extend({}, Backbone.Events);
|
rodrigoBerlochi/JobAnalitics3
|
www/js/src/events.js
|
JavaScript
|
bsd-3-clause
| 43
|
var _ = require('underscore');
var WindshaftConfig = require('./config');
/**
* Wrapper over a server response to a map instantiation giving some utility methods.
* @constructor
* @param {object} windshaftSettings - Object containing the request options.
* @param {string} serverResponse - The json string representing a windshaft response to a map instantiation.
*/
function Response (windshaftSettings, serverResponse) {
this._windshaftSettings = windshaftSettings;
this._layerGroupId = serverResponse.layergroupid;
this._layers = serverResponse.metadata.layers;
this._dataviews = serverResponse.metadata.dataviews;
this._analyses = serverResponse.metadata.analyses;
this._cdnUrl = serverResponse.cdn_url;
}
/**
* Return the indexes of the layers for a certain type.
* @example
* // layers = [ carto, carto, tiled, plain, tiled, torque];
* getLayerIndexesByType('mapnik') // [0, 1]
* getLayerIndexesByType('tiled') // [2, 4]
* getLayerIndexesByType('torque') // [5]
* @param {string} Type - The type of the layers: mapnik, torque, plain, tiled.
*/
Response.prototype.getLayerIndexesByType = function getLayerIndexesByType (layerType) {
return _.reduce(this._getLayers(), function (layerIndexes, layer, index) {
if (layer.type === layerType) {
layerIndexes.push(index);
}
return layerIndexes;
}, []);
};
/**
* Build the base url to build windshaft map requests.
*/
Response.prototype.getBaseURL = function getBaseURL () {
return [
this._getHost(),
WindshaftConfig.MAPS_API_BASE_URL,
this._layerGroupId
].join('/');
};
/**
* Build the base url for static maps.
*/
Response.prototype.getStaticBaseURL = function getStaticBaseURL () {
return [
this._getHost(),
WindshaftConfig.MAPS_API_BASE_URL,
'static/center',
this._layerGroupId
].join('/');
};
Response.prototype._getHost = function _getHost () {
var urlTemplate = this._windshaftSettings.urlTemplate;
var userName = this._windshaftSettings.userName;
var protocol = this.getProtocol();
var cdnUrl = this._cdnUrl;
var cdnHost = cdnUrl && cdnUrl[protocol];
var templates = cdnUrl && cdnUrl.templates;
if (templates && templates[protocol]) {
var template = templates[protocol];
return template.url + '/' + userName;
}
if (cdnHost) {
return [protocol, '://', cdnHost, '/', userName].join('');
}
return urlTemplate.replace('{user}', userName);
};
Response.prototype.getProtocol = function getProtocol () {
return this._isHttps() ? 'https' : 'http';
};
Response.prototype._isHttps = function isHttps () {
return this._windshaftSettings.urlTemplate.indexOf('https') === 0;
};
Response.prototype.getSupportedSubdomains = function getSupportedSubdomains () {
var templates = this._cdnUrl && this._cdnUrl.templates;
var protocol = this.getProtocol();
if (templates && templates[protocol]) {
return templates[protocol].subdomains;
}
return [];
};
Response.prototype.getLayerMetadata = function getLayerMetadata (layerIndex) {
var layerMeta = {};
var layers = this._getLayers();
if (layers && layers[layerIndex]) {
layerMeta = layers[layerIndex].meta || {};
}
return layerMeta;
};
Response.prototype.getDataviewMetadata = function getDataviewMetadata (dataviewId) {
var dataviews = this._getDataviews();
if (dataviews && dataviews[dataviewId]) {
return dataviews[dataviewId];
}
// Try to get dataview's metatadta from the 'widgets' dictionary inside the metadata of each of the layers
dataviews = {};
var layersDataviews = _.compact(_.map(this._getLayers(), function (layer) { return layer.widgets; }));
_.each(layersDataviews, function (layerDataviews) { _.extend(dataviews, layerDataviews); });
if (dataviews && dataviews[dataviewId]) {
return dataviews[dataviewId];
}
};
Response.prototype.getAnalysisNodeMetadata = function (analysisId) {
var metadata = {};
var nodes = _.map(this._getAnalyses(), function (analysis) {
return analysis.nodes;
});
_.each(nodes, function (node) { _.extend(metadata, node); });
return metadata[analysisId];
};
/**
* Return the array with all the layers in the response
*/
Response.prototype._getLayers = function _getLayers () {
return this._layers;
};
Response.prototype._getDataviews = function _getDataviews () {
return this._dataviews;
};
Response.prototype._getAnalyses = function _getAnalyses () {
return this._analyses;
};
module.exports = Response;
|
splashblot/cartodb.js
|
src/windshaft/response.js
|
JavaScript
|
bsd-3-clause
| 4,453
|
import { addBooleanParameter, addDefaultParameter } from '@ovh-ux/ui-kit.core/src/js/component-utils';
export default class {
constructor($attrs, $element, $scope, $timeout, ouiPasswordConfiguration) {
'ngInject';
this.$attrs = $attrs;
this.$element = $element;
this.$scope = $scope;
this.$timeout = $timeout;
this.translations = ouiPasswordConfiguration.translations;
}
toggleVisibility() {
this.isVisible = !this.isVisible;
}
updateValidity(key, isValid) {
if (isValid) {
delete this.errors[key];
} else {
this.errors[key] = true;
}
this.valid = !Object.keys(this.errors).length;
this.form[this.name].$setValidity('password', this.valid);
}
$onInit() {
addBooleanParameter(this, 'disabled');
addBooleanParameter(this, 'required');
addDefaultParameter(this, 'id', `ouiPassword${this.$scope.$id}`);
addDefaultParameter(this, 'name', `ouiPassword${this.$scope.$id}`);
this.errors = {};
this.isVisible = false;
}
$postLink() {
this.$timeout(() => {
this.$element
.removeAttr('id')
.removeAttr('name')
.addClass('oui-password');
if ('confirm' in this.$attrs) {
this.$scope.$watch(
() => this.confirm === this.model,
(value) => this.updateValidity('confirm', value),
);
}
});
}
}
|
ovh-ux/ovh-ui-kit
|
packages/components/password/src/js/password.controller.js
|
JavaScript
|
bsd-3-clause
| 1,376
|
/**
* 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.
*
* @providesModule SectionList
* @flow
*/
'use strict';
const MetroListView = require('MetroListView');
const Platform = require('Platform');
const React = require('React');
const VirtualizedSectionList = require('VirtualizedSectionList');
import type {ViewToken} from 'ViewabilityHelper';
import type {Props as VirtualizedSectionListProps} from 'VirtualizedSectionList';
type Item = any;
type SectionBase<SectionItemT> = {
/**
* The data for rendering items in this section.
*/
data: $ReadOnlyArray<SectionItemT>,
/**
* Optional key to keep track of section re-ordering. If you don't plan on re-ordering sections,
* the array index will be used by default.
*/
key?: string,
// Optional props will override list-wide props just for this section.
renderItem?: ?(info: {
item: SectionItemT,
index: number,
section: SectionBase<SectionItemT>,
separators: {
highlight: () => void,
unhighlight: () => void,
updateProps: (select: 'leading' | 'trailing', newProps: Object) => void,
},
}) => ?React.Element<any>,
ItemSeparatorComponent?: ?ReactClass<any>,
keyExtractor?: (item: SectionItemT) => string,
// TODO: support more optional/override props
// onViewableItemsChanged?: ...
};
type RequiredProps<SectionT: SectionBase<any>> = {
/**
* The actual data to render, akin to the `data` prop in [`<FlatList>`](/react-native/docs/flatlist.html).
*
* General shape:
*
* sections: $ReadOnlyArray<{
* data: $ReadOnlyArray<SectionItem>,
* renderItem?: ({item: SectionItem, ...}) => ?React.Element<*>,
* ItemSeparatorComponent?: ?ReactClass<{highlighted: boolean, ...}>,
* }>
*/
sections: $ReadOnlyArray<SectionT>,
};
type OptionalProps<SectionT: SectionBase<any>> = {
/**
* Default renderer for every item in every section. Can be over-ridden on a per-section basis.
*/
renderItem: (info: {
item: Item,
index: number,
section: SectionT,
separators: {
highlight: () => void,
unhighlight: () => void,
updateProps: (select: 'leading' | 'trailing', newProps: Object) => void,
},
}) => ?React.Element<any>,
/**
* Rendered in between each item, but not at the top or bottom. By default, `highlighted`,
* `section`, and `[leading/trailing][Item/Separator]` props are provided. `renderItem` provides
* `separators.highlight`/`unhighlight` which will update the `highlighted` prop, but you can also
* add custom props with `separators.updateProps`.
*/
ItemSeparatorComponent?: ?ReactClass<any>,
/**
* Rendered at the very beginning of the list. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListHeaderComponent?: ?(ReactClass<any> | React.Element<any>),
/**
* Rendered when the list is empty. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListEmptyComponent?: ?(ReactClass<any> | React.Element<any>),
/**
* Rendered at the very end of the list. Can be a React Component Class, a render function, or
* a rendered element.
*/
ListFooterComponent?: ?(ReactClass<any> | React.Element<any>),
/**
* Rendered at the top and bottom of each section (note this is different from
* `ItemSeparatorComponent` which is only rendered between items). These are intended to separate
* sections from the headers above and below and typically have the same highlight response as
* `ItemSeparatorComponent`. Also receives `highlighted`, `[leading/trailing][Item/Separator]`,
* and any custom props from `separators.updateProps`.
*/
SectionSeparatorComponent?: ?ReactClass<any>,
/**
* A marker property for telling the list to re-render (since it implements `PureComponent`). If
* any of your `renderItem`, Header, Footer, etc. functions depend on anything outside of the
* `data` prop, stick it here and treat it immutably.
*/
extraData?: any,
/**
* How many items to render in the initial batch. This should be enough to fill the screen but not
* much more. Note these items will never be unmounted as part of the windowed rendering in order
* to improve perceived performance of scroll-to-top actions.
*/
initialNumToRender: number,
/**
* Used to extract a unique key for a given item at the specified index. Key is used for caching
* and as the react key to track item re-ordering. The default extractor checks item.key, then
* falls back to using the index, like react does.
*/
keyExtractor: (item: Item, index: number) => string,
/**
* Called once when the scroll position gets within `onEndReachedThreshold` of the rendered
* content.
*/
onEndReached?: ?(info: {distanceFromEnd: number}) => void,
/**
* How far from the end (in units of visible length of the list) the bottom edge of the
* list must be from the end of the content to trigger the `onEndReached` callback.
* Thus a value of 0.5 will trigger `onEndReached` when the end of the content is
* within half the visible length of the list.
*/
onEndReachedThreshold?: ?number,
/**
* If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make
* sure to also set the `refreshing` prop correctly.
*/
onRefresh?: ?() => void,
/**
* Called when the viewability of rows changes, as defined by the
* `viewabilityConfig` prop.
*/
onViewableItemsChanged?: ?(info: {
viewableItems: Array<ViewToken>,
changed: Array<ViewToken>,
}) => void,
/**
* Set this true while waiting for new data from a refresh.
*/
refreshing?: ?boolean,
/**
* Note: may have bugs (missing content) in some circumstances - use at your own risk.
*
* This may improve scroll performance for large lists.
*/
removeClippedSubviews?: boolean,
/**
* Rendered at the top of each section. These stick to the top of the `ScrollView` by default on
* iOS. See `stickySectionHeadersEnabled`.
*/
renderSectionHeader?: ?(info: {section: SectionT}) => ?React.Element<any>,
/**
* Rendered at the bottom of each section.
*/
renderSectionFooter?: ?(info: {section: SectionT}) => ?React.Element<any>,
/**
* Makes section headers stick to the top of the screen until the next one pushes it off. Only
* enabled by default on iOS because that is the platform standard there.
*/
stickySectionHeadersEnabled?: boolean,
legacyImplementation?: ?boolean,
};
type Props<SectionT> = RequiredProps<SectionT>
& OptionalProps<SectionT>
& VirtualizedSectionListProps<SectionT>;
const defaultProps = {
...VirtualizedSectionList.defaultProps,
stickySectionHeadersEnabled: Platform.OS === 'ios',
};
type DefaultProps = typeof defaultProps;
/**
* A performant interface for rendering sectioned lists, supporting the most handy features:
*
* - Fully cross-platform.
* - Configurable viewability callbacks.
* - List header support.
* - List footer support.
* - Item separator support.
* - Section header support.
* - Section separator support.
* - Heterogeneous data and item rendering support.
* - Pull to Refresh.
* - Scroll loading.
*
* If you don't need section support and want a simpler interface, use
* [`<FlatList>`](/react-native/docs/flatlist.html).
*
* Simple Examples:
*
* <SectionList
* renderItem={({item}) => <ListItem title={item.title} />}
* renderSectionHeader={({section}) => <H1 title={section.title} />}
* sections={[ // homogenous rendering between sections
* {data: [...], title: ...},
* {data: [...], title: ...},
* {data: [...], title: ...},
* ]}
* />
*
* <SectionList
* sections={[ // heterogeneous rendering between sections
* {data: [...], title: ..., renderItem: ...},
* {data: [...], title: ..., renderItem: ...},
* {data: [...], title: ..., renderItem: ...},
* ]}
* />
*
* This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist.html),
* and thus inherits it's props (as well as those of `ScrollView`) that aren't explicitly listed
* here, along with the following caveats:
*
* - Internal state is not preserved when content scrolls out of the render window. Make sure all
* your data is captured in the item data or external stores like Flux, Redux, or Relay.
* - This is a `PureComponent` which means that it will not re-render if `props` remain shallow-
* equal. Make sure that everything your `renderItem` function depends on is passed as a prop
* (e.g. `extraData`) that is not `===` after updates, otherwise your UI may not update on
* changes. This includes the `data` prop and parent component state.
* - In order to constrain memory and enable smooth scrolling, content is rendered asynchronously
* offscreen. This means it's possible to scroll faster than the fill rate and momentarily see
* blank content. This is a tradeoff that can be adjusted to suit the needs of each application,
* and we are working on improving it behind the scenes.
* - By default, the list looks for a `key` prop on each item and uses that for the React key.
* Alternatively, you can provide a custom `keyExtractor` prop.
*
*/
class SectionList<SectionT: SectionBase<any>>
extends React.PureComponent<DefaultProps, Props<SectionT>, void>
{
props: Props<SectionT>;
static defaultProps: DefaultProps = defaultProps;
/**
* Scrolls to the item at the specified `sectionIndex` and `itemIndex` (within the section)
* positioned in the viewable area such that `viewPosition` 0 places it at the top (and may be
* covered by a sticky header), 1 at the bottom, and 0.5 centered in the middle. `viewOffset` is a
* fixed number of pixels to offset the final target position, e.g. to compensate for sticky
* headers.
*
* Note: cannot scroll to locations outside the render window without specifying the
* `getItemLayout` prop.
*/
scrollToLocation(params: {
animated?: ?boolean,
itemIndex: number,
sectionIndex: number,
viewOffset?: number,
viewPosition?: number,
}) {
this._wrapperListRef.scrollToLocation(params);
}
/**
* Tells the list an interaction has occured, which should trigger viewability calculations, e.g.
* if `waitForInteractions` is true and the user has not scrolled. This is typically called by
* taps on items or by navigation actions.
*/
recordInteraction() {
const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
listRef && listRef.recordInteraction();
}
/**
* Provides a handle to the underlying scroll responder.
*/
getScrollResponder() {
const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
if (listRef) {
return listRef.getScrollResponder();
}
}
getScrollableNode() {
const listRef = this._wrapperListRef && this._wrapperListRef.getListRef();
if (listRef) {
return listRef.getScrollableNode();
}
}
render() {
const List = this.props.legacyImplementation ? MetroListView : VirtualizedSectionList;
return <List {...this.props} ref={this._captureRef} />;
}
_wrapperListRef: MetroListView | VirtualizedSectionList<any>;
_captureRef = (ref) => { this._wrapperListRef = ref; };
}
module.exports = SectionList;
|
tszajna0/react-native
|
Libraries/Lists/SectionList.js
|
JavaScript
|
bsd-3-clause
| 11,670
|
define(function(require) {
'use strict';
return {
trendingHotelDestination: require('text!templates/trendingHotelDestination.html')
}
});
|
kinddevil/hotel
|
v2/public/js/templates.js
|
JavaScript
|
bsd-3-clause
| 164
|
var APIRoot = "http://localhost:3000";
module.exports = {
APIEndPoints: {
LOGIN: APIRoot + "/v1/login",
REGISTRATION: APIRoot + "/v1/users",
STORIES: APIRoot + "/v1/stories"
},
};
|
xuorig/insyto
|
js/constants/Constants.js
|
JavaScript
|
bsd-3-clause
| 215
|
/**
* Created by suiuu on 15/6/1.
*/
var emailTimer;
var topMessageInterval;
var user_message_count=0;
var sys_message_count=0;
var challenge='';
var validate='';
var seccode='';
var _isCode=false;
var phoneTimer;
var phoneTime=0;
function initSocketConnection() {
// 创建websocket
ws = new WebSocket("ws://58.96.191.44:7272");
// 当socket连接打开时,输入用户名
ws.onopen = function () {
if(reconnect == false) {
// 登录
var login_data = JSON.stringify({"type":"login","user_key":sessionId});
//console.log("socket connection success");
ws.send(login_data);
reconnect = true;
}else{
// 断线重连
var relogin_data = JSON.stringify({"type":"re_login","user_key":sessionId});
//console.log("socket reconnection success");
ws.send(relogin_data);
}
};
// 当有消息时根据消息类型显示不同信息
ws.onmessage = function (e) {
console.log(e.data);
var data = JSON.parse(e.data);
switch(data['type']){
// 服务端ping客户端
case 'ping':
ws.send(JSON.stringify({"type":"pong"}));
break;;
// 登录 更新用户列表
case 'login':
break;
// 断线重连,只更新用户列表
case 're_login':
break;
// 发言
case 'say':
newMessageProcess(data);
break;
// 用户退出 更新用户列表
case 'logout':
//console.log("用户退出了登录");
}
};
ws.onclose = function () {
//console.log("连接关闭,定时重连");
};
ws.onerror = function () {
console.log("出现错误");
};
}
function initBreadcrumb(){
var href=window.location.href;
if(href.indexOf("?")!=-1){
href=href.substring(0,href.indexOf("?"));
}
$(".menu_ul li").each(function(){
var a=$(this).find("a");
if(href.indexOf($(a).attr("href"))!=-1){
$(".menu_ul li").removeClass("active");
$(this).addClass("active");
}
});
}
function initTopMessage(){
//如果用户登录了,查询是否有新私信
if(isLogin==1){
initSocketConnection();
if(topNewMessageCount>0){
$("#topNewMessageCount").html(topNewMessageCount);
$("#topNewMessageCount").show();
}
//setTopUnReadMessageCount(topNewMessageCount);
//initUserMessageInfoList();
//topMessageInterval=window.setInterval(function(){
// initUserMessageInfoList();
//},10000);
}
$(".search-btn").bind("click",function(){
var search=$("#search").val();
if(search!=""){
window.location.href="/view-trip/list?s="+search;
}
});
$("#userMessageLiBtn").bind("click",function(){
$("#userMessageLiBtn").addClass("active");
$("#sysMessageLiBtn").removeClass("active");
$("#unReadUserMessageList").show();
$("#unReadSystemMessageList").hide();
});
$("#sysMessageLiBtn").bind("click",function(){
$("#userMessageLiBtn").removeClass("active");
$("#sysMessageLiBtn").addClass("active");
$("#unReadUserMessageList").hide();
$("#unReadSystemMessageList").show();
});
}
var newMessageProcess=function (messageInfo)
{
var userHtml="";
var nickname=messageInfo.sender_name;
if(nickname.length>5){
nickname=nickname.substring(0,5);
}
userHtml+='<li class="message"><a style="width: 240px;height: 40px" href="/user-info?tab=myMessage"><img src="'+messageInfo.sender_HeadImg+'"><span>'+nickname+'</span>';
userHtml+='<p>给您发了私信</p>';
userHtml+='</a></li>';
$("#unReadUserMessageList").html(userHtml+$("#unReadUserMessageList").html());
var nowUserMessageCount=$("#unReadUserMessageList li[class='message']").size();
if(nowUserMessageCount>maxMessageCount){
$("#unReadUserMessageList li[class='message']").last().remove();
}
setTopUnReadMessageCount(1);
if(typeof(messageSessionList)!="undefined"){
var tempMessage={};
tempMessage.headImg=messageInfo.sender_HeadImg;
tempMessage.isRead=0;
tempMessage.lastConcatTime=messageInfo.time;
tempMessage.lastContentInfo=messageInfo.content;
tempMessage.nickname=messageInfo.sender_name;
tempMessage.relateId=messageInfo.receive_id;
tempMessage.sessionId=0;
tempMessage.sessionKey=messageInfo.session_key;
tempMessage.userId=messageInfo.sender_id;
rebuildMessageSessionList(new Array(tempMessage),2);
}
}
var setTopUnReadMessageCount=function(count) {
if(count==undefined){
return;
}
count=$("#unReadUserMessageList li[class='message']").size()+parseInt(count);
if(count>0){
$("#topNewMessageCount").show();
$("#topNewMessageCount").html(count);
$("#noUserMessage").hide();
if(count>maxMessageCount){
$("#moreUserMessage").show();
}else{
$("#moreUserMessage").hide();
}
}else{
$("#topNewMessageCount").hide();
$("#topNewMessageCount").html("");
$("#noUserMessage").show();
$("#moreUserMessage").hide();
}
};
function buildSysMessageListHtml(list){
if(list==""||list.length==0){
$("#unReadSystemMessageList").html('<li><p style="text-align: center">暂无系统消息</p></li>');
return;
}
var sysHtml="",messageInfo="",nickname="";
for(var i=0;i<list.length;i++){
if(i==7){
break;
}
messageInfo=list[i];
var content=messageInfo.content;
if(content.length>12){
content=content.substring(0,12)+"...";
}
sysHtml+='<li onclick="changeSystemMessageRead('+messageInfo.messageId+',\''+messageInfo.url+'\')">';
sysHtml+='<p>'+content+'</p>';
sysHtml+='</li>';
sys_message_count++;
}
$("#unReadSystemMessageList").html(sysHtml);
}
function initTopMessageSelect(){
if(sys_message_count>0){
$("#suiuu-btn1").addClass("active");
$("#sysMessageLiBtn").click();
}
if(user_message_count>0){
$("#suiuu-btn1").addClass("active");
$("#userMessageLiBtn").click();
}
}
function buildUserMessageListHtml(list){
if(list==""||list.length==0){
$("#unReadUserMessageList").html('<li><p style="text-align: center;width: 240px">暂无私信消息</p></li>');
return;
}
var userHtml="",messageInfo="",nickname="";
for(var i=0;i<list.length;i++){
if(i==7){
break;
}
messageInfo=list[i];
if(messageInfo.relateId!=SystemMessage.userId){
nickname=messageInfo.nickname;
if(nickname.length>5){
nickname=nickname.substring(0,5);
}
userHtml+='<li><a style="width: 240px;height: 40px" href="/user-info?tab=myMessage"><img src="'+messageInfo.headImg+'"><span>'+nickname+'</span>';
userHtml+='<p>给您发了私信</p>';
userHtml+='</a></li>';
user_message_count++;
}
}
if(userHtml==""){
userHtml='<li><p style="text-align: center;width: 240px">暂无私信消息</p></li>';
}
$("#unReadUserMessageList").html(userHtml);
}
function changeSystemMessageRead(messageId,url){
$.ajax({
type: 'post',
url: '/user-message/change-system-message-read',
data: {
messageId:messageId,
_csrf: $('input[name="_csrf"]').val()
},
error:function(){
window.clearInterval(topMessageInterval);
},
success: function (data) {
var datas=eval('('+data+')');
if(datas.status==1){
if(url!=""){
window.location.href=url;
}else{
window.location.href="/user-info?tab=myMessage";
}
}else{
}
}
});
}
function initEmailTimer(){
emailTimer=window.setInterval(function(){
if(emailTime>0){
emailTime--;
initEmailTime();
}else{
window.clearInterval(emailTimer);
initEmailTime();
}
},1000);
}
function initEmailTime(){
//emailTime!=""&&emailTime>0
if(emailTime!=""&&emailTime>0){
$("#emailTime").show();
$("#emailTime input").val("发送成功,"+emailTime+"秒后可重新发送");
$("#emailRegister").attr("disabled","disabled");
$("#emailRegister").removeAttr("disabled");
$("#emailRegister").css("background","#858585");
$("#emailRegister").unbind("click");
}else{
$("#emailTime input").val("");
$("#emailTime").hide();
$("#emailRegister").removeAttr("disabled");
$("#emailRegister").css("background","#3dd9c3");
$("#emailRegister").unbind("click");
$("#emailRegister").bind("click",function(){
emailRegister();
});
}
}
/**
* 邮箱注册
* @returns {boolean}
*/
function emailRegister() {
var nickname = $("#regNickname").val();
var email = $("#regEmail").val();
var password = $("#regEmailPwd").val();
if(nickname.length>20){
Main.showTip("昵称不能大于20字符");
return false;
}
if(email.length>30||email.length<6){
Main.showTip("邮箱长度必须在6~30个字符之间");
return false;
}else{
var regexp = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
var matches = regexp.exec(email);
if(matches==null){
Main.showTip("邮箱格式不正确");
return false;
}
}
if(password.length>30||password.length<6){
Main.showTip("密码长度必须在6~30个字符之间");
return false;
}
if(!$("#zhuce-check02").is(":checked")){
Main.showTip("请同意《服务协议、退款政策、版权声明、免责声明》");
return;
}
$.ajax({
type: 'post',
url: '/index/send-email',
data: {
nickname:nickname,
email: email,
password: password,
_csrf: $('input[name="_csrf"]').val()
},
beforeSend: function () {
$("#emailRegister").attr("disabled","disabled");
$("#emailRegister").css("background","#858585");
$("#emailTime").show();
$("#emailTime input").val("正在发送验证邮件,请稍后...");
},
error:function(){
Main.showTip("系统异常。。。");
},
success: function (data) {
var datas=eval('('+data+')');
if(datas.status==1){
emailTime=datas.data;
initEmailTimer();
}else{
$("#emailRegister").removeAttr("disabled");
$("#emailRegister").css("background","#3dd9c3");
$("#emailTime").hide();
Main.showTip(datas.data);
}
}
});
}
function gt_custom_ajax(result, selector, message) {
if (result) {
challenge = selector(".geetest_challenge").value;
validate = selector(".geetest_validate").value;
seccode = selector(".geetest_seccode").value;
_isCode=false;
//当验证成功时,获取相应input的值,并做ajax验证请求
}else
{
_isCode=true;
}
}
function login(){
var username = $("#username_bottom").val();
var password = $("#userpassword_bottom").val();
var remember = $("#logo-check").is(":checked");
if(username=='')
{
Main.showTip('用户名不能为空');
}else if(password=='')
{
Main.showTip('密码不能为空');
}else if(_isCode)
{
Main.showTip('验证失败');
}else{
$.ajax({
type: 'post',
url: '/index/login',
data: {
username: username,
password: password,
remember:remember,
geetest_challenge:challenge,
geetest_validate: validate,
geetest_seccode:seccode,
_csrf: $('input[name="_csrf"]').val()
},
beforeSend: function () {
//Main.showTip('正在提交,请稍后。。。');
},
error:function(){
Main.showTip("系统异常。。。");
},
success: function (data) {
var obj= $.parseJSON(data);
if(obj.status==1){
if(window.location.href.indexOf("result?result=")==-1){
window.location.reload();
}else{
window.location.href="/";
}
}else{
Main.showTip(obj.data);
if(obj.message>=3){
$('.gt_refresh_button')[0].click();
$("#code9527").css('display','block');
}
}
}
});
}
}
function initPhoneRegister(){
phoneTimer=window.setInterval(function(){
if(phoneTime>0){
phoneTime--;
$("#getCodePhoneRegister").html(phoneTime+"秒后可发送");
$("#getCodePhoneRegister").unbind("click");
}else{
window.clearInterval(phoneTimer);
$("#getCodePhoneRegister").html("发送验证码");
$("#getCodePhoneRegister").bind("click",function(){
$("#getCodePhoneRegister").removeAttr("disabled");
$("#getCodePhoneRegister").css("background","#FFAA00");
getCodePhoneRegister();
});
}
},1000);
}
function getCodePhoneRegister(){
var nickname=$('#nickname_top').val();
var phone=$('#phone_top').val();
var password=$('#phone_password_top').val();
var areaCode = $("#codeId_top").val();
var valNum = $("#valNum").val();
if(nickname==''){
Main.showTip("昵称不能为空");
return false;
}else if(phone==''){
Main.showTip("手机号不能为空");
return false;
}else if(password==''){
Main.showTip("密码不能为空");
return false;
}else if(areaCode==''){
Main.showTip("国家区号不能为空");
return false;
}else if(valNum==''){
Main.showTip("请输入图形验证码");
return false;
}else{
$.ajax({
type: 'post',
url: '/index/send-message',
data: {
nickname:nickname,
phone:phone,
password:password,
areaCode:areaCode,
valNum:valNum,
_csrf: $('input[name="_csrf"]').val()
},
beforeSend: function () {
//Main.showTip('正在提交,请稍后。。。');
$("#getCodePhoneRegister").attr("disabled","disbaled");
$("#getCodePhoneRegister").css("background","#858585");
},
error:function(){
Main.showTip("系统异常。。。");
},
success: function (data) {
var obj=eval('('+data+')');
if(obj.status==1)
{
phoneTime=obj.data;
$("#phoneRegister").bind("click",function(){
phoneRegister();
});
initPhoneRegister();
Main.showTip("发送成功请注意查收。。。");
}else
{
$("#getCodePhoneRegister").removeAttr("disabled");
$("#getCodePhoneRegister").css("background","#FFAA00");
Main.showTip(obj.data);
}
}
});
}
}
function phoneRegister(){
var code=$('#phoneCode_top').val();
var password=$("#phone_password_top").val();
var nickname=$('#nickname_top').val();
if(code=='')
{
Main.showTip('验证码不能为空');
}else{
if(!$("#zhuce-check01").is(":checked")){
Main.showTip("请同意《服务协议、退款政策、版权声明、免责声明》");
return;
}
$.ajax({
type: 'post',
url: '/index/phone-register',
data: {
nickname:nickname,
code:code,
password:password,
_csrf: $('input[name="_csrf"]').val()
},
beforeSend: function () {
//Main.showTip('正在提交,请稍后。。。');
},
error:function(){
Main.showTip("系统异常。。。");
},
success: function (data) {
var obj=eval('('+data+')');
if(obj.status==1)
{
Main.showTip("注册成功即将跳转");
if(window.location.href.indexOf("result?result=")==-1){
window.location.reload();
}else{
window.location.href="/";
}
}else
{
Main.showTip(obj.data);
}
}
});
}
}
function initBottomTab(){
var href=window.location.href;
var tabId='';
var tabArr=[]
try{
if(href.indexOf("/static")!=-1&&href.indexOf("?")!=-1){
tabId=href.substring(href.indexOf("?")+1,href.length);
tabArr=tabId.split("-");
$("#"+tabArr[0]).click();
$("#"+tabArr[1]).click();
}
}catch (e){}
}
function sendFeedback(){
var content =$('#feedback_content').val();
var username=$('#username_static').val();
var phone=$('#phone_static').val();
var email=$('#email_static').val();
var chkType=$("input[type='radio'][name='rad']:checked").val();
if(content=='')
{
Main.showTip('请输入反馈后提交');
return;
}
if(chkType==1&&phone==''&&email==''){
Main.showTip("手机或者邮箱必须填写一种");
return;
}
$.ajax({
url: "/user-feedback/web-create-feedback",
type: "post",
data:{
content:content,
username:username,
email:email,
phone:phone,
_csrf: $('input[name="_csrf"]').val()
},
error:function(){
Main.showTip('反馈异常');
},
success: function(data){
var result=eval("("+data+")");
if(result.status==1){
Main.showTip('反馈成功,感谢您的反馈');
}else{
Main.showTip(result.data);
}
}
});
}
function loadDes(search){
search= $.trim(search);
if(search==''){
return '';
}
var allList=$.parseJSON(searchList);
var rst=[];
for(var i=0;i<allList.length;i++){
var t=allList[i].cname+allList[i].ename;
if(t.toLowerCase().indexOf(search.toLowerCase())!=-1){
rst.push(allList[i]);
}
}
return rst;
}
$(document).ready(function () {
//初始化区号选择
$(".areaCodeSelect_top").select2({
'width':'288px',
'height':'40px',
formatNoMatches: function () {
return "暂无匹配";
}
});
initEmailTimer();
initPhoneRegister();
initTopMessage();
initBreadcrumb();
initBottomTab();
$("#userpassword_bottom").keypress(function(e){
if(e.keyCode==13){
$("#login-check").click();
}
});
$("#search-ipt").keypress(function(e){
if(e.keyCode==13){
$(".search-btn").click();
}
});
$("#sendFeedback").bind("click",function(){
sendFeedback();
});
$("#search").on('input',function(e){
var search= $.trim($(this).val());
if(search==''){
$("#searchDrop").html("");
$("#searchDrop").hide();
return;
}
var rst=loadDes(search);
if(rst!=null&&rst.length>0){
var html='';
for(var j=0;j<rst.length;j++){
var temp=rst[j];
var name=temp.cname+"\\"+temp.ename;
var tripCountHtml='<b>'+temp.count+'条随游</b>';
if(name.length>10){
name=name.substring(0,10)+"...";
}
html+='<li><a href="'+UrlManager.getTripSearchUrl(temp.cname)+'">';
html+=name+tripCountHtml;
html+='</a></li>'
if(j==6){
break;
}
}
$("#searchDrop").html(html);
$("#searchDrop").show();
}else{
$("#searchDrop").html("");
$("#searchDrop").hide();
}
});
});
|
suiuuwebandapp/Web-Backend
|
frontend/web/assets/pages/layout/layout.js
|
JavaScript
|
bsd-3-clause
| 21,327
|
/*
* JavaScript tracker for Snowplow: forms.js
*
* Significant portions copyright 2010 Anthon Pang. Remainder copyright
* 2012-2014 Snowplow Analytics Ltd. 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 Anthon Pang nor Snowplow Analytics Ltd nor the
* names of their 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.
*/
var lodash = require('./lib_managed/lodash'),
helpers = require('./lib/helpers'),
object = typeof exports !== 'undefined' ? exports : this;
/**
* Object for handling automatic form tracking
*
* @param object core The tracker core
* @param string trackerId Unique identifier for the tracker instance, used to mark tracked elements
* @param function contextAdder Function to add common contexts like PerformanceTiming to all events
* @return object formTrackingManager instance
*/
object.getFormTrackingManager = function (core, trackerId, contextAdder) {
// Tag names of mutable elements inside a form
var innerElementTags = ['textarea', 'input', 'select'];
// Used to mark elements with event listeners
var trackingMarker = trackerId + 'form';
// Filter to determine which forms should be tracked
var formFilter = function (e) {return true;}
// Filter to determine which form fields should be tracked
var fieldFilter = function (e) {return true;}
/*
* Get an identifier for a form, input, textarea, or select element
*/
function getFormElementName(elt) {
return elt[lodash.find(['name', 'id', 'type', 'nodeName'], function (propName) {
// If elt has a child whose name is "id", that element will be returned
// instead of the actual id of elt unless we ensure that a string is returned
return elt[propName] && typeof elt[propName] === 'string';
})];
}
/*
* Identifies the parent form in which an element is contained
*/
function getParentFormName(elt) {
while (elt && elt.nodeName.toUpperCase() !== 'HTML' && elt.nodeName.toUpperCase() !== 'FORM') {
elt = elt.parentNode;
}
if (elt.nodeName.toUpperCase() === 'FORM') {
return getFormElementName(elt);
}
}
/*
* Returns a list of the input, textarea, and select elements inside a form along with their values
*/
function getInnerFormElements(elt) {
var innerElements = [];
lodash.forEach(innerElementTags, function (tagname) {
var trackedChildren = lodash.filter(elt.getElementsByTagName(tagname), function (child) {
return child.hasOwnProperty(trackingMarker);
});
lodash.forEach(trackedChildren, function (child) {
if (child.type === 'submit') {
return;
}
var elementJson = {
name: getFormElementName(child),
value: child.value,
nodeName: child.nodeName
};
if (child.type && child.nodeName.toUpperCase() === 'INPUT') {
elementJson.type = child.type;
}
if ((child.type === 'checkbox' || child.type === 'radio') && !child.checked) {
elementJson.value = null;
}
innerElements.push(elementJson);
});
});
return innerElements;
}
/*
* Return function to handle form field change event
*/
function getFormChangeListener(context) {
return function (e) {
var elt = e.target;
var type = elt.nodeName.toUpperCase() === 'INPUT' ? elt.type : null;
var value = (elt.type === 'checkbox' && !elt.checked) ? null : elt.value;
core.trackFormChange(getParentFormName(elt), getFormElementName(elt), elt.nodeName, type, lodash.map(elt.classList), value, contextAdder(context));
};
}
/*
* Return function to handle form submission event
*/
function getFormSubmissionListener(context) {
return function (e) {
var elt = e.target;
var innerElements = getInnerFormElements(elt);
core.trackFormSubmission(getFormElementName(elt), lodash.map(elt.classList), innerElements, contextAdder(context));
};
}
return {
/*
* Configures form tracking: which forms and fields will be tracked, and the context to attach
*/
configureFormTracking: function (config, context) {
if (config) {
formFilter = helpers.getFilter(config.forms, true);
fieldFilter = helpers.getFilter(config.fields, false);
}
},
/*
* Add submission event listeners to all form elements
* Add value change event listeners to all mutable inner form elements
*/
addFormListeners: function (context) {
lodash.forEach(document.getElementsByTagName('form'), function (form) {
if (formFilter(form) && !form[trackingMarker]) {
lodash.forEach(innerElementTags, function (tagname) {
lodash.forEach(form.getElementsByTagName(tagname), function (innerElement) {
if (fieldFilter(innerElement) && !innerElement[trackingMarker]) {
helpers.addEventListener(innerElement, 'change', getFormChangeListener(context), false);
innerElement[trackingMarker] = true;
}
});
});
helpers.addEventListener(form, 'submit', getFormSubmissionListener(context));
form[trackingMarker] = true;
}
});
}
};
};
|
fivetran/snowplow-javascript-tracker
|
src/js/forms.js
|
JavaScript
|
bsd-3-clause
| 6,332
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';
/**
* SuggestAppsDialog contains a list box to select an app to be opened the file
* with. This dialog should be used as action picker for file operations.
*/
/**
* The width of the widget (in pixel).
* @type {number}
* @const
*/
var WEBVIEW_WIDTH = 735;
/**
* The height of the widget (in pixel).
* @type {number}
* @const
*/
var WEBVIEW_HEIGHT = 480;
/**
* The URL of the widget.
* @type {string}
* @const
*/
var CWS_WIDGET_URL =
'https://clients5.google.com/webstore/wall/cros-widget-container';
/**
* The origin of the widget.
* @type {string}
* @const
*/
var CWS_WIDGET_ORIGIN = 'https://clients5.google.com';
/**
* RegExp to extract the origin (shema, host and port) from the URL.
* TODO(yoshiki): Remove this before ShareDialog launches or M31 branch cut.
*
* @type {RegExp}
* @const
*/
var REGEXP_EXTRACT_HOST = /^https?:\/\/[\w\.\-]+(?:\:\d{1,5})?(?=\/)/;
/**
* RegExp to check if the origin is google host or not.
* Google hosts must be on https and default port.
* TODO(yoshiki): Remove this before ShareDialog launches or M31 branch cut.
*
* @type {RegExp}
* @const
*/
var REGEXP_GOOGLE_MATCH = /^https:\/\/[\w\.\-]+\.google\.com$/;
/**
* RegExp to check if the origin is localhost or not.
* TODO(yoshiki): Remove this before ShareDialog launches or M31 branch cut.
*
* @type {RegExp}
* @const
*/
var REGEXP_LOCALHOST_MATCH = /^https?:\/\/localhost(?:\:\d{1,5})?$/;
/**
* Creates dialog in DOM tree.
*
* @param {HTMLElement} parentNode Node to be parent for this dialog.
* @constructor
* @extends {FileManagerDialogBase}
*/
function SuggestAppsDialog(parentNode) {
FileManagerDialogBase.call(this, parentNode);
this.frame_.id = 'suggest-app-dialog';
this.spinner_ = this.document_.createElement('div');
this.spinner_.className = 'spinner';
this.spinnerWrapper_ = this.document_.createElement('div');
this.spinnerWrapper_.className = 'spinner-container';
this.spinnerWrapper_.style.width = WEBVIEW_WIDTH + 'px';
this.spinnerWrapper_.style.height = WEBVIEW_HEIGHT + 'px';
this.spinnerWrapper_.appendChild(this.spinner_);
this.frame_.insertBefore(this.spinnerWrapper_, this.text_.nextSibling);
this.webviewContainer_ = this.document_.createElement('div');
this.webviewContainer_.id = 'webview-container';
this.webviewContainer_.style.width = WEBVIEW_WIDTH + 'px';
this.webviewContainer_.style.height = WEBVIEW_HEIGHT + 'px';
this.frame_.insertBefore(this.webviewContainer_, this.text_.nextSibling);
this.buttons_ = this.document_.createElement('div');
this.buttons_.id = 'buttons';
this.frame_.appendChild(this.buttons_);
this.webstoreButton_ = this.document_.createElement('div');
this.webstoreButton_.id = 'webstore-button';
this.webstoreButton_.innerHTML = str('SUGGEST_DIALOG_LINK_TO_WEBSTORE');
this.webstoreButton_.addEventListener(
'click', this.onWebstoreLinkClicked_.bind(this));
this.buttons_.appendChild(this.webstoreButton_);
this.initialFocusElement_ = this.webviewContainer_;
this.webview_ = null;
this.accessToken_ = null;
this.widgetUrl_ = CWS_WIDGET_URL;
this.widgetOrigin_ = CWS_WIDGET_ORIGIN;
// For development, we provide the feature to override the URL of the widget.
// TODO(yoshiki): Remove this before ShareDialog launches or M31 branch cut.
this.urlOverrided_ = false;
chrome.storage.local.get(
['widgetUrlOverride'],
function(items) {
if (items['widgetUrlOverride']) {
this.widgetUrl_ = items['widgetUrlOverride'];
var match = REGEXP_EXTRACT_HOST.exec(this.widgetUrl_);
// Overriding URL must be on either localhost or .google.com.
if (!match ||
(!REGEXP_GOOGLE_MATCH.test(match[0]) &&
!REGEXP_LOCALHOST_MATCH.test(match[0])))
throw new Error('The widget URL is invalid.');
this.widgetOrigin_ = match[0];
this.urlOverrided_ = true;
}
}.bind(this));
this.extension_ = null;
this.mime_ = null;
this.installingItemId_ = null;
this.state_ = SuggestAppsDialog.State.UNINITIALIZED;
this.initializationTask_ = new AsyncUtil.Group();
this.initializationTask_.add(this.retrieveAuthorizeToken_.bind(this));
this.initializationTask_.run();
}
SuggestAppsDialog.prototype = {
__proto__: FileManagerDialogBase.prototype
};
/**
* @enum {string}
* @const
*/
SuggestAppsDialog.State = {
UNINITIALIZED: 'SuggestAppsDialog.State.UNINITIALIZED',
INITIALIZING: 'SuggestAppsDialog.State.INITIALIZING',
INITIALIZE_FAILED_CLOSING:
'SuggestAppsDialog.State.INITIALIZE_FAILED_CLOSING',
INITIALIZED: 'SuggestAppsDialog.State.INITIALIZED',
INSTALLING: 'SuggestAppsDialog.State.INSTALLING',
INSTALLED_CLOSING: 'SuggestAppsDialog.State.INSTALLED_CLOSING',
CANCELED_CLOSING: 'SuggestAppsDialog.State.CANCELED_CLOSING'
};
Object.freeze(SuggestAppsDialog.State);
/**
* @enum {string}
* @const
*/
SuggestAppsDialog.Result = {
// Install is done. The install app should be opened.
INSTALL_SUCCESSFUL: 'SuggestAppsDialog.Result.INSTALL_SUCCESSFUL',
// User cancelled the suggest app dialog. No message should be shown.
USER_CANCELL: 'SuggestAppsDialog.Result.USER_CANCELL',
// Failed to load the widget. Error message should be shown.
FAILED: 'SuggestAppsDialog.Result.FAILED'
};
Object.freeze(SuggestAppsDialog.Result);
/**
* @override
*/
SuggestAppsDialog.prototype.onInputFocus = function() {
this.webviewContainer_.select();
};
/**
* Injects headers into the passed request.
*
* @param {Event} e Request event.
* @return {{requestHeaders: HttpHeaders}} Modified headers.
* @private
*/
SuggestAppsDialog.prototype.authorizeRequest_ = function(e) {
e.requestHeaders.push({
name: 'Authorization',
value: 'Bearer ' + this.accessToken_
});
return {requestHeaders: e.requestHeaders};
};
/**
* Retrieves the authorize token. This method should be called in
* initialization of the dialog.
*
* @param {function()} callback Called when the token is retrieved.
* @private
*/
SuggestAppsDialog.prototype.retrieveAuthorizeToken_ = function(callback) {
if (this.accessToken_) {
callback();
return;
}
// Fetch or update the access token.
chrome.fileBrowserPrivate.requestWebStoreAccessToken(
function(accessToken) {
// In case of error, this.accessToken_ will be set to null.
this.accessToken_ = accessToken;
callback();
}.bind(this));
};
/**
* Shows dialog.
*
* @param {string} extension Extension of the file.
* @param {string} mime Mime of the file.
* @param {function(boolean)} onDialogClosed Called when the dialog is closed.
* The argument is the result of installation: true if an app is installed,
* false otherwise.
*/
SuggestAppsDialog.prototype.show = function(extension, mime, onDialogClosed) {
if (this.state_ != SuggestAppsDialog.State.UNINITIALIZED) {
console.error('Invalid state.');
return;
}
this.extension_ = extension;
this.mimeType_ = mime;
this.onDialogClosed_ = onDialogClosed;
this.state_ = SuggestAppsDialog.State.INITIALIZING;
// Makes it sure that the initialization is completed.
this.initializationTask_.run(function() {
if (!this.accessToken_) {
this.state_ = SuggestAppsDialog.State.INITIALIZE_FAILED_CLOSING;
this.onHide_();
return;
}
var title = str('SUGGEST_DIALOG_TITLE');
// TODO(yoshiki): Remove this before ShareDialog launches.
if (this.urlOverrided_)
title += ' [OVERRIDED]';
var show =
FileManagerDialogBase.prototype.showTitleOnlyDialog.call(this, title);
if (!show) {
console.error('SuggestAppsDialog can\'t be shown');
this.state_ = SuggestAppsDialog.State.UNINITIALIZED;
this.onHide();
return;
}
this.webviewContainer_.innerHTML =
'<webview id="cws-widget" partition="persist:cwswidgets"></webview>';
this.webview_ = this.container_.querySelector('#cws-widget');
this.webview_.style.width = WEBVIEW_WIDTH + 'px';
this.webview_.style.height = WEBVIEW_HEIGHT + 'px';
this.webview_.request.onBeforeSendHeaders.addListener(
this.authorizeRequest_.bind(this),
{urls: [this.widgetOrigin_ + '/*']},
['blocking', 'requestHeaders']);
this.webview_.addEventListener('newwindow', function(event) {
// Discard the window object and reopen in an external window.
event.window.discard();
util.visitURL(event.targetUrl);
event.preventDefault();
});
this.frame_.classList.add('show-spinner');
this.webviewClient_ = new CWSContainerClient(
this.webview_,
extension, mime,
WEBVIEW_WIDTH, WEBVIEW_HEIGHT,
this.widgetUrl_, this.widgetOrigin_);
this.webviewClient_.addEventListener(CWSContainerClient.Events.LOADED,
this.onWidgetLoaded_.bind(this));
this.webviewClient_.addEventListener(CWSContainerClient.Events.LOAD_FAILED,
this.onWidgetLoadFailed_.bind(this));
this.webviewClient_.addEventListener(
CWSContainerClient.Events.REQUEST_INSTALL,
this.onInstallRequest_.bind(this));
this.webviewClient_.load();
}.bind(this));
};
/**
* Called when the 'See more...' link is clicked to be navigated to Webstore.
* @param {Event} e Evnet.
* @private
*/
SuggestAppsDialog.prototype.onWebstoreLinkClicked_ = function(e) {
var webStoreUrl =
FileTasks.createWebStoreLink(this.extension_, this.mimeType_);
chrome.windows.create({url: webStoreUrl});
this.hide();
};
/**
* Called when the widget is loaded successfuly.
* @param {Event} event Evnet.
* @private
*/
SuggestAppsDialog.prototype.onWidgetLoaded_ = function(event) {
this.frame_.classList.remove('show-spinner');
this.state_ = SuggestAppsDialog.State.INITIALIZED;
this.webview_.focus();
};
/**
* Called when the widget is failed to load.
* @param {Event} event Evnet.
* @private
*/
SuggestAppsDialog.prototype.onWidgetLoadFailed_ = function(event) {
this.frame_.classList.remove('show-spinner');
this.state_ = SuggestAppsDialog.State.INITIALIZE_FAILED_CLOSING;
this.hide();
};
/**
* Called when receiving the install request from the webview client.
* @param {Event} e Evnet.
* @private
*/
SuggestAppsDialog.prototype.onInstallRequest_ = function(e) {
var itemId = e.itemId;
this.installingItemId_ = itemId;
this.appInstaller_ = new AppInstaller(itemId);
this.appInstaller_.install(this.onInstallCompleted_.bind(this));
this.frame_.classList.add('show-spinner');
this.state_ = SuggestAppsDialog.State.INSTALLING;
};
/**
* Called when the installation is completed from the app installer.
* @param {AppInstaller.Result} result Result of the installation.
* @param {string} error Detail of the error.
* @private
*/
SuggestAppsDialog.prototype.onInstallCompleted_ = function(result, error) {
var success = (result === AppInstaller.Result.SUCCESS);
this.frame_.classList.remove('show-spinner');
this.state_ = success ?
SuggestAppsDialog.State.INSTALLED_CLOSING :
SuggestAppsDialog.State.INITIALIZED; // Back to normal state.
this.webviewClient_.onInstallCompleted(success, this.installingItemId_);
this.installingItemId_ = null;
switch (result) {
case AppInstaller.Result.SUCCESS:
this.hide();
break;
case AppInstaller.Result.CANCELLED:
// User cancelled the installation. Do nothing.
break;
case AppInstaller.Result.ERROR:
fileManager.error.show(str('SUGGEST_DIALOG_INSTALLATION_FAILED'));
break;
}
};
/**
* @override
*/
SuggestAppsDialog.prototype.hide = function(opt_originalOnHide) {
switch (this.state_) {
case SuggestAppsDialog.State.INSTALLING:
// Install is being aborted. Send the failure result.
// Cancels the install.
if (this.webviewClient_)
this.webviewClient_.onInstallCompleted(false, this.installingItemId_);
this.installingItemId_ = null;
// Assumes closing the dialog as canceling the install.
this.state_ = SuggestAppsDialog.State.CANCELED_CLOSING;
break;
case SuggestAppsDialog.State.INSTALLED_CLOSING:
case SuggestAppsDialog.State.INITIALIZE_FAILED_CLOSING:
// Do nothing.
break;
case SuggestAppsDialog.State.INITIALIZED:
this.state_ = SuggestAppsDialog.State.CANCELED_CLOSING;
break;
default:
this.state_ = SuggestAppsDialog.State.CANCELED_CLOSING;
console.error('Invalid state.');
}
if (this.webviewClient_) {
this.webviewClient_.dispose();
this.webviewClient_ = null;
}
this.webviewContainer_.innerHTML = '';
this.extension_ = null;
this.mime_ = null;
FileManagerDialogBase.prototype.hide.call(
this,
this.onHide_.bind(this, opt_originalOnHide));
};
/**
* @param {function()=} opt_originalOnHide Original onHide function passed to
* SuggestAppsDialog.hide().
* @private
*/
SuggestAppsDialog.prototype.onHide_ = function(opt_originalOnHide) {
// Calls the callback after the dialog hides.
if (opt_originalOnHide)
opt_originalOnHide();
var result;
switch (this.state_) {
case SuggestAppsDialog.State.INSTALLED_CLOSING:
result = SuggestAppsDialog.Result.INSTALL_SUCCESSFUL;
break;
case SuggestAppsDialog.State.INITIALIZE_FAILED_CLOSING:
result = SuggestAppsDialog.Result.FAILED;
break;
case SuggestAppsDialog.State.CANCELED_CLOSING:
result = SuggestAppsDialog.Result.USER_CANCELL;
break;
default:
result = SuggestAppsDialog.Result.USER_CANCELL;
console.error('Invalid state.');
}
this.state_ = SuggestAppsDialog.State.UNINITIALIZED;
this.onDialogClosed_(result);
};
|
mogoweb/chromium-crosswalk
|
chrome/browser/resources/file_manager/js/suggest_apps_dialog.js
|
JavaScript
|
bsd-3-clause
| 13,909
|
$(document).ready(function() {
/*
* Implementation notes:
* - Update button must have a data-id
* - Update Action button must also have a data-id
*/
// Gather all the fields
var dataTypeSource = "."+$('#data-type-source').html();
var fieldArray = []; // "Question (EN)"
var typeArray = []; // "text", "textarea", "formatted-textarea", etc.
var fieldNameArray = []; // "question_en"
$('.row-fields').first().find(dataTypeSource).each(function() {
fieldArray.push($(this).text());
typeArray.push($(this).data('type'));
fieldNameArray.push($(this).data('field'));
})
// Once the UPDATE button is clicked, fill the modal.
$('.btn-update').on('click', function() {
var dataId = $(this).data('id');
var modalSelector = '.modal-inner-data-'+dataId;
if ($(modalSelector).html().trim() == ""){
$('#row-'+dataId).find('.value').each(function(index, value) {
fillModal($(this), dataId, index, value, fieldArray, typeArray);
});
makeModalTextAreaEditable(modalSelector);
}
});
// Once the SAVE button is clicked, gather the updated information and toss it to the controller.
$('.btn-action-update').on('click', function() {
saveUpdateModal($(this), $(this).data('update-url'), typeArray, fieldNameArray, false);
});
// Once the ADD button is clicked, fill the modal.
$('.btn-add').on('click', function() {
var modalSelector = '.modal-inner-data-new';
if ($(this).parent().find(modalSelector).html().trim() == ""){
$('.row-fields').first().find(dataTypeSource).each(function(index, value) {
fillModalAdd($(this), index, value, fieldArray, typeArray);
});
makeModalTextAreaEditable(modalSelector);
}
});
// Once the INSERT button is clicked, gather the newly-added information and toss it to the controller.
$('.btn-action-add').on('click', function() {
saveUpdateModal($(this), $(this).data('add-url'), typeArray, fieldNameArray, true);
});
// Once the DELETE button is clicked, confirm the destructive action, and delete if the user has approved it.
$(document).on('click', '.btn-delete', function() {
deleteElement('#row-'+$(this).data('id'), $(this).data('delete-url'), $(this).data('id'));
});
// File upload
$(document).on('change', '.browse-file-modal', function() {
// Change the photo
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
// Change photo into a loading pic
var reader = new FileReader();
var browseFileInputParent = $(this).parent();
var loadingGif = $('#ajax-loading-image').data('url')
var oldPhoto = browseFileInputParent.find('img').attr('src');
browseFileInputParent.find('img').attr('src', loadingGif)
reader.onload = function(e) {
// Upload the image file here and return the filename
$.ajax({
type: 'POST',
url: $('#ajax-upload-image').data('url'),
data: {
'image': e.target.result,
'filename': name,
'type': type,
'size': size
},
success: function(msg){
var response = JSON.parse(msg);
if (response.success) {
browseFileInputParent.find('img').attr('src', response.message);
}
else {
alert(response.message);
browseFileInputParent.find('img').attr('src', oldPhoto);
}
},
error: function(msg){
alert('Whoops, looks like something went wrong... \n\n Message: '+msg['responseText']+'\n Refreshing...');
}
});
}
reader.readAsDataURL(this.files[0]);
})
});
function makeModalTextAreaEditable(modalSelector) {
// All newly-added formattable textarea in the modal must be editable
$(modalSelector).find('.formatted-textarea').each(function() {
$(this).tinymce({
menubar: false,
plugins: ['lists link'],
toolbar1: 'bold italic underline link | bullist numlist outdent indent | alignleft aligncenter alignright alignjustify'
});
});
}
function fillModalAdd(dataElement, index, value, fieldArray, typeArray) {
var newDataId = -1;
fillModal(dataElement, newDataId, index, value, fieldArray, typeArray);
}
function deleteElement(selectorToDelete, deleteUrl, id) {
var confirmed = confirm("This action cannot be undone. Are you sure?");
if (confirmed) {
var hideDelay = 500;
$.ajax({
type: 'POST',
url: deleteUrl,
data: {
'id': id
},
success: function(msg){
$(selectorToDelete).hide(hideDelay);
location.reload();
},
error: function(msg){
// alert('Whoops, looks like something went wrong... \n\n Message: '+msg['responseText']+'\n Refreshing...');
alert("An unknown error has occured. Press OK to reload.");
location.reload();
}
});
}
}
function saveUpdateModal(buttonElement, actionUrl, typeArray, fieldNameArray, isNewEntry) {
data = {};
if (isNewEntry == false) {
data['id'] = $(buttonElement).data('id');
}
$(buttonElement).parent().parent().find('.form-group').each(function(index, value) {
var fieldType = typeArray[index];
var result = "";
switch(fieldType) {
case "text":
result = $(this).find('.form-control').val();
break;
case "textarea":
result = $(this).find('.form-control').val();
break;
case "formatted-textarea":
result = $(this).find('iframe').contents().find('html').find('.mce-content-body').html();
break;
case "image-upload":
result = $(this).find('img').attr('src');
break;
case "dropdown":
result = $(this).find('.form-control').val();
break;
default:
alert("NONE>>>"+fieldType);
break;
}
data[fieldNameArray[index]] = result;
});
$.ajax({
type: 'POST',
url: actionUrl,
data: data,
success: function(msg){
// alert(msg);
location.reload();
},
error: function(msg){
alert('Whoops, looks like something went wrong... \n\n Message: '+msg['responseText']+'\n Refreshing...');
// alert("An unknown error has occured. Press OK to reload.");
// location.reload();
}
});
}
function fillModal(dataElement, dataId, index, value, fieldArray, typeArray) {
var valueText = $(dataElement).text().trim(); // e.g.: "banner_zazen.jpg"
var fieldText = fieldArray[index]; // e.g.: "Banner Image"
var fieldType = typeArray[index];
if ($('#data-index-source').html() == 'row') {
fieldType = $(dataElement).data('type');
fieldText = $(dataElement).data('field');
typeArray[index] = fieldType;
fieldArray[index] = fieldText;
}
var selector = '.admin-form-text';
var targetSelector = '.modal-inner-data-'+dataId;
var formId = 'form-'+fieldText;
var isNewEntry = dataId == -1;
if (isNewEntry) {
valueText = '';
targetSelector = '.modal-inner-data-new';
}
switch(fieldType) {
case "text":
selector = ".admin-form-text";
$(selector).find('.form-control').attr('value', valueText);
break;
case "textarea":
selector = ".admin-form-textarea";
$(selector).find('.form-control').text(valueText);
break;
case "formatted-textarea":
selector = ".admin-form-formatted";
if (isNewEntry) {
valueText = '';
}
else {
valueText = $(value).html().trim();
}
$(selector).find('.form-element').html($(selector).find('.form-control-source').html());
$(selector).find('.form-element').find('textarea').text(valueText);
$(selector).find('.form-element').find('textarea').addClass('formatted-textarea');
break;
case "image-upload":
selector = ".admin-form-image";
if (isNewEntry) {
$(selector).find('img').attr('src', $('#no-image').data('url'));
$(selector).find('img').attr('class', $(value).data('class'));
$(selector).find('img').addClass('max-width-100');
}
else {
$(selector).find('img').attr('src', $(value).find('img').attr('src'));
$(selector).find('img').attr('class', $(value).find('img').attr('class'));
$(selector).find('img').addClass('max-width-100');
}
break;
case "dropdown":
selector = ".admin-form-dropdown";
$(selector).find('.form-control').find('option').remove();
var dropdownOptions = $(dataElement).data('dropdown-options');
$.each(dropdownOptions, function(index, value){
$(selector).find('.form-control').append($('<option/>', {
value: index,
text : value
}));
});
break;
default:
alert("NONE>>>"+fieldType);
break;
}
$(selector).find('.control-label').attr('for', formId);
$(selector).find('.control-label').text(fieldText);
$(selector).find('input').attr('id', formId);
$(targetSelector).append($(selector).find('.form-content').html());
}
|
kieferyap/samurai-meetups
|
web/js/admin.js
|
JavaScript
|
bsd-3-clause
| 8,424
|
var searchData=
[
['define_5fmaps',['define_maps',['../structex__block__params.html#ae5b7d28db11451e6a03f7ea193a4a484',1,'ex_block_params']]],
['distribution_5ffactor_5flist',['distribution_factor_list',['../structex__set.html#a55b371867c6117ddf2938c498f5fda32',1,'ex_set']]]
];
|
nschloe/seacas
|
docs/html/search/variables_1.js
|
JavaScript
|
bsd-3-clause
| 283
|
var AnalysisOptionsCollection = require('../../../../../../javascripts/cartodb3/components/modals/add-analysis/analysis-options-collection');
describe('components/modals/add-analysis/analysis-options-collection', function () {
beforeEach(function () {
this.collection = new AnalysisOptionsCollection();
});
describe('when reset with some options', function () {
beforeEach(function () {
this.collection.reset([
{
title: 'A Buffer',
nodeAttrs: {
type: 'buffer'
}
}, {
title: 'A Trade-Area',
nodeAttrs: {
type: 'trade-area'
}
}
]);
});
it('should create a model for given data', function () {
expect(this.collection.length).toEqual(2);
expect(this.collection.first().get('title')).toEqual(jasmine.any(String));
expect(this.collection.first().getFormAttrs).toEqual(jasmine.any(Function));
});
it('should only allow one selection at a time', function () {
expect(this.collection.pluck('selected')).toEqual([false, false]);
this.collection.first().set('selected', true);
expect(this.collection.pluck('selected')).toEqual([true, false]);
this.collection.last().set('selected', true);
expect(this.collection.pluck('selected')).toEqual([false, true]);
});
});
});
|
splashblot/dronedb
|
lib/assets/test/spec/cartodb3/components/modals/add-analysis/analysis-options-collection.spec.js
|
JavaScript
|
bsd-3-clause
| 1,366
|
const path = require('path');
const test = require('tap').test;
const makeTestStorage = require('../fixtures/make-test-storage');
const readFileToBuffer = require('../fixtures/readProjectFile').readFileToBuffer;
const VirtualMachine = require('../../src/index');
const Thread = require('../../src/engine/thread');
const Runtime = require('../../src/engine/runtime');
const execute = require('../../src/engine/execute.js');
const projectUri = path.resolve(__dirname, '../fixtures/timer-greater-than-hat.sb2');
const project = readFileToBuffer(projectUri);
const checkIsHatThread = (t, vm, hatThread) => {
t.equal(hatThread.stackClick, false);
t.equal(hatThread.updateMonitor, false);
const blockContainer = hatThread.target.blocks;
const opcode = blockContainer.getOpcode(blockContainer.getBlock(hatThread.topBlock));
t.assert(vm.runtime.getIsEdgeActivatedHat(opcode));
};
const checkIsStackClickThread = (t, vm, stackClickThread) => {
t.equal(stackClickThread.stackClick, true);
t.equal(stackClickThread.updateMonitor, false);
};
/**
* timer-greater-than-hat.sb2 contains a single stack
* when timer > -1
* change color effect by 25
* The intention is to make sure that the hat block condition is evaluated
* on each frame.
*/
test('edge activated hat thread runs once every frame', t => {
const vm = new VirtualMachine();
vm.attachStorage(makeTestStorage());
// Start VM, load project, and run
t.doesNotThrow(() => {
// Note: don't run vm.start(), we handle calling _step() manually in this test
vm.runtime.currentStepTime = Runtime.THREAD_STEP_INTERVAL;
vm.clear();
vm.setCompatibilityMode(false);
vm.setTurboMode(false);
vm.loadProject(project).then(() => {
t.equal(vm.runtime.threads.length, 0);
vm.runtime._step();
let threads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 0);
t.equal(threads.length, 1);
checkIsHatThread(t, vm, threads[0]);
t.assert(threads[0].status === Thread.STATUS_DONE);
// Check that the hat thread is added again when another step is taken
vm.runtime._step();
threads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 0);
t.equal(threads.length, 1);
checkIsHatThread(t, vm, threads[0]);
t.assert(threads[0].status === Thread.STATUS_DONE);
t.end();
});
});
});
/**
* When a hat is added it should run in the next frame. Any block related
* caching should be reset.
*/
test('edge activated hat thread runs after being added to previously executed target', t => {
const vm = new VirtualMachine();
vm.attachStorage(makeTestStorage());
// Start VM, load project, and run
t.doesNotThrow(() => {
// Note: don't run vm.start(), we handle calling _step() manually in this test
vm.runtime.currentStepTime = Runtime.THREAD_STEP_INTERVAL;
vm.clear();
vm.setCompatibilityMode(false);
vm.setTurboMode(false);
vm.loadProject(project).then(() => {
t.equal(vm.runtime.threads.length, 0);
vm.runtime._step();
let threads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 0);
t.equal(threads.length, 1);
checkIsHatThread(t, vm, threads[0]);
t.assert(threads[0].status === Thread.STATUS_DONE);
// Add a second hat that should create a second thread
const hatBlock = threads[0].target.blocks.getBlock(threads[0].topBlock);
threads[0].target.blocks.createBlock(Object.assign(
{}, hatBlock, {id: 'hatblock2', next: null}
));
// Check that the hat thread is added again when another step is taken
vm.runtime._step();
threads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 0);
t.equal(threads.length, 2);
checkIsHatThread(t, vm, threads[0]);
checkIsHatThread(t, vm, threads[1]);
t.assert(threads[0].status === Thread.STATUS_DONE);
t.assert(threads[1].status === Thread.STATUS_DONE);
t.end();
});
});
});
/**
* If the hat doesn't finish evaluating within one frame, it shouldn't be added again
* on the next frame. (We skip execution by setting the step time to 0)
*/
test('edge activated hat thread not added twice', t => {
const vm = new VirtualMachine();
vm.attachStorage(makeTestStorage());
// Start VM, load project, and run
t.doesNotThrow(() => {
// Note: don't run vm.start(), we handle calling _step() manually in this test
vm.runtime.currentStepTime = 0;
vm.clear();
vm.setCompatibilityMode(false);
vm.setTurboMode(false);
vm.loadProject(project).then(() => {
t.equal(vm.runtime.threads.length, 0);
vm.runtime._step();
let doneThreads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 1);
t.equal(doneThreads.length, 0);
const prevThread = vm.runtime.threads[0];
checkIsHatThread(t, vm, vm.runtime.threads[0]);
t.assert(vm.runtime.threads[0].status === Thread.STATUS_RUNNING);
// Check that no new threads are added when another step is taken
vm.runtime._step();
doneThreads = vm.runtime._lastStepDoneThreads;
// There should now be one done hat thread and one new hat thread to run
t.equal(vm.runtime.threads.length, 1);
t.equal(doneThreads.length, 0);
checkIsHatThread(t, vm, vm.runtime.threads[0]);
t.assert(vm.runtime.threads[0] === prevThread);
t.end();
});
});
});
/**
* Duplicating a sprite should also track duplicated edge activated hat in
* runtime's _edgeActivatedHatValues map.
*/
test('edge activated hat should trigger for both sprites when sprite is duplicated', t => {
// Project that is similar to timer-greater-than-hat.sb2, but has code on the sprite so that
// the sprite can be duplicated
const projectWithSpriteUri = path.resolve(__dirname, '../fixtures/edge-triggered-hat.sb3');
const projectWithSprite = readFileToBuffer(projectWithSpriteUri);
const vm = new VirtualMachine();
vm.attachStorage(makeTestStorage());
// Start VM, load project, and run
t.doesNotThrow(() => {
// Note: don't run vm.start(), we handle calling _step() manually in this test
vm.runtime.currentStepTime = 0;
vm.clear();
vm.setCompatibilityMode(false);
vm.setTurboMode(false);
vm.loadProject(projectWithSprite).then(() => {
t.equal(vm.runtime.threads.length, 0);
vm.runtime._step();
t.equal(vm.runtime.threads.length, 1);
checkIsHatThread(t, vm, vm.runtime.threads[0]);
t.assert(vm.runtime.threads[0].status === Thread.STATUS_RUNNING);
let numTargetEdgeHats = vm.runtime.targets.reduce((val, target) =>
val + Object.keys(target._edgeActivatedHatValues).length, 0);
t.equal(numTargetEdgeHats, 1);
vm.duplicateSprite(vm.runtime.targets[1].id).then(() => {
vm.runtime._step();
// Check that the runtime's _edgeActivatedHatValues object has two separate keys
// after execute is run on each thread
numTargetEdgeHats = vm.runtime.targets.reduce((val, target) =>
val + Object.keys(target._edgeActivatedHatValues).length, 0);
t.equal(numTargetEdgeHats, 2);
t.end();
});
});
});
});
/**
* Cloning a sprite should also track cloned edge activated hat separately
* runtime's _edgeActivatedHatValues map.
*/
test('edge activated hat should trigger for both sprites when sprite is cloned', t => {
// Project that is similar to loudness-hat-block.sb2, but has code on the sprite so that
// the sprite can be duplicated
const projectWithSpriteUri = path.resolve(__dirname, '../fixtures/edge-triggered-hat.sb3');
const projectWithSprite = readFileToBuffer(projectWithSpriteUri);
const vm = new VirtualMachine();
vm.attachStorage(makeTestStorage());
// Start VM, load project, and run
t.doesNotThrow(() => {
// Note: don't run vm.start(), we handle calling _step() manually in this test
vm.runtime.currentStepTime = 0;
vm.clear();
vm.setCompatibilityMode(false);
vm.setTurboMode(false);
vm.loadProject(projectWithSprite).then(() => {
t.equal(vm.runtime.threads.length, 0);
vm.runtime._step();
t.equal(vm.runtime.threads.length, 1);
checkIsHatThread(t, vm, vm.runtime.threads[0]);
t.assert(vm.runtime.threads[0].status === Thread.STATUS_RUNNING);
// Run execute on the thread to populate the runtime's
// _edgeActivatedHatValues object
execute(vm.runtime.sequencer, vm.runtime.threads[0]);
let numTargetEdgeHats = vm.runtime.targets.reduce((val, target) =>
val + Object.keys(target._edgeActivatedHatValues).length, 0);
t.equal(numTargetEdgeHats, 1);
const cloneTarget = vm.runtime.targets[1].makeClone();
vm.runtime.addTarget(cloneTarget);
vm.runtime._step();
// Check that the runtime's _edgeActivatedHatValues object has two separate keys
// after execute is run on each thread
vm.runtime.threads.forEach(thread => execute(vm.runtime.sequencer, thread));
numTargetEdgeHats = vm.runtime.targets.reduce((val, target) =>
val + Object.keys(target._edgeActivatedHatValues).length, 0);
t.equal(numTargetEdgeHats, 2);
t.end();
});
});
});
/**
* When adding a stack click thread first, make sure that the edge activated hat thread and
* the stack click thread are both pushed and run (despite having the same top block)
*/
test('edge activated hat thread does not interrupt stack click thread', t => {
const vm = new VirtualMachine();
vm.attachStorage(makeTestStorage());
// Start VM, load project, and run
t.doesNotThrow(() => {
// Note: don't run vm.start(), we handle calling _step() manually in this test
vm.runtime.currentStepTime = Runtime.THREAD_STEP_INTERVAL;
vm.clear();
vm.setCompatibilityMode(false);
vm.setTurboMode(false);
vm.loadProject(project).then(() => {
t.equal(vm.runtime.threads.length, 0);
vm.runtime._step();
let doneThreads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 0);
t.equal(doneThreads.length, 1);
checkIsHatThread(t, vm, doneThreads[0]);
t.assert(doneThreads[0].status === Thread.STATUS_DONE);
// Add stack click thread on this hat
vm.runtime.toggleScript(doneThreads[0].topBlock, {stackClick: true});
// Check that the hat thread is added again when another step is taken
vm.runtime._step();
doneThreads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 0);
t.equal(doneThreads.length, 2);
let hatThread;
let stackClickThread;
if (doneThreads[0].stackClick) {
stackClickThread = doneThreads[0];
hatThread = doneThreads[1];
} else {
stackClickThread = doneThreads[1];
hatThread = doneThreads[0];
}
checkIsHatThread(t, vm, hatThread);
checkIsStackClickThread(t, vm, stackClickThread);
t.assert(doneThreads[0].status === Thread.STATUS_DONE);
t.assert(doneThreads[1].status === Thread.STATUS_DONE);
t.end();
});
});
});
/**
* When adding the hat thread first, make sure that the edge activated hat thread and
* the stack click thread are both pushed and run (despite having the same top block)
*/
test('edge activated hat thread does not interrupt stack click thread', t => {
const vm = new VirtualMachine();
vm.attachStorage(makeTestStorage());
// Start VM, load project, and run
t.doesNotThrow(() => {
// Note: don't run vm.start(), we handle calling _step() manually in this test
vm.runtime.currentStepTime = 0;
vm.clear();
vm.setCompatibilityMode(false);
vm.setTurboMode(false);
vm.loadProject(project).then(() => {
t.equal(vm.runtime.threads.length, 0);
vm.runtime._step();
let doneThreads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 1);
t.equal(doneThreads.length, 0);
checkIsHatThread(t, vm, vm.runtime.threads[0]);
t.assert(vm.runtime.threads[0].status === Thread.STATUS_RUNNING);
vm.runtime.currentStepTime = Runtime.THREAD_STEP_INTERVAL;
// Add stack click thread on this hat
vm.runtime.toggleScript(vm.runtime.threads[0].topBlock, {stackClick: true});
// Check that the hat thread is added again when another step is taken
vm.runtime._step();
doneThreads = vm.runtime._lastStepDoneThreads;
t.equal(vm.runtime.threads.length, 0);
t.equal(doneThreads.length, 2);
let hatThread;
let stackClickThread;
if (doneThreads[0].stackClick) {
stackClickThread = doneThreads[0];
hatThread = doneThreads[1];
} else {
stackClickThread = doneThreads[1];
hatThread = doneThreads[0];
}
checkIsHatThread(t, vm, hatThread);
checkIsStackClickThread(t, vm, stackClickThread);
t.assert(doneThreads[0].status === Thread.STATUS_DONE);
t.assert(doneThreads[1].status === Thread.STATUS_DONE);
t.end();
});
});
});
|
LLK/scratch-vm
|
test/integration/hat-threads-run-every-frame.js
|
JavaScript
|
bsd-3-clause
| 14,338
|
(function ($) {
$.fn.extend({
formsetHelpers: function () {
return this.each(function () {
var obj = $(this);
function check_more_than_one(element) {
// Check if the element is the last one
if ($(element).parent().children("input").length > 1)
return true;
return false;
}
function remove_input(element) {
// Hide the element and remove it
if (check_more_than_one(element))
$(element).fadeOut(function callback() {
$(element).remove();
});
}
function add_input(element) {
// Append one input to the parent div
base_name = $(element).attr("id").split("-")[0];
$(element).parent().append('<input style="display: none" id="' + base_name +
'" name="' + base_name + '" type="text">');
input = $(element).parent().children("input:last-child");
input.fadeIn();
assignEvents(input); // Assign event to thew new input
}
function reindex() {
// Create autoenumerate index for all the inputs inside the container
base_identifier = obj.children("input:first").attr("id").split("-")[0];
index = 0;
obj.children("input").each(function assignNewIndex() {
$(this).attr("id", base_identifier + "-" + index);
$(this).attr("name", base_identifier + "-" + index);
index++;
});
}
function assignEvents(element) {
// Remove input if empty
$(element).change(function onChange() {
if (!$(this).val())
remove_input($(this));
});
// Add input if is needed
$(element).bind("keypress change", function addIfNeeded() {
if ($(this).parent().children("input:last-child").val()) //The last one should be non-empty
add_input($(this));
});
// Remove empty fields (the last ones) and reindex all the elements
$(element).parents("form").submit(function clearEmptyBeforeSubmit() {
obj.children("input").each(function removeIfEmpty() {
if (!$(this).val())
$(this).remove();
});
reindex();
});
}
// First time events
obj.children("input").each(function assignAllEvent() {
assignEvents($(this));
});
// Add extra input only if the first is not empty.
obj.children("input:last-child").each(function addExtraInput() {
if ($(this).parent().children("input:first").val())
add_input($(this));
});
}); //Close jQuery plugin
}
});
})(jQuery);
|
paylogic/jquery-wtforms-formset
|
src/jquery-wtforms-formset.js
|
JavaScript
|
bsd-3-clause
| 2,791
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.define('settings', function() {
/**
* The state of the preference controlling Smart Lock's ability to sign-in the
* user.
* @enum {string}
*/
const SignInEnabledState = {
ENABLED: 'enabled',
DISABLED: 'disabled',
};
Polymer({
is: 'settings-multidevice-smartlock-subpage',
behaviors: [
MultiDeviceFeatureBehavior,
WebUIListenerBehavior,
],
properties: {
/** @type {?OsSettingsRoutes} */
routes: {
type: Object,
value: settings.routes,
},
/**
* True if Smart Lock is enabled.
* @private
*/
smartLockEnabled_: {
type: Boolean,
computed: 'computeIsSmartLockEnabled_(pageContentData)',
},
/**
* Whether Smart Lock may be used to sign-in the user (as opposed to only
* being able to unlock the user's screen).
* @private {!settings.SignInEnabledState}
*/
smartLockSignInEnabled_: {
type: Object,
value: SignInEnabledState.DISABLED,
},
/**
* True if the user is allowed to enable Smart Lock sign-in.
* @private
*/
smartLockSignInAllowed_: {
type: Boolean,
value: true,
},
/** @private */
showPasswordPromptDialog_: {
type: Boolean,
value: false,
},
/**
* Authentication token provided by password-prompt-dialog.
* @private {!chrome.quickUnlockPrivate.TokenInfo|undefined}
*/
authToken_: {
type: Object,
},
},
/** @private {?settings.MultiDeviceBrowserProxy} */
browserProxy_: null,
/** @override */
ready() {
this.browserProxy_ = settings.MultiDeviceBrowserProxyImpl.getInstance();
this.addWebUIListener(
'smart-lock-signin-enabled-changed',
this.updateSmartLockSignInEnabled_.bind(this));
this.addWebUIListener(
'smart-lock-signin-allowed-changed',
this.updateSmartLockSignInAllowed_.bind(this));
this.browserProxy_.getSmartLockSignInEnabled().then(enabled => {
this.updateSmartLockSignInEnabled_(enabled);
});
this.browserProxy_.getSmartLockSignInAllowed().then(allowed => {
this.updateSmartLockSignInAllowed_(allowed);
});
},
/**
* Returns true if Smart Lock is an enabled feature.
* @return {boolean}
* @private
*/
computeIsSmartLockEnabled_() {
return !!this.pageContentData &&
this.getFeatureState(settings.MultiDeviceFeature.SMART_LOCK) ==
settings.MultiDeviceFeatureState.ENABLED_BY_USER;
},
/**
* Updates the state of the Smart Lock 'sign-in enabled' toggle.
* @private
*/
updateSmartLockSignInEnabled_(enabled) {
this.smartLockSignInEnabled_ =
enabled ? SignInEnabledState.ENABLED : SignInEnabledState.DISABLED;
},
/**
* Updates the Smart Lock 'sign-in enabled' toggle such that disallowing
* sign-in disables the toggle.
* @private
*/
updateSmartLockSignInAllowed_(allowed) {
this.smartLockSignInAllowed_ = allowed;
},
/** @private */
openPasswordPromptDialog_() {
this.showPasswordPromptDialog_ = true;
},
/**
* Sets the Smart Lock 'sign-in enabled' pref based on the value of the
* radio group representing the pref.
* @private
*/
onSmartLockSignInEnabledChanged_() {
const radioGroup = this.$$('cr-radio-group');
const enabled = radioGroup.selected == SignInEnabledState.ENABLED;
if (!enabled) {
// No authentication check is required to disable.
this.browserProxy_.setSmartLockSignInEnabled(false /* enabled */);
settings.recordSettingChange();
return;
}
// Toggle the enabled state back to disabled, as authentication may not
// succeed. The toggle state updates automatically by the pref listener.
radioGroup.selected = SignInEnabledState.DISABLED;
this.openPasswordPromptDialog_();
},
/**
* Updates the state of the password dialog controller flag when the UI
* element closes.
* @private
*/
onEnableSignInDialogClose_() {
this.showPasswordPromptDialog_ = false;
// If |this.authToken_| is set when the dialog has been closed, this means
// that the user entered the correct password into the dialog when
// attempting to enable SignIn with Smart Lock.
if (this.authToken_) {
this.browserProxy_.setSmartLockSignInEnabled(
true /* enabled */, this.authToken_.token);
settings.recordSettingChange();
}
// Always require password entry if re-enabling SignIn with Smart Lock.
this.authToken_ = undefined;
},
/**
* @param {!CustomEvent<!chrome.quickUnlockPrivate.TokenInfo>} e
* @private
*/
onTokenObtained_(e) {
this.authToken_ = e.detail;
},
});
// #cr_define_end
return {
SignInEnabledState: SignInEnabledState,
};
});
|
endlessm/chromium-browser
|
chrome/browser/resources/settings/chromeos/multidevice_page/multidevice_smartlock_subpage.js
|
JavaScript
|
bsd-3-clause
| 5,211
|
import PropTypes from 'prop-types';
import React from 'react';
import Chip from 'material-ui/Chip';
import s from './SelectedItemsContainer.scss';
function SelectedItemsContainer(props) {
const {
collectionName, items, removeItem, className,
} = props;
const selectedItemsContainer = items.map((item, index) => {
const renderedLabel = (typeof props.renderLabel === 'function') ? props.renderLabel(item) : item;
const handleClicked = (event) => {
event.stopPropagation();
event.preventDefault();
removeItem(collectionName, item);
};
return (
<div
className={s.searchChip}
key={JSON.stringify(item)}
onClick={handleClicked}
onKeyPress={handleClicked}
role="button"
tabIndex="0"
>
<Chip
onRequestDelete={handleClicked}
>
{renderedLabel}
</Chip>
</div>
);
});
return items.length ? (
<div className={[s.searchByContainer, className].join(' ')}>
<div className={s.searchChips}>
{selectedItemsContainer}
</div>
</div>
) : null;
}
SelectedItemsContainer.propTypes = {
collectionName: PropTypes.string.isRequired,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
removeItem: PropTypes.func.isRequired,
renderLabel: PropTypes.func,
className: PropTypes.string,
};
SelectedItemsContainer.defaultProps = {
renderLabel: undefined,
className: '',
};
export default SelectedItemsContainer;
|
uprisecampaigns/uprise-app
|
app/client/src/components/SelectedItemsContainer/SelectedItemsContainer.js
|
JavaScript
|
bsd-3-clause
| 1,497
|
var searchData=
[
['arglist',['argList',['../structLambda.html#a7f50d0df92708ab9fc9d8c770e9adbaf',1,'Lambda']]]
];
|
vidarr/fulisp
|
doc/doxygen/html/search/variables_0.js
|
JavaScript
|
bsd-3-clause
| 117
|
/**
* Copyright (c) 2013-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.
*
* @emails oncall+relay
*/
'use strict';
require('configureForRelayOSS');
const Relay = require('Relay');
const RelayTestUtils = require('RelayTestUtils');
const flattenRelayQuery = require('flattenRelayQuery');
describe('flattenRelayQuery', () => {
var {getNode} = RelayTestUtils;
beforeEach(() => {
jasmine.addMatchers(RelayTestUtils.matchers);
});
it('flattens roots', () => {
var node = getNode(Relay.QL`
query {
viewer {
... on Viewer {
actor {
name
}
}
actor {
firstName,
... on Actor {
lastName
}
}
}
}
`);
var expected = getNode(Relay.QL`
query {
viewer {
actor {
firstName,
name,
lastName
}
}
}
`);
expect(flattenRelayQuery(node)).toEqualQueryRoot(expected);
});
it('flattens fragments', () => {
var node = getNode(Relay.QL`
fragment on Viewer {
actor {
firstName,
... on Actor {
lastName
... on Actor {
name
... on User {
username
}
}
}
}
}
`);
var expected = getNode(Relay.QL`
fragment on Viewer {
actor {
firstName,
lastName,
name,
... on User {
username
}
}
}
`);
expect(flattenRelayQuery(node)).toEqualQueryNode(expected);
});
it('flattens fields', () => {
var node = getNode(Relay.QL`
query {
viewer {
actor {
firstName,
name,
... on Actor {
name,
lastName
}
}
}
}
`).getFieldByStorageKey('actor');
var expected = getNode(Relay.QL`
query {
viewer {
actor {
firstName,
name,
lastName
}
}
}
`).getFieldByStorageKey('actor');
expect(flattenRelayQuery(node)).toEqualQueryNode(expected);
});
it('flattens empty fragments', () => {
var emptyFragment = Relay.QL`
fragment on TimezoneInfo {
${null}
}
`;
var fragmentNode = getNode(emptyFragment);
var rootNode = getNode(Relay.QL`
query {
viewer {
timezoneEstimate {
${emptyFragment}
}
}
}
`);
var fieldNode = rootNode.getFieldByStorageKey('timezoneEstimate');
expect(flattenRelayQuery(fragmentNode)).toBe(null);
expect(flattenRelayQuery(rootNode)).toBe(null);
expect(flattenRelayQuery(fieldNode)).toBe(null);
});
it('optionally removes fragments', () => {
var node = getNode(Relay.QL`
query {
viewer {
... on Viewer {
actor {
... on User {
firstName
}
... on Page {
name
}
}
}
}
}
`);
var expected = getNode(Relay.QL`
query {
viewer {
actor {
firstName,
name
}
}
}
`);
expect(flattenRelayQuery(node, {
shouldRemoveFragments: true,
})).toEqualQueryNode(expected);
});
it('optionally preserves empty non-leaf nodes', () => {
var node = getNode(Relay.QL`
fragment on Comment {
likers # can have sub-selections, normally is removed
doesViewerLike
}
`);
const flattened = flattenRelayQuery(node, {
preserveEmptyNodes: true,
});
expect(flattened.getChildren().length).toBe(3);
expect(flattened.getChildren()[0].getSchemaName()).toBe('likers');
expect(flattened.getChildren()[1].getSchemaName()).toBe('doesViewerLike');
expect(flattened.getChildren()[2].getSchemaName()).toBe('id');
});
});
|
venepe/relay
|
src/traversal/__tests__/flattenRelayQuery-test.js
|
JavaScript
|
bsd-3-clause
| 4,292
|
/**
* @constructor
* @template V
*/
de.benshu.ko.dataSource.Query = function () {};
/**
* @constructor
* @template V
* @extends {de.benshu.ko.dataSource.Query<V>}
*/
de.benshu.ko.dataSource.LimitableQueryConfigurator = function () {};
/**
* @param limit
* @returns {de.benshu.ko.dataSource.Query<V>}
*/
de.benshu.ko.dataSource.LimitableQueryConfigurator.prototype.limitedTo = function (limit) {};
/**
* @constructor
* @template V
* @extends {de.benshu.ko.dataSource.LimitableQueryConfigurator<V>}
*/
de.benshu.ko.dataSource.OffsettableQueryConfigurator = function () {};
/**
* @param offset
* @returns {de.benshu.ko.dataSource.FilterableQueryConfigurator<V>}
*/
de.benshu.ko.dataSource.OffsettableQueryConfigurator.prototype.offsetBy = function (offset) {};
/**
* @constructor
* @template V
* @extends {de.benshu.ko.dataSource.OffsettableQueryConfigurator<V>}
*/
de.benshu.ko.dataSource.SortableQueryConfigurator = function () {};
/**
* @param comparator
* @returns {de.benshu.ko.dataSource.OffsettableQueryConfigurator<V>}
*/
de.benshu.ko.dataSource.SortableQueryConfigurator.prototype.sortedBy = function (comparator) {};
/**
* @constructor
* @template V
* @extends {de.benshu.ko.dataSource.SortableQueryConfigurator<V>}
*/
de.benshu.ko.dataSource.FilterableQueryConfigurator = function () {};
/**
* @param predicate
* @returns {de.benshu.ko.dataSource.FilterableQueryConfigurator<V>}
*/
de.benshu.ko.dataSource.FilterableQueryConfigurator.prototype.filteredBy = function (predicate) {};
/**
* @constructor
* @template V
* @extends {de.benshu.ko.dataSource.FilterableQueryConfigurator<V>}
*/
de.benshu.ko.dataSource.QueryConfigurator = function () {};
|
benschulz/ko-data-source
|
api/query-configuration.externs.js
|
JavaScript
|
bsd-3-clause
| 1,698
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { Image } from 'react-bootstrap';
import Helmet from 'react-helmet';
import { getFeaturedList } from '../../utils/ajax';
import { Loader, Spacer } from '../../../common/app/helperComponents';
import BannerWide from '../../components/BannerWide';
import ArticleMeta from '../../components/ArticleMeta';
const propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired
})
};
const styles = `
.featured-list {
list-style: none;
padding-left: 0;
margin-top: 40px;
}
.featured-list-item {
padding-bottom: 20px;
}
.featured-list-item .title {
color: #333;
padding-bottom: 20px;
}
.featured-list-item a {
padding-top: 5px;
}
.featured-list-image {
margin: 0 auto;
}
.featured-list-item a:hover,
.featured-list-item a:focus {
text-decoration: none;
text-decoration-line: none;
text-decoration-color: transparaent;
}
.featured-list-item a:hover > .meta-wrapper,
.featured-list-item a:focus > .meta-wrapper {
color: #006400;
}
`;
class Featured extends Component {
constructor(props) {
super(props);
this.state = {
fetchState: {
pending: false,
complete: false,
errored: false,
error: null
},
featuredList: []
};
this.fetchFeaturedList = this.fetchFeaturedList.bind(this);
}
componentDidMount() {
return this.fetchFeaturedList();
}
fetchFeaturedList() {
return this.setState(
{
fetchState: { pending: true, complete: false, errored: false }
},
() =>
getFeaturedList().then(({ data }) =>
this.setState({
featuredList: data,
fetchState: {
pending: false,
complete: true,
errored: false,
error: null
}
})
)
);
}
createHandleArticleClick(slug, article) {
const { history } = this.props;
return e => {
e.preventDefault();
return history.push({ pathname: slug, state: { article } });
};
}
renderFeatured(articles) {
return articles.map(article => {
const slug = `/${article.author.username}/`.concat(
article.slugPart,
'--',
article.shortId
);
const { featureImage, shortId, title } = article;
return (
<li className='featured-list-item' key={shortId}>
<a
href={'/news' + slug}
onClick={this.createHandleArticleClick(slug, article)}
>
<h3 className='title'>{title}</h3>
{featureImage && featureImage.src ? (
<Image
className='featured-list-image'
responsive={true}
src={featureImage.src}
/>
) : (
<BannerWide />
)}
<ArticleMeta article={article} />
</a>
<Spacer />
</li>
);
});
}
render() {
const {
fetchState: { pending, complete, errored },
featuredList
} = this.state;
if (pending || !complete) {
return (
<div className='full-size' style={{ position: 'fixed', left: 0 }}>
<Loader />
</div>
);
}
if (complete && errored) {
return <h2>Oh noes!! Something went wrong!</h2>;
}
return (
<div>
<Helmet>
<style>{styles}</style>
</Helmet>
<ul className='featured-list'>{this.renderFeatured(featuredList)}</ul>
</div>
);
}
}
Featured.displayName = 'Featured';
Featured.propTypes = propTypes;
export default withRouter(Featured);
|
MiloATH/FreeCodeCamp
|
news/routes/Featured/Featured.js
|
JavaScript
|
bsd-3-clause
| 3,769
|
const debug = require('debug')('github-metrics:config:logger');
const os = require('os');
const path = require('path');
const makeDir = require('make-dir');
const split = require('split');
const DailyRotateFile = require('winston-daily-rotate-file');
const winston = require('winston');
debug('configuring logger');
const pkg = require('../../package.json');
winston.emitErrs = true;
const logDirectory = path.join(os.homedir(), `.${pkg.name}/logs`);
makeDir.sync(logDirectory);
const logger = new winston.Logger({
transports: [
new DailyRotateFile({
level: 'info',
filename: path.join(logDirectory, '.out'),
datePattern: 'dd-MM-yyyy.log',
prepend: true,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
maxDays: 10,
colorize: false,
}),
new winston.transports.Console({
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
}),
],
exitOnError: false,
});
module.exports = logger;
module.exports.stream = split().on('data', (message) => {
logger.info(message);
});
|
rodrigogs/github-metrics
|
src/config/logger.js
|
JavaScript
|
bsd-3-clause
| 1,119
|
({
openReleaseGateModal: function (component, eventParameters) {
const releaseGateAction = eventParameters.releaseGateAction;
const productRegistryName = eventParameters.productRegistryName;
const productName = eventParameters.productName;
const productLabel = eventParameters.productLabel;
const releaseGateName = eventParameters.releaseGateName;
const releaseGateLabel = eventParameters.releaseGateLabel;
component.set("v.releaseGateAction", releaseGateAction);
component.set("v.productRegistryName", productRegistryName);
component.set("v.productName", productName);
component.set("v.productLabel", productLabel);
component.set("v.releaseGateName", releaseGateName);
component.set("v.releaseGateLabel", releaseGateLabel);
let modalBody;
let modalFooter;
let modalHeaderLabel;
let confirmButton;
let cancelButton;
switch (component.get("v.releaseGateAction")) {
case "activate":
modalHeaderLabel = $A.get("$Label.c.stgReleaseGateActivate").replace("{0}", releaseGateLabel);
cancelButton = $A.get("$Label.c.stgBtnCancel");
confirmButton = $A.get("$Label.c.stgBtnReleaseGateActivate");
break;
}
$A.createComponents(
[
[
"c:releaseGateModal",
{
releaseGateAction: component.get("v.releaseGateAction"),
productRegistryName: component.get("v.productRegistryName"),
productName: component.get("v.productName"),
productLabel: component.get("v.productLabel"),
releaseGateName: component.get("v.releaseGateName"),
releaseGateLabel: component.get("v.releaseGateLabel")
}
],
[
"c:customModalFooter",
{
confirmButtonLabel: confirmButton,
confirmButtonTitle: confirmButton,
cancelButtonLabel: cancelButton,
cancelButtonTitle: cancelButton,
customModalFooterEvent: component.getReference("c.handleModalFooterEvent")
}
]
],
function (components, status) {
if (status === "SUCCESS") {
modalBody = components[0];
modalFooter = components[1];
//Create the modal
component.find("edaOverlayLibrary").showCustomModal({
header: modalHeaderLabel,
body: modalBody,
footer: modalFooter,
showCloseButton: false
});
}
}
);
},
handleModalFooterEvent: function (component, event) {
event.stopPropagation();
switch (event.getParam("action")) {
case "confirm":
this.handleModalFooterConfirm(component);
break;
}
},
handleModalFooterConfirm: function (component) {
switch (component.get("v.releaseGateAction")) {
case "activate":
this.handleModalActionConfirm(component);
break;
}
},
handleModalActionConfirm: function (component) {
let modalSaveEvent = component.getEvent("modalSaveEvent");
const saveModel = this.getReleaseGateModel(component);
modalSaveEvent.setParams({
saveModel: saveModel
});
modalSaveEvent.fire();
},
getReleaseGateModel: function (component) {
const releaseGateAction = component.get("v.releaseGateAction");
const productRegistryName = component.get("v.productRegistryName");
const productName = component.get("v.productName");
const productLabel = component.get("v.productLabel");
const releaseGateName = component.get("v.releaseGateName");
const releaseGateLabel = component.get("v.releaseGateLabel");
return {
modalType: "releasegate",
releaseGateAction: releaseGateAction,
productRegistryName: productRegistryName,
productName: productName,
productLabel: productLabel,
releaseGateName: releaseGateName,
releaseGateLabel: releaseGateLabel
};
}
});
|
SalesforceFoundation/HEDAP
|
force-app/main/releaseGating/aura/releaseGateModalOpener/releaseGateModalOpenerHelper.js
|
JavaScript
|
bsd-3-clause
| 4,591
|
// 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.
cr.define('options', function() {
/////////////////////////////////////////////////////////////////////////////
// OptionsPage class:
/**
* Base class for options page.
* @constructor
* @param {string} name Options page name.
* @param {string} title Options page title, used for history.
* @extends {EventTarget}
*/
function OptionsPage(name, title, pageDivName) {
this.name = name;
this.title = title;
this.pageDivName = pageDivName;
this.pageDiv = $(this.pageDivName);
this.tab = null;
this.lastFocusedElement = null;
}
/**
* This is the absolute difference maintained between standard and
* fixed-width font sizes. Refer http://crbug.com/91922.
* @const
*/
OptionsPage.SIZE_DIFFERENCE_FIXED_STANDARD = 3;
/**
* Offset of page container in pixels, to allow room for side menu.
* Simplified settings pages can override this if they don't use the menu.
* The default (155) comes from -webkit-margin-start in uber_shared.css
* @private
*/
OptionsPage.horizontalOffset = 155;
/**
* Main level option pages. Maps lower-case page names to the respective page
* object.
* @protected
*/
OptionsPage.registeredPages = {};
/**
* Pages which are meant to behave like modal dialogs. Maps lower-case overlay
* names to the respective overlay object.
* @protected
*/
OptionsPage.registeredOverlayPages = {};
/**
* Gets the default page (to be shown on initial load).
*/
OptionsPage.getDefaultPage = function() {
return BrowserOptions.getInstance();
};
/**
* Shows the default page.
*/
OptionsPage.showDefaultPage = function() {
this.navigateToPage(this.getDefaultPage().name);
};
/**
* "Navigates" to a page, meaning that the page will be shown and the
* appropriate entry is placed in the history.
* @param {string} pageName Page name.
*/
OptionsPage.navigateToPage = function(pageName) {
this.showPageByName(pageName, true);
};
/**
* Shows a registered page. This handles both top-level and overlay pages.
* @param {string} pageName Page name.
* @param {boolean} updateHistory True if we should update the history after
* showing the page.
* @param {Object=} opt_propertyBag An optional bag of properties including
* replaceState (if history state should be replaced instead of pushed).
* @private
*/
OptionsPage.showPageByName = function(pageName,
updateHistory,
opt_propertyBag) {
// If |opt_propertyBag| is non-truthy, homogenize to object.
opt_propertyBag = opt_propertyBag || {};
// If a bubble is currently being shown, hide it.
this.hideBubble();
// Find the currently visible root-level page.
var rootPage = null;
for (var name in this.registeredPages) {
var page = this.registeredPages[name];
if (page.visible && !page.parentPage) {
rootPage = page;
break;
}
}
// Find the target page.
var targetPage = this.registeredPages[pageName.toLowerCase()];
if (!targetPage || !targetPage.canShowPage()) {
// If it's not a page, try it as an overlay.
if (!targetPage && this.showOverlay_(pageName, rootPage)) {
if (updateHistory)
this.updateHistoryState_(!!opt_propertyBag.replaceState);
return;
} else {
targetPage = this.getDefaultPage();
}
}
pageName = targetPage.name.toLowerCase();
var targetPageWasVisible = targetPage.visible;
// Determine if the root page is 'sticky', meaning that it
// shouldn't change when showing an overlay. This can happen for special
// pages like Search.
var isRootPageLocked =
rootPage && rootPage.sticky && targetPage.parentPage;
var allPageNames = Array.prototype.concat.call(
Object.keys(this.registeredPages),
Object.keys(this.registeredOverlayPages));
// Notify pages if they will be hidden.
for (var i = 0; i < allPageNames.length; ++i) {
var name = allPageNames[i];
var page = this.registeredPages[name] ||
this.registeredOverlayPages[name];
if (!page.parentPage && isRootPageLocked)
continue;
if (page.willHidePage && name != pageName &&
!page.isAncestorOfPage(targetPage)) {
page.willHidePage();
}
}
// Update visibilities to show only the hierarchy of the target page.
for (var i = 0; i < allPageNames.length; ++i) {
var name = allPageNames[i];
var page = this.registeredPages[name] ||
this.registeredOverlayPages[name];
if (!page.parentPage && isRootPageLocked)
continue;
page.visible = name == pageName || page.isAncestorOfPage(targetPage);
}
// Update the history and current location.
if (updateHistory)
this.updateHistoryState_(!!opt_propertyBag.replaceState);
// Update tab title.
this.setTitle_(targetPage.title);
// Update focus if any other control was focused before.
if (document.activeElement != document.body)
targetPage.focus();
// Notify pages if they were shown.
for (var i = 0; i < allPageNames.length; ++i) {
var name = allPageNames[i];
var page = this.registeredPages[name] ||
this.registeredOverlayPages[name];
if (!page.parentPage && isRootPageLocked)
continue;
if (!targetPageWasVisible && page.didShowPage &&
(name == pageName || page.isAncestorOfPage(targetPage))) {
page.didShowPage();
}
}
};
/**
* Sets the title of the page. This is accomplished by calling into the
* parent page API.
* @param {String} title The title string.
* @private
*/
OptionsPage.setTitle_ = function(title) {
uber.invokeMethodOnParent('setTitle', {title: title});
};
/**
* Scrolls the page to the correct position (the top when opening an overlay,
* or the old scroll position a previously hidden overlay becomes visible).
* @private
*/
OptionsPage.updateScrollPosition_ = function() {
var container = $('page-container');
var scrollTop = container.oldScrollTop || 0;
container.oldScrollTop = undefined;
window.scroll(document.body.scrollLeft, scrollTop);
};
/**
* Pushes the current page onto the history stack, overriding the last page
* if it is the generic chrome://settings/.
* @param {boolean} replace If true, allow no history events to be created.
* @param {object=} opt_params A bag of optional params, including:
* {boolean} ignoreHash Whether to include the hash or not.
* @private
*/
OptionsPage.updateHistoryState_ = function(replace, opt_params) {
var page = this.getTopmostVisiblePage();
var path = window.location.pathname + window.location.hash;
if (path)
path = path.slice(1).replace(/\/(?:#|$)/, ''); // Remove trailing slash.
// Update tab title.
this.setTitle_(page.title);
// The page is already in history (the user may have clicked the same link
// twice). Do nothing.
if (path == page.name &&
!document.documentElement.classList.contains('loading')) {
return;
}
var hash = opt_params && opt_params.ignoreHash ? '' : window.location.hash;
// If settings are embedded, tell the outer page to set its "path" to the
// inner frame's path.
var outerPath = (page == this.getDefaultPage() ? '' : page.name) + hash;
uber.invokeMethodOnParent('setPath', {path: outerPath});
// If there is no path, the current location is chrome://settings/.
// Override this with the new page.
var historyFunction = path && !replace ? window.history.pushState :
window.history.replaceState;
historyFunction.call(window.history,
{pageName: page.name},
page.title,
'/' + page.name + hash);
};
/**
* Shows a registered Overlay page. Does not update history.
* @param {string} overlayName Page name.
* @param {OptionPage} rootPage The currently visible root-level page.
* @return {boolean} whether we showed an overlay.
*/
OptionsPage.showOverlay_ = function(overlayName, rootPage) {
var overlay = this.registeredOverlayPages[overlayName.toLowerCase()];
if (!overlay || !overlay.canShowPage())
return false;
// Save the currently focused element in the page for restoration later.
var currentPage = this.getTopmostVisiblePage();
if (currentPage)
currentPage.lastFocusedElement = document.activeElement;
if ((!rootPage || !rootPage.sticky) && overlay.parentPage)
this.showPageByName(overlay.parentPage.name, false);
if (!overlay.visible) {
overlay.visible = true;
if (overlay.didShowPage) overlay.didShowPage();
}
// Update tab title.
this.setTitle_(overlay.title);
// Change focus to the overlay if any other control was focused before.
if (document.activeElement != document.body)
overlay.focus();
$('searchBox').setAttribute('aria-hidden', true);
if ($('search-field').value == '') {
var section = overlay.associatedSection;
if (section)
options.BrowserOptions.scrollToSection(section);
}
return true;
};
/**
* Returns whether or not an overlay is visible.
* @return {boolean} True if an overlay is visible.
* @private
*/
OptionsPage.isOverlayVisible_ = function() {
return this.getVisibleOverlay_() != null;
};
/**
* Returns the currently visible overlay, or null if no page is visible.
* @return {OptionPage} The visible overlay.
*/
OptionsPage.getVisibleOverlay_ = function() {
var topmostPage = null;
for (var name in this.registeredOverlayPages) {
var page = this.registeredOverlayPages[name];
if (page.visible &&
(!topmostPage || page.nestingLevel > topmostPage.nestingLevel)) {
topmostPage = page;
}
}
return topmostPage;
};
/**
* Restores the last focused element on a given page.
*/
OptionsPage.restoreLastFocusedElement_ = function() {
var currentPage = this.getTopmostVisiblePage();
if (currentPage.lastFocusedElement)
currentPage.lastFocusedElement.focus();
};
/**
* Closes the visible overlay. Updates the history state after closing the
* overlay.
*/
OptionsPage.closeOverlay = function() {
var overlay = this.getVisibleOverlay_();
if (!overlay)
return;
overlay.visible = false;
if (overlay.didClosePage) overlay.didClosePage();
this.updateHistoryState_(false, {ignoreHash: true});
this.restoreLastFocusedElement_();
if (!this.isOverlayVisible_())
$('searchBox').removeAttribute('aria-hidden');
};
/**
* Cancels (closes) the overlay, due to the user pressing <Esc>.
*/
OptionsPage.cancelOverlay = function() {
// Blur the active element to ensure any changed pref value is saved.
document.activeElement.blur();
var overlay = this.getVisibleOverlay_();
// Let the overlay handle the <Esc> if it wants to.
if (overlay.handleCancel) {
overlay.handleCancel();
this.restoreLastFocusedElement_();
} else {
this.closeOverlay();
}
};
/**
* Hides the visible overlay. Does not affect the history state.
* @private
*/
OptionsPage.hideOverlay_ = function() {
var overlay = this.getVisibleOverlay_();
if (overlay)
overlay.visible = false;
};
/**
* Returns the pages which are currently visible, ordered by nesting level
* (ascending).
* @return {Array.OptionPage} The pages which are currently visible, ordered
* by nesting level (ascending).
*/
OptionsPage.getVisiblePages_ = function() {
var visiblePages = [];
for (var name in this.registeredPages) {
var page = this.registeredPages[name];
if (page.visible)
visiblePages[page.nestingLevel] = page;
}
return visiblePages;
};
/**
* Returns the topmost visible page (overlays excluded).
* @return {OptionPage} The topmost visible page aside any overlay.
* @private
*/
OptionsPage.getTopmostVisibleNonOverlayPage_ = function() {
var topPage = null;
for (var name in this.registeredPages) {
var page = this.registeredPages[name];
if (page.visible &&
(!topPage || page.nestingLevel > topPage.nestingLevel))
topPage = page;
}
return topPage;
};
/**
* Returns the topmost visible page, or null if no page is visible.
* @return {OptionPage} The topmost visible page.
*/
OptionsPage.getTopmostVisiblePage = function() {
// Check overlays first since they're top-most if visible.
return this.getVisibleOverlay_() || this.getTopmostVisibleNonOverlayPage_();
};
/**
* Returns the currently visible bubble, or null if no bubble is visible.
* @return {OptionsBubble} The bubble currently being shown.
*/
OptionsPage.getVisibleBubble = function() {
var bubble = OptionsPage.bubble_;
return bubble && !bubble.hidden ? bubble : null;
};
/**
* Shows an informational bubble displaying |content| and pointing at the
* |anchor| element. If |content| has focusable elements, they join the
* current page's tab order as siblings of |anchor|.
* @param {HTMLDivElement} content The content of the bubble.
* @param {HTMLElement} anchor The element at which the bubble points.
*/
OptionsPage.showBubble = function(content, anchor) {
OptionsPage.hideBubble();
var bubble = new options.OptionsBubble;
bubble.anchorNode = anchor;
bubble.arrowLocation = cr.ui.ArrowLocation.TOP_END;
bubble.content = content;
bubble.show();
OptionsPage.bubble_ = bubble;
};
/**
* Hides the currently visible bubble, if any.
*/
OptionsPage.hideBubble = function() {
if (OptionsPage.bubble_)
OptionsPage.bubble_.hide();
};
/**
* Shows the tab contents for the given navigation tab.
* @param {!Element} tab The tab that the user clicked.
*/
OptionsPage.showTab = function(tab) {
// Search parents until we find a tab, or the nav bar itself. This allows
// tabs to have child nodes, e.g. labels in separately-styled spans.
while (tab && !tab.classList.contains('subpages-nav-tabs') &&
!tab.classList.contains('tab')) {
tab = tab.parentNode;
}
if (!tab || !tab.classList.contains('tab'))
return;
// Find tab bar of the tab.
var tabBar = tab;
while (tabBar && !tabBar.classList.contains('subpages-nav-tabs')) {
tabBar = tabBar.parentNode;
}
if (!tabBar)
return;
if (tabBar.activeNavTab != null) {
tabBar.activeNavTab.classList.remove('active-tab');
$(tabBar.activeNavTab.getAttribute('tab-contents')).classList.
remove('active-tab-contents');
}
tab.classList.add('active-tab');
$(tab.getAttribute('tab-contents')).classList.add('active-tab-contents');
tabBar.activeNavTab = tab;
};
/**
* Registers new options page.
* @param {OptionsPage} page Page to register.
*/
OptionsPage.register = function(page) {
this.registeredPages[page.name.toLowerCase()] = page;
page.initializePage();
};
/**
* Find an enclosing section for an element if it exists.
* @param {Element} element Element to search.
* @return {OptionPage} The section element, or null.
* @private
*/
OptionsPage.findSectionForNode_ = function(node) {
while (node = node.parentNode) {
if (node.nodeName == 'SECTION')
return node;
}
return null;
};
/**
* Registers a new Overlay page.
* @param {OptionsPage} overlay Overlay to register.
* @param {OptionsPage} parentPage Associated parent page for this overlay.
* @param {Array} associatedControls Array of control elements associated with
* this page.
*/
OptionsPage.registerOverlay = function(overlay,
parentPage,
associatedControls) {
this.registeredOverlayPages[overlay.name.toLowerCase()] = overlay;
overlay.parentPage = parentPage;
if (associatedControls) {
overlay.associatedControls = associatedControls;
if (associatedControls.length) {
overlay.associatedSection =
this.findSectionForNode_(associatedControls[0]);
}
// Sanity check.
for (var i = 0; i < associatedControls.length; ++i) {
assert(associatedControls[i], 'Invalid element passed.');
}
}
// Reverse the button strip for views. See the documentation of
// reverseButtonStrip_() for an explanation of why this is necessary.
if (cr.isViews)
this.reverseButtonStrip_(overlay);
overlay.tab = undefined;
overlay.isOverlay = true;
overlay.initializePage();
};
/**
* Reverses the child elements of a button strip. This is necessary because
* WebKit does not alter the tab order for elements that are visually reversed
* using -webkit-box-direction: reverse, and the button order is reversed for
* views. See https://bugs.webkit.org/show_bug.cgi?id=62664 for more
* information.
* @param {Object} overlay The overlay containing the button strip to reverse.
* @private
*/
OptionsPage.reverseButtonStrip_ = function(overlay) {
var buttonStrips = overlay.pageDiv.querySelectorAll('.button-strip');
// Reverse all button-strips in the overlay.
for (var j = 0; j < buttonStrips.length; j++) {
var buttonStrip = buttonStrips[j];
var childNodes = buttonStrip.childNodes;
for (var i = childNodes.length - 1; i >= 0; i--)
buttonStrip.appendChild(childNodes[i]);
}
};
/**
* Callback for window.onpopstate.
* @param {Object} data State data pushed into history.
*/
OptionsPage.setState = function(data) {
if (data && data.pageName) {
this.willClose();
this.showPageByName(data.pageName, false);
}
};
/**
* Callback for window.onbeforeunload. Used to notify overlays that they will
* be closed.
*/
OptionsPage.willClose = function() {
var overlay = this.getVisibleOverlay_();
if (overlay && overlay.didClosePage)
overlay.didClosePage();
};
/**
* Freezes/unfreezes the scroll position of the root page container.
* @param {boolean} freeze Whether the page should be frozen.
* @private
*/
OptionsPage.setRootPageFrozen_ = function(freeze) {
var container = $('page-container');
if (container.classList.contains('frozen') == freeze)
return;
if (freeze) {
// Lock the width, since auto width computation may change.
container.style.width = window.getComputedStyle(container).width;
container.oldScrollTop = document.body.scrollTop;
container.classList.add('frozen');
var verticalPosition =
container.getBoundingClientRect().top - container.oldScrollTop;
container.style.top = verticalPosition + 'px';
this.updateFrozenElementHorizontalPosition_(container);
} else {
container.classList.remove('frozen');
container.style.top = '';
container.style.left = '';
container.style.right = '';
container.style.width = '';
}
};
/**
* Freezes/unfreezes the scroll position of the root page based on the current
* page stack.
*/
OptionsPage.updateRootPageFreezeState = function() {
var topPage = OptionsPage.getTopmostVisiblePage();
if (topPage)
this.setRootPageFrozen_(topPage.isOverlay);
};
/**
* Initializes the complete options page. This will cause all C++ handlers to
* be invoked to do final setup.
*/
OptionsPage.initialize = function() {
chrome.send('coreOptionsInitialize');
uber.onContentFrameLoaded();
document.addEventListener('scroll', this.handleScroll_.bind(this));
// Trigger the scroll handler manually to set the initial state.
this.handleScroll_();
// Shake the dialog if the user clicks outside the dialog bounds.
var containers = [$('overlay-container-1'), $('overlay-container-2')];
for (var i = 0; i < containers.length; i++) {
var overlay = containers[i];
cr.ui.overlay.setupOverlay(overlay);
overlay.addEventListener('cancelOverlay',
OptionsPage.cancelOverlay.bind(OptionsPage));
}
};
/**
* Does a bounds check for the element on the given x, y client coordinates.
* @param {Element} e The DOM element.
* @param {number} x The client X to check.
* @param {number} y The client Y to check.
* @return {boolean} True if the point falls within the element's bounds.
* @private
*/
OptionsPage.elementContainsPoint_ = function(e, x, y) {
var clientRect = e.getBoundingClientRect();
return x >= clientRect.left && x <= clientRect.right &&
y >= clientRect.top && y <= clientRect.bottom;
};
/**
* Called when the page is scrolled; moves elements that are position:fixed
* but should only behave as if they are fixed for vertical scrolling.
* @private
*/
OptionsPage.handleScroll_ = function() {
this.updateAllFrozenElementPositions_();
};
/**
* Updates all frozen pages to match the horizontal scroll position.
* @private
*/
OptionsPage.updateAllFrozenElementPositions_ = function() {
var frozenElements = document.querySelectorAll('.frozen');
for (var i = 0; i < frozenElements.length; i++)
this.updateFrozenElementHorizontalPosition_(frozenElements[i]);
};
/**
* Updates the given frozen element to match the horizontal scroll position.
* @param {HTMLElement} e The frozen element to update.
* @private
*/
OptionsPage.updateFrozenElementHorizontalPosition_ = function(e) {
if (isRTL()) {
e.style.right = OptionsPage.horizontalOffset + 'px';
} else {
e.style.left = OptionsPage.horizontalOffset -
document.body.scrollLeft + 'px';
}
};
/**
* Change the horizontal offset used to reposition elements while showing an
* overlay from the default.
*/
OptionsPage.setHorizontalOffset = function(value) {
OptionsPage.horizontalOffset = value;
};
OptionsPage.setClearPluginLSODataEnabled = function(enabled) {
if (enabled) {
document.documentElement.setAttribute(
'flashPluginSupportsClearSiteData', '');
} else {
document.documentElement.removeAttribute(
'flashPluginSupportsClearSiteData');
}
};
OptionsPage.setPepperFlashSettingsEnabled = function(enabled) {
if (enabled) {
document.documentElement.setAttribute(
'enablePepperFlashSettings', '');
} else {
document.documentElement.removeAttribute(
'enablePepperFlashSettings');
}
};
OptionsPage.prototype = {
__proto__: cr.EventTarget.prototype,
/**
* The parent page of this option page, or null for top-level pages.
* @type {OptionsPage}
*/
parentPage: null,
/**
* The section on the parent page that is associated with this page.
* Can be null.
* @type {Element}
*/
associatedSection: null,
/**
* An array of controls that are associated with this page. The first
* control should be located on a top-level page.
* @type {OptionsPage}
*/
associatedControls: null,
/**
* Initializes page content.
*/
initializePage: function() {},
/**
* Sets focus on the first focusable element. Override for a custom focus
* strategy.
*/
focus: function() {
var elements = this.pageDiv.querySelectorAll(
'input, list, select, textarea, button');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Try to focus. If fails, then continue.
element.focus();
if (document.activeElement == element)
return;
}
},
/**
* Gets the container div for this page if it is an overlay.
* @type {HTMLElement}
*/
get container() {
assert(this.isOverlay);
return this.pageDiv.parentNode;
},
/**
* Gets page visibility state.
* @type {boolean}
*/
get visible() {
// If this is an overlay dialog it is no longer considered visible while
// the overlay is fading out. See http://crbug.com/118629.
if (this.isOverlay &&
this.container.classList.contains('transparent')) {
return false;
}
return !this.pageDiv.hidden;
},
/**
* Sets page visibility.
* @type {boolean}
*/
set visible(visible) {
if ((this.visible && visible) || (!this.visible && !visible))
return;
// If using an overlay, the visibility of the dialog is toggled at the
// same time as the overlay to show the dialog's out transition. This
// is handled in setOverlayVisible.
if (this.isOverlay) {
this.setOverlayVisible_(visible);
} else {
this.pageDiv.hidden = !visible;
this.onVisibilityChanged_();
}
cr.dispatchPropertyChange(this, 'visible', visible, !visible);
},
/**
* Shows or hides an overlay (including any visible dialog).
* @param {boolean} visible Whether the overlay should be visible or not.
* @private
*/
setOverlayVisible_: function(visible) {
assert(this.isOverlay);
var pageDiv = this.pageDiv;
var container = this.container;
if (visible) {
uber.invokeMethodOnParent('beginInterceptingEvents');
this.pageDiv.removeAttribute('aria-hidden');
if (this.parentPage)
this.parentPage.pageDiv.setAttribute('aria-hidden', true);
} else {
if (this.parentPage)
this.parentPage.pageDiv.removeAttribute('aria-hidden');
}
if (container.hidden != visible) {
if (visible) {
// If the container is set hidden and then immediately set visible
// again, the fadeCompleted_ callback would cause it to be erroneously
// hidden again. Removing the transparent tag avoids that.
container.classList.remove('transparent');
// Hide all dialogs in this container since a different one may have
// been previously visible before fading out.
var pages = container.querySelectorAll('.page');
for (var i = 0; i < pages.length; i++)
pages[i].hidden = true;
// Show the new dialog.
pageDiv.hidden = false;
}
return;
}
if (visible) {
container.hidden = false;
pageDiv.hidden = false;
// NOTE: This is a hacky way to force the container to layout which
// will allow us to trigger the webkit transition.
container.scrollTop;
container.classList.remove('transparent');
this.onVisibilityChanged_();
} else {
var self = this;
// TODO: Use an event delegate to avoid having to subscribe and
// unsubscribe for webkitTransitionEnd events.
container.addEventListener('webkitTransitionEnd', function f(e) {
if (e.target != e.currentTarget || e.propertyName != 'opacity')
return;
container.removeEventListener('webkitTransitionEnd', f);
self.fadeCompleted_();
});
container.classList.add('transparent');
}
},
/**
* Called when a container opacity transition finishes.
* @private
*/
fadeCompleted_: function() {
if (this.container.classList.contains('transparent')) {
this.pageDiv.hidden = true;
this.container.hidden = true;
this.onVisibilityChanged_();
if (this.nestingLevel == 1)
uber.invokeMethodOnParent('stopInterceptingEvents');
}
},
/**
* Called when a page is shown or hidden to update the root options page
* based on this page's visibility.
* @private
*/
onVisibilityChanged_: function() {
OptionsPage.updateRootPageFreezeState();
if (this.isOverlay && !this.visible)
OptionsPage.updateScrollPosition_();
},
/**
* The nesting level of this page.
* @type {number} The nesting level of this page (0 for top-level page)
*/
get nestingLevel() {
var level = 0;
var parent = this.parentPage;
while (parent) {
level++;
parent = parent.parentPage;
}
return level;
},
/**
* Whether the page is considered 'sticky', such that it will
* remain a top-level page even if sub-pages change.
* @type {boolean} True if this page is sticky.
*/
get sticky() {
return false;
},
/**
* Checks whether this page is an ancestor of the given page in terms of
* subpage nesting.
* @param {OptionsPage} page The potential descendent of this page.
* @return {boolean} True if |page| is nested under this page.
*/
isAncestorOfPage: function(page) {
var parent = page.parentPage;
while (parent) {
if (parent == this)
return true;
parent = parent.parentPage;
}
return false;
},
/**
* Whether it should be possible to show the page.
* @return {boolean} True if the page should be shown.
*/
canShowPage: function() {
return true;
},
};
// Export
return {
OptionsPage: OptionsPage
};
});
|
leighpauls/k2cro4
|
chrome/browser/resources/options/options_page.js
|
JavaScript
|
bsd-3-clause
| 29,700
|
// require('./check-versions')()
var config = require('../config')
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = require('./webpack.dev.conf')
// default port where dev server listens for incoming traffic
var port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
var autoOpenBrowser = !!config.dev.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.dev.proxyTable
var app = express()
const spacesCache = require('../src/api/client-cache/spaces')
const routes = require('../src/api/routes')
app.use('/rest', routes)
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: false,
heartbeat: 2000
})
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)
// serve pure static assets
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
app.use(staticPath, express.static('./static'))
var uri = 'http://localhost:' + port
var _resolve
var readyPromise = new Promise(resolve => {
_resolve = resolve
})
/* Init caches here */
const cfCache = require('../src/api/client-cache/aggregrate')
console.log('Attempting to initialize cache')
cfCache.initialize().then((res) =>{
console.log('Cache initialized')
console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
console.log('> Listening at ' + uri + '\n')
// when env is testing, don't need open it
// if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
// opn(uri)
// }
_resolve()
})
})
var server = app.listen(port)
module.exports = {
ready: readyPromise,
close: () => {
server.close()
},
app: app
}
|
MonsantoCo/cf-portal
|
build/dev-server.js
|
JavaScript
|
bsd-3-clause
| 2,847
|
//var textarea = document.getElementById("queryarea");
//var cm = CodeMirror.fromTextArea(textarea, {
// mode: "application/sparql-query",
// matchBrackets: true,
// lineNumbers: true,
// size: 100
//});
//cm.refresh();
https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
// dec2hex :: Integer -> String
function dec2hex (dec) {
return ('0' + dec.toString(16)).substr(-2)
}
// generateVar :: Integer -> String
function generateVar (len) {
var arr = new Uint8Array((len || 40) / 2)
window.crypto.getRandomValues(arr)
return "?"+Array.from(arr, dec2hex).join('')
}
var QUERY = {
//"brick:Room": {
// SELECT: "?start",
// WHERE: ["?start rdf:type brick:Room . "],
//},
};
var rebuildquery = function(term) {
QUERY = {};
QUERY[term] = {SELECT: "?start", WHERE: ["?start rdf:type brick:" + term + " . "]};
}
var to_query = function() {
var build = "SELECT";
for (key in QUERY) {
build += " " + QUERY[key].SELECT;
}
build += " WHERE { "
for (key in QUERY) {
build += " " + QUERY[key].WHERE.join(' ');
}
build += " };";
return build;
}
var to_query_no_explore = function() {
var build = "SELECT";
for (key in QUERY) {
build += " " + QUERY[key].SELECT;
}
build += " WHERE { "
for (key in QUERY) {
build += " " + QUERY[key].WHERE.slice(0,2).join(' ');
}
build += " };";
return build;
}
var get_vars = function() {
var build = [];
for (key in QUERY) {
build.push(QUERY[key].SELECT);
}
return build;
}
var find_edge_by_id = function(n, edgeid) {
for (var i in n.edges) {
if (n.edges[i].id == edgeid) {
return n.edges[i];
}
}
console.log('could not find', edgeid,'in',n);
return null;
}
var find_node_by_id = function(n, nodeid) {
for (var i in n.nodes) {
if (n.nodes[i].id == nodeid) {
return n.nodes[i];
}
}
console.log('could not find', edgeid,'in',n);
return null;
}
var update_node_by_id = function(n, nodeid, node) {
for (var i in n.nodes) {
if (n.nodes[i].id == nodeid) {
console.log('update', node);
n.nodes[i] = node;
return;
}
}
return null;
}
var get_var_name = function(name) {
var split = name.split('|');
if (split.length == 1) {
return name;
}
return split[0];
}
var get_old_name = function(name) {
var split = name.split('|');
if (split.length == 1) {
return '';
}
return split[1];
}
var get_classes = function(term, handleresults) {
$.post("/api/search", JSON.stringify({'Query': term, 'Number': 1}), function(data) {
console.log("TERMS", data);
handleresults(data);
});
}
var submit_query = function() {
var html = "";
var begin = moment();
$("#errortext").hide();
var parsedData = {nodes: [], edges: []};
console.log(to_query());
$.post("/api/queryclassdot", to_query(), function(data) {
if (network != null) {
network.destroy();
}
console.log(data);
var end = moment();
var duration = moment.duration(end - begin);
$("#elapsed").text(duration.milliseconds() + " ms");
var newdata = vis.network.convertDot(data)
parsedData.options = newdata.options;
parsedData.update = newdata.update;
for (var idx in newdata.nodes) {
var n = newdata.nodes[idx];
console.log(n);
console.log(QUERY);
if (get_var_name(n.id).length < n.id.length) {
n.varname = get_var_name(n.id);
n.label = get_old_name(n.id);
n.id = get_old_name(n.id);
if (n.id == 'bf:uri') {
continue;
}
if (n.id == 'bf:uuid') {
continue;
}
var found = false;
parsedData.nodes.forEach(function(nn, idxx) {
console.log("here", nn);
if (nn.id == n.id) {
parsedData.nodes[idxx].varname = n.varname;
parsedData.nodes[idxx].label = n.label;
parsedData.nodes[idxx].color = n.color;
found = true;
}
});
if (!found) {
parsedData.nodes.push(n);
}
} else {
console.log(n);
var dup = parsedData.nodes.find(function(dup) {
return dup.id == n.id;
});
if (dup == null) {
parsedData.nodes.push(n);
}
}
}
//parsedData.nodes = newnodes;
console.log(newdata.edges);
for (var idx in newdata.edges) {
var e = newdata.edges[idx];
if (get_var_name(e.from).length < e.from.length) {
e.from = get_old_name(e.from);
}
if (get_var_name(e.to).length < e.to.length) {
e.to = get_old_name(e.to);
}
console.log(e);
if (e.to == 'bf:uri' || e.to == 'uri') {
e.to = generateVar(10);
e.label = 'bf:uri';
var n = {id: e.to, label: 'URI'};
parsedData.nodes.push(n);
} else if (e.to == 'bf:uuid' || e.to == 'uuid') {
e.to = generateVar(10);
e.label = 'bf:uuid';
var n = {id: e.to, label: 'UUID'};
parsedData.nodes.push(n);
}
parsedData.edges.push(e);
}
var container = document.getElementById('mynetwork');
var data = {
nodes: parsedData.nodes,
edges: parsedData.edges
};
var options = parsedData.options;
options.interaction = {
hover: true,
selectable: true
};
options.layout = {
hierarchical: {
enabled: true,
blockShifting: true,
levelSeparation: 300,
nodeSpacing: 100,
edgeMinimization: false,
direction: 'LR'
}
};
//options.physics = {
// barnesHut: {
// //gravitationalConstant: -3000,
// springLength: 300,
// //avoidOverlap: .3,
// },
// timestep: 1
//};
var network = new vis.Network(container, data, options);
network.on("click", function(params) {
var clicked = network.getSelectedNodes()[0]
if (clicked in QUERY) {
delete QUERY[clicked];
submit_query();
return;
}
var edge = find_edge_by_id(parsedData, network.getSelectedEdges()[0]);
var newclass = edge.to;
var newvar = generateVar(5);
var orignode = find_node_by_id(parsedData, edge.from);
var clickednode = find_node_by_id(parsedData, edge.to);
orignode.varname = QUERY[orignode.id].SELECT;
console.log(QUERY[orignode.id].SELECT);
console.log("clicked", clicked, orignode, edge);
if (clickednode.label == "URI") {
QUERY[newclass] = {
SELECT: newvar,
WHERE: [orignode.varname + " bf:uri " + newvar + " . "]
};
//clickednode.color = {background: '#f00'}
//update_node_by_id(parsedData, clickednode.id, clickednode);
//network.redraw();
return;
} else if (clickednode.label == "UUID") {
QUERY[newclass] = {
SELECT: newvar+'_uuid',
WHERE: [orignode.varname + " bf:uuid " + newvar+'_uuid' + " . "]
};
//clickednode.color = {background: '#f00'}
//update_node_by_id(parsedData, clickednode.id, clickednode);
//network.redraw();
return;
} else {
var line1 = orignode.varname + " " + edge.label + " " + newvar + " . ";
var line2 = newvar + " rdf:type " + newclass + " . ";
var p = generateVar(5);
var o = generateVar(5);
var line3 = newvar + " " + p + " " + o + " . ";
QUERY[newclass] = {
SELECT: newvar,// + ' ' + p + ' ' + o,
WHERE: [line1, line2, line3],
}
}
console.log("NEW",to_query());
submit_query();
});
network.redraw();
}).fail(function(e) {
$("#errortext").show();
$("#errortext > p").text(e.responseText);
});
}
//cm.on("change", function(e, x) {
// //submit_query(cm.getValue());
//});
// run once
var querytext = $("#queryarea").val();
//submit_query();
|
gtfierro/hod
|
server/static/js/demo.js
|
JavaScript
|
bsd-3-clause
| 8,546
|
/**
* Copyright (c) 2008-2010 The Open Source Geospatial Foundation
*
* Published under the BSD license.
* See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text
* of the license.
*/
Ext.namespace("GeoExt.ux.form");
GeoExt.ux.form.FilterAction = Ext.extend(Ext.form.Action, {
/** private: property[type]
* ``String`` The action type string.
*/
type: "filter",
/** api: property[formToFilter]
* ``GeoExt.ux.form.FormToFilter`` object that defines the mapping
* from the Form contents to the Filter object (by calling its toFilter()
* method).
* Defaults to an instance of GeoExt.ux.form.FormToFilter with
* the default options.
*/
formToFilter: new GeoExt.ux.form.FormToFilter(),
/** private
* (used by ``GeoExt.ux.form.AttributeFilterBasicForm``)
*/
constructor: function(form, options) {
Ext.apply(this, options);
GeoExt.ux.form.FilterAction.superclass.constructor.call(this, form, options);
},
/** private: method[run]
* Run the action.
*/
run: function() {
var o = this.options;
var f = this.formToFilter.toFilter(this.form, o.logicalOp, o.wildcard);
if (o.clientValidation === false || this.form.isValid()) {
if (o.layer) {
if (f != null) {
o.layer.filter = f;
o.layer.refresh({force: true});
/*
if (this.strategy && this.strategy instanceof OpenLayers.Strategy.Fixed) {
this.strategy.load();
}
*/
} else if (this.noFeaturesOnEmptyForm) {
o.layer.removeAllFeatures();
o.layer.redraw();
}
}
} else if (o.clientValidation !== false){
// client validation failed
this.failureType = Ext.form.Action.CLIENT_INVALID;
this.form.afterAction(this, false);
}
}
});
|
groupe-conseil-nutshimit-nippour/django-geoprisma
|
geoprisma/static/geoprisma/lib/geoext-ux-attributefilterpanel/lib/GeoExt.ux/widgets/attributefilterpanel/FilterAction.js
|
JavaScript
|
bsd-3-clause
| 1,796
|
var structanonymous__namespace_02io__shell__ts_8C_03_1_1param =
[
[ "entity", "structanonymous__namespace_02io__shell__ts_8C_03_1_1param.html#adb67b17db3888a519262c95057b183db", null ],
[ "interface", "structanonymous__namespace_02io__shell__ts_8C_03_1_1param.html#ab2db70987ae993fbd7481dab3010ea15", null ],
[ "output_region", "structanonymous__namespace_02io__shell__ts_8C_03_1_1param.html#a4ac885dbea14b3e66d8b75dacf1dbc9b", null ],
[ "role", "structanonymous__namespace_02io__shell__ts_8C_03_1_1param.html#a53825be2f7b1684653ff08c42eb62dcb", null ]
];
|
nschloe/seacas
|
docs/ioss_html/structanonymous__namespace_02io__shell__ts_8C_03_1_1param.js
|
JavaScript
|
bsd-3-clause
| 571
|
/**
* Pimcore
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.pimcore.org/license
*
* @copyright Copyright (c) 2009-2013 pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license New BSD License
*/
pimcore.registerNS("pimcore.object.tags.link");
pimcore.object.tags.link = Class.create(pimcore.object.tags.abstract, {
type: "link",
dirty: false,
initialize: function (data, fieldConfig) {
this.data = "";
this.defaultData = {
type: "internal",
path: "",
parameters: "",
anchor: "",
accesskey: "",
rel: "",
tabindex: "",
target: ""
};
if (data) {
this.data = data;
}
else {
this.data = this.defaultData;
}
this.fieldConfig = fieldConfig;
},
getGridColumnConfig: function(field) {
var renderer = function(key, value, metaData, record) {
this.applyPermissionStyle(key, value, metaData, record);
if(record.data.inheritedFields[key] && record.data.inheritedFields[key].inherited == true) {
metaData.css += " grid_value_inherited";
}
if(value) {
return value.text;
}
return t("empty");
}.bind(this, field.key);
return {header: ts(field.label), sortable: true, dataIndex: field.key, renderer: renderer};
},
getLayoutEdit: function () {
var input = {
fieldLabel: this.fieldConfig.title,
name: this.fieldConfig.name,
itemCls: "object_field"
};
this.button = new Ext.Button({
iconCls: "pimcore_icon_edit_link",
handler: this.openEditor.bind(this)
});
var textValue = "[not set]";
if (this.data.text) {
textValue = this.data.text;
}
this.displayField = new Ext.form.DisplayField({
value: textValue
});
this.component = new Ext.form.CompositeField({
xtype: 'compositefield',
fieldLabel: this.fieldConfig.title,
combineErrors: false,
items: [this.displayField, this.button],
itemCls: "object_field"
});
return this.component;
},
getLayoutShow: function () {
this.component = this.getLayoutEdit();
//this.layout.disable();
this.button.hide();
return this.component;
},
getValue: function () {
return this.data;
},
getName: function () {
return this.fieldConfig.name;
},
openEditor: function () {
this.fieldPath = new Ext.form.TextField({
fieldLabel: t("path"),
value: this.data.path,
name: "path",
width: 320,
cls: "pimcore_droptarget_input",
enableKeyEvents: true,
listeners: {
keyup: function (el) {
if(el.getValue().match(/^www\./)) {
el.setValue("http://" + el.getValue());
}
}
}
});
this.fieldPath.on("render", function (el) {
// add drop zone
new Ext.dd.DropZone(el.getEl(), {
reference: this,
ddGroup: "element",
getTargetFromEvent: function(e) {
return this.reference.fieldPath.getEl();
},
onNodeOver : function(target, dd, e, data) {
return Ext.dd.DropZone.prototype.dropAllowed;
}.bind(this),
onNodeDrop : function (target, dd, e, data) {
if (data.node.attributes.elementType == "asset" || data.node.attributes.elementType == "document") {
this.fieldPath.setValue(data.node.attributes.path);
return true;
}
return false;
}.bind(this)
});
}.bind(this));
this.form = new Ext.FormPanel({
items: [
{
xtype:'tabpanel',
activeTab: 0,
deferredRender: false,
defaults:{autoHeight:true, bodyStyle:'padding:10px'},
border: false,
items: [
{
title:t('basic'),
layout:'form',
border: false,
defaultType: 'textfield',
items: [
{
fieldLabel: t('text'),
name: 'text',
value: this.data.text
},
{
xtype: "compositefield",
items: [this.fieldPath, {
xtype: "button",
iconCls: "pimcore_icon_search",
handler: this.openSearchEditor.bind(this)
}]
},
{
xtype:'fieldset',
title: t('properties'),
collapsible: false,
autoHeight:true,
defaultType: 'textfield',
items :[
{
xtype: "combo",
fieldLabel: t('target'),
name: 'target',
triggerAction: 'all',
editable: true,
store: ["","_blank","_self","_top","_parent"],
value: this.data.target
},
{
fieldLabel: t('parameters'),
name: 'parameters',
value: this.data.parameters
},
{
fieldLabel: t('anchor'),
name: 'anchor',
value: this.data.anchor
},
{
fieldLabel: t('title'),
name: 'title',
value: this.data.title
}
]
}
]
},
{
title:t('advanced'),
layout:'form',
defaultType: 'textfield',
border: false,
items: [
{
fieldLabel: t('accesskey'),
name: 'accesskey',
value: this.data.accesskey
},
{
fieldLabel: t('relation'),
name: 'rel',
value: this.data.rel
},
{
fieldLabel: t('tabindex'),
name: 'tabindex',
value: this.data.tabindex
}
]
}
]
}
],
buttons: [
{
text: t("empty"),
listeners: {
"click": this.empty.bind(this)
}
},
{
text: t("cancel"),
listeners: {
"click": this.cancel.bind(this)
}
},
{
text: t("save"),
listeners: {
"click": this.save.bind(this)
},
icon: "/pimcore/static/img/icon/tick.png"
}
]
});
this.window = new Ext.Window({
width: 500,
height: 330,
title: "Edit link",
items: [this.form],
layout: "fit",
listeners: {
"close": function () {
this.getObject().edit.enableFieldMasks();
}.bind(this)
}
});
this.window.show();
// this is because of underlying activated wysiwyg, which will also catch the drop event, when the panel
// is not disabled
this.getObject().edit.disableFieldMasks();
},
openSearchEditor: function () {
pimcore.helpers.itemselector(false, this.addDataFromSelector.bind(this), {
type: ["asset","document"]
});
},
addDataFromSelector: function (item) {
if (item) {
this.fieldPath.setValue(item.fullpath);
return true;
}
},
save: function () {
var values = this.form.getForm().getFieldValues();
if(Ext.encode(values) != Ext.encode(this.data)) {
this.dirty = true;
}
this.data = values;
var textValue = "[not set]";
if (this.data.text) {
textValue = this.data.text;
}
this.displayField.setValue(textValue);
// close window
this.window.close();
},
empty: function () {
// close window
this.window.close();
this.data = this.defaultData;
this.dirty = true;
// set text
this.displayField.setValue("[not set]");
},
cancel: function () {
this.window.close();
},
isDirty: function() {
if(!this.isRendered()) {
return false;
}
return this.dirty;
}
});
|
PatidarWeb/pimcore
|
pimcore/static/js/pimcore/object/tags/link.js
|
JavaScript
|
bsd-3-clause
| 10,999
|
/*
arcticModal — jQuery plugin
Version: 0.2
Author: Sergey Predvoditelev (sergey.predvoditelev@gmail.com)
Company: Arctic Laboratory (http://arcticlab.ru/)
Docs & Examples: http://arcticlab.ru/arcticmodal/
*/
(function(d){var g={type:"html",content:"",url:"",ajax:{},ajax_request:null,closeOnEsc:!0,closeOnOverlayClick:!0,clone:!1,overlay:{block:void 0,tpl:'<div class="arcticmodal-overlay"></div>',css:{backgroundColor:"#000",opacity:0.5}},container:{block:void 0,tpl:'<div class="arcticmodal-container"><table class="arcticmodal-container_i"><tr><td class="arcticmodal-container_i2"></td></tr></table></div>'},wrap:void 0,body:void 0,errors:{tpl:'<div class="arcticmodal-error arcticmodal-close"></div>',autoclose_delay:2E3,
ajax_unsuccessful_load:"Error"},openEffect:{type:"fade",speed:400},closeEffect:{type:"fade",speed:400},beforeOpen:d.noop,afterOpen:d.noop,beforeClose:d.noop,afterClose:d.noop,afterLoading:d.noop,afterLoadingOnShow:d.noop,errorLoading:d.noop},i=0,e=d(),l={isEventOut:function(a,b){var c=!0;d(a).each(function(){d(b.target).get(0)==d(this).get(0)&&(c=!1);0==d(b.target).closest("HTML",d(this).get(0)).length&&(c=!1)});return c}},f={transition:function(a,b,c,e){e=void 0==e?d.noop:e;switch(c.type){case "fade":"show"==
b?a.fadeIn(c.speed,e):a.fadeOut(c.speed,e);break;case "none":"show"==b?a.show():a.hide(),e()}},prepare_body:function(a,b){d(".arcticmodal-close",a.body).click(function(){b.arcticmodal("close");return!1})},init_el:function(a,b){var c=a.data("arcticmodal");if(!c){c=b;i++;c.modalID=i;c.overlay.block=d(c.overlay.tpl);c.overlay.block.css(c.overlay.css);c.container.block=d(c.container.tpl);c.body=d(".arcticmodal-container_i2",c.container.block);b.clone?c.body.html(a.clone(!0)):(a.before('<div id="arcticmodalReserve'+
c.modalID+'" style="display: none" />'),c.body.html(a));f.prepare_body(c,a);c.closeOnOverlayClick&&c.overlay.block.add(c.container.block).click(function(b){l.isEventOut(d(">*",c.body),b)&&a.arcticmodal("close")});a.data("arcticmodal",c);e=e.add(a);d.proxy(h.show,a)();if("html"==c.type)return a;if(void 0!=c.ajax.beforeSend){var j=c.ajax.beforeSend;delete c.ajax.beforeSend}if(void 0!=c.ajax.success){var g=c.ajax.success;delete c.ajax.success}if(void 0!=c.ajax.error){var k=c.ajax.error;delete c.ajax.error}var m=
d.extend(!0,{url:c.url,beforeSend:function(){void 0==j?c.body.html('<div class="arcticmodal-loading" />'):j(c,a)},success:function(b){a.trigger("afterLoading");c.afterLoading(c,a,b);void 0==g?c.body.html(b):g(c,a,b);f.prepare_body(c,a);a.trigger("afterLoadingOnShow");c.afterLoadingOnShow(c,a,b)},error:function(){a.trigger("errorLoading");c.errorLoading(c,a);void 0==k?(c.body.html(c.errors.tpl),d(".arcticmodal-error",c.body).html(c.errors.ajax_unsuccessful_load),d(".arcticmodal-close",c.body).click(function(){a.arcticmodal("close");
return!1}),c.errors.autoclose_delay&&setTimeout(function(){a.arcticmodal("close")},c.errors.autoclose_delay)):k(c,a)}},c.ajax);c.ajax_request=d.ajax(m);a.data("arcticmodal",c)}},init:function(a){a=d.extend(!0,{},g,a);if(d.isFunction(this))if(void 0==a)d.error("jquery.arcticmodal: Uncorrect parameters");else if(""==a.type)d.error('jquery.arcticmodal: Don\'t set parameter "type"');else switch(a.type){case "html":if(""==a.content){d.error('jquery.arcticmodal: Don\'t set parameter "content"');break}var b=
a.content;a.content="";return f.init_el(d(b),a);case "ajax":if(""==a.url){d.error('jquery.arcticmodal: Don\'t set parameter "url"');break}return f.init_el(d("<div />"),a)}else return this.each(function(){f.init_el(d(this),a)})}},h={show:function(){var a=d(this),b=a.data("arcticmodal");if(b){b.overlay.block.hide();b.container.block.hide();d("BODY").append(b.overlay.block);d("BODY").append(b.container.block);b.beforeOpen(b,a);a.trigger("beforeOpen");if("hidden"!=b.wrap.css("overflow")){b.wrap.data("arcticmodalOverflow",
b.wrap.css("overflow"));var c=b.wrap.outerWidth(!0);b.wrap.css("overflow","hidden");var g=b.wrap.outerWidth(!0);g!=c&&b.wrap.css("marginRight",g-c+"px")}e.not(a).each(function(){d(this).data("arcticmodal").overlay.block.hide()});f.transition(b.overlay.block,"show",1<e.length?{type:"none"}:b.openEffect);f.transition(b.container.block,"show",1<e.length?{type:"none"}:b.openEffect,function(){b.afterOpen(b,a);a.trigger("afterOpen")});return a}d.error("jquery.arcticmodal: Uncorrect call")},close:function(){if(d.isFunction(this))e.each(function(){d(this).arcticmodal("close")});
else return this.each(function(){var a=d(this),b=a.data("arcticmodal");b?!1!==b.beforeClose(b,a)&&(a.trigger("beforeClose"),e.not(a).last().each(function(){d(this).data("arcticmodal").overlay.block.show()}),f.transition(b.overlay.block,"hide",1<e.length?{type:"none"}:b.closeEffect),f.transition(b.container.block,"hide",1<e.length?{type:"none"}:b.closeEffect,function(){b.afterClose(b,a);a.trigger("afterClose");b.clone||d("#arcticmodalReserve"+b.modalID).replaceWith(b.body.find(">*"));b.overlay.block.remove();
b.container.block.remove();a.data("arcticmodal",null);d(".arcticmodal-container").length||(b.wrap.data("arcticmodalOverflow")&&b.wrap.css("overflow",b.wrap.data("arcticmodalOverflow")),b.wrap.css("marginRight",0))}),"ajax"==b.type&&b.ajax_request.abort(),e=e.not(a)):d.error("jquery.arcticmodal: Uncorrect call")})},setDefault:function(a){d.extend(!0,g,a)}};d(function(){g.wrap=d(document.all&&!document.querySelector?"html":"body")});d(document).bind("keyup.arcticmodal",function(a){var b=e.last();b.length&&
b.data("arcticmodal").closeOnEsc&&27===a.keyCode&&b.arcticmodal("close")});d.arcticmodal=d.fn.arcticmodal=function(a){if(h[a])return h[a].apply(this,Array.prototype.slice.call(arguments,1));if("object"===typeof a||!a)return f.init.apply(this,arguments);d.error("jquery.arcticmodal: Method "+a+" does not exist")}})(jQuery);
|
swash13/football
|
web/js/jquery.arcticmodal-0.2.min.js
|
JavaScript
|
bsd-3-clause
| 5,780
|
"use strict";
var Components = require("../lib/components");
var builder = require("../lib/stringBuilder");
var components = new Components(builder);
var name = "test-component";
var template = "{{#if 2 > 1}}<b>Yup!</b>{{/if}}{{#if 2 === 3}}Nope!{{/if}}";
components.add({
name: name,
template: template
});
var rendered = components[name].render();
console.log(rendered);
|
RangerMauve/nexilis
|
examples/exampleIf.js
|
JavaScript
|
isc
| 380
|
(function() {
'use strict';
var stateConfig = function($stateProvider) {
$stateProvider
.state('episode_type_management', {
url:'/episode_type_management',
parent: 'yujihomo',
data: {
roles: ['admin']
},
views: {
'@yujihomo': {
templateUrl: 'app/episode_type_management/episode_type_management.tmpl.html',
controller: 'EpisodeTypeManagementController as vm'
}
},
resolve: {
episodeTypes: ['EpisodeType', function(EpisodeType) {
return EpisodeType.query();
}]
}
});
};
stateConfig.$inject = ['$stateProvider'];
angular.module('yujihomo').config(stateConfig);
})();
|
xzlstc415/japanesekoreanug
|
client/src/app/episode_type_management/episode_type_management.route.js
|
JavaScript
|
mit
| 743
|
describe('Deceptive Offer', function() {
integration(function() {
describe('Deceptive Offer\'s action', function() {
beforeEach(function() {
this.setupTest({
phase: 'conflict',
player1: {
inPlay: ['bayushi-manipulator'],
hand: ['deceptive-offer'],
honor: 10
},
player2: {
honor: 10
}
});
this.noMoreActions();
this.bayushiManipulator = this.player1.findCardByName('bayushi-manipulator');
});
it('should prompt a character to be chosen', function() {
this.initiateConflict({
type: 'military',
attackers: [this.bayushiManipulator],
defenders: []
});
this.player2.pass();
this.player1.clickCard('deceptive-offer');
expect(this.player1).toHavePrompt('Choose a character');
});
it('should give the opponent an option to select between effects', function() {
this.initiateConflict({
type: 'military',
attackers: [this.bayushiManipulator],
defenders: []
});
this.player2.pass();
this.player1.clickCard('deceptive-offer');
this.player1.clickCard(this.bayushiManipulator);
expect(this.player2).toHavePromptButton('Allow your opponent\'s character to gain military and political skill');
expect(this.player2).toHavePromptButton('Give your opponent 1 honor');
});
it('should give +2/+2 when the option is selected', function() {
this.initiateConflict({
type: 'military',
attackers: [this.bayushiManipulator],
defenders: []
});
this.player2.pass();
this.player1.clickCard('deceptive-offer');
this.player1.clickCard(this.bayushiManipulator);
this.player2.clickPrompt('Allow your opponent\'s character to gain military and political skill');
expect(this.bayushiManipulator.getMilitarySkill()).toBe(3);
expect(this.bayushiManipulator.getPoliticalSkill()).toBe(3);
});
it('should cause the opponent to lose 1 honor and the player to gain 1 honor', function() {
this.initiateConflict({
type: 'military',
attackers: [this.bayushiManipulator],
defenders: []
});
this.player2.pass();
this.player1.clickCard('deceptive-offer');
this.player1.clickCard(this.bayushiManipulator);
this.player2.clickPrompt('Give your opponent 1 honor');
expect(this.player1.player.honor).toBe(11);
expect(this.player2.player.honor).toBe(9);
});
});
});
});
|
gryffon/ringteki
|
test/server/cards/04.4-TEaF/DeceptiveOffer.spec.js
|
JavaScript
|
mit
| 3,216
|
'use strict';
var iteratorSymbol = require('es6-symbol').iterator;
module.exports = function (t, a) {
var x;
a.throws(function () { t(0); }, TypeError, "0");
a.throws(function () { t(false); }, TypeError, "false");
a(t(''), '', "''");
a.throws(function () { t({}); }, TypeError, "Plain Object");
a.throws(function () { t(function () {}); }, TypeError, "Function");
a(t(x = String('raz')), x, "String object"); //jslint: ignore
a(t(x = { length: 1 }), x, "Array like");
a.throws(function () { t(); }, TypeError, "Undefined");
a.throws(function () { t(null); }, TypeError, "null");
x = {};
x[iteratorSymbol] = function () {};
a(t(x), x, "Iterable");
};
|
Berkmann18/Essencejs
|
1.0/node_modules/eslint/node_modules/escope/node_modules/es6-weak-map/node_modules/es5-ext/test/iterable/validate.js
|
JavaScript
|
mit
| 667
|
var wprm_admin = wprm_admin || {};
wprm_admin.prep_time_set = false;
wprm_admin.cook_time_set = false;
wprm_admin.total_time_set = false;
wprm_admin.editing_recipe = 0;
wprm_admin.editing_recipe_type = 'insert';
wprm_admin.editing_recipe_fields = false;
wprm_admin.editing_recipe_ingredients = {};
wprm_admin.editing_recipe_instructions = {};
wprm_admin.set_recipe = function(args) {
var recipe_id = args.recipe_id ? args.recipe_id : 0;
var clone_recipe_id = args.clone_recipe_id ? args.clone_recipe_id : 0;
wprm_admin.editing_recipe = recipe_id;
wprm_admin.editing_recipe_type = 0 === recipe_id ? 'insert' : 'update';
wprm_admin.editing_recipe_fields = false;
wprm_admin.editing_recipe_ingredients = {};
wprm_admin.editing_recipe_instructions = {};
wprm_admin.clear_recipe_fields();
if(typeof wprmp_admin !== 'undefined') {
wprmp_admin.clear_recipe_fields();
}
if ('insert' === wprm_admin.editing_recipe_type) {
var button = jQuery('.wprm-button-action'),
button_save = jQuery('.wprm-button-action-save');
jQuery('.wprm-router.active').find('.wprm-menu-item').each(function() {
jQuery(this).data('button', wprm_modal.text.action_button_insert);
});
button.text(wprm_modal.text.action_button_insert);
button_save.show();
if(clone_recipe_id) {
var data = {
action: 'wprm_get_recipe',
security: wprm_modal.nonce,
recipe_id: clone_recipe_id
};
wprm_admin.start_loader(button);
wprm_admin.start_loader(button_save);
jQuery.post(wprm_modal.ajax_url, data, function(out) {
wprm_admin.stop_loader(button);
wprm_admin.stop_loader(button_save);
if (out.success) {
wprm_admin.editing_recipe_fields = out.data.recipe;
wprm_admin.set_recipe_fields(out.data.recipe);
if(typeof wprmp_admin !== 'undefined') {
wprmp_admin.set_recipe_fields(out.data.recipe);
}
}
}, 'json');
}
} else {
var button = jQuery('.wprm-button-action'),
button_save = jQuery('.wprm-button-action-save');
jQuery('.wprm-router.active').find('.wprm-menu-item').each(function() {
jQuery(this).data('button', wprm_modal.text.action_button_update);
});
button.text(wprm_modal.text.action_button_update);
button_save.show();
wprm_admin.disable_menu();
var data = {
action: 'wprm_get_recipe',
security: wprm_modal.nonce,
recipe_id: recipe_id
};
wprm_admin.start_loader(button);
wprm_admin.start_loader(button_save);
jQuery.post(wprm_modal.ajax_url, data, function(out) {
wprm_admin.stop_loader(button);
wprm_admin.stop_loader(button_save);
if (out.success) {
wprm_admin.editing_recipe_fields = out.data.recipe;
wprm_admin.set_recipe_fields(out.data.recipe);
if(typeof wprmp_admin !== 'undefined') {
wprmp_admin.set_recipe_fields(out.data.recipe);
}
jQuery('.wprm-frame-title').find('h1').text(wprm_modal.text.edit_recipe);
}
}, 'json');
}
};
wprm_admin.edit_recipe = function() {
var id = parseInt(jQuery('#wprm-edit-recipe-id').val());
if(id != 0) {
var editor = wprm_admin.active_editor_id;
wprm_admin.close_modal();
wprm_admin.open_modal(editor, {
recipe_id: id
});
}
};
wprm_admin.insert_recipe = function() {
var id = parseInt(jQuery('#wprm-insert-recipe-id').val());
if(id != 0) {
var shortcode = '[wprm-recipe id="' + id + '"]';
wprm_admin.add_text_to_editor(shortcode);
wprm_admin.close_modal();
}
};
wprm_admin.clear_recipe_fields = function() {
// Recipe Details
wprm_admin.remove_media_image(jQuery('.wprm-recipe-image-container'));
jQuery('#wprm-recipe-name').val('');
wprm_admin.rich_editor.resetContent(''); // Recipe summary
jQuery('#wprm-recipe-author-display').val('disabled').change();
jQuery('#wprm-recipe-author-name').val('');
jQuery('#wprm-recipe-author-link').val('');
jQuery('#wprm-recipe-servings').val('');
jQuery('#wprm-recipe-servings-unit').val('');
jQuery('#wprm-recipe-calories').val('');
jQuery('#wprm-recipe-prep-time').val('');
jQuery('#wprm-recipe-cook-time').val('');
jQuery('#wprm-recipe-total-time').val('');
wprm_admin.prep_time_set = false;
wprm_admin.cook_time_set = false;
wprm_admin.total_time_set = false;
jQuery('.wprm-recipe-tags').val(null).trigger('change');
// Ingredients & Instructions
jQuery('.wprm-recipe-ingredients .wprm-recipe-ingredients-instructions-delete, .wprm-recipe-instructions .wprm-recipe-ingredients-instructions-delete').each(function() {
jQuery(this).click();
});
jQuery('.wprm-recipe-ingredients-add').click();
jQuery('.wprm-recipe-instructions-add').click();
// Recipe Notes
if (typeof tinyMCE !== 'undefined' && tinyMCE.get('wprm_recipe_notes') && !tinyMCE.get('wprm_recipe_notes').isHidden()) {
tinyMCE.get('wprm_recipe_notes').focus(true);
// Check for error caused by EasyRecipe.
jQuery('.wprm-easyrecipe-warning').hide();
try {
tinyMCE.activeEditor.setContent('');
} catch(err) {
jQuery('.wprm-easyrecipe-warning').show();
}
} else {
jQuery('#wprm_recipe_notes').val('');
}
};
wprm_admin.set_recipe_fields = function(recipe) {
// Recipe Details
if (parseInt(recipe.image_id) > 0) {
wprm_admin.set_media_image(jQuery('.wprm-recipe-details-form .wprm-recipe-image-container'), recipe.image_id, recipe.image_url);
}
jQuery('#wprm-recipe-name').val(recipe.name);
wprm_admin.rich_editor.setContent(recipe.summary);
jQuery('#wprm-recipe-servings-unit').val(recipe.servings_unit);
jQuery('#wprm-recipe-author-display').val(recipe.author_display).change();
jQuery('#wprm-recipe-author-name').val(recipe.author_name);
jQuery('#wprm-recipe-author-link').val(recipe.author_link);
var servings = parseInt(recipe.servings) > 0 ? parseInt(recipe.servings) : '',
calories = recipe.nutrition.calories ? parseFloat(recipe.nutrition.calories) : '',
prep_time = parseInt(recipe.prep_time) > 0 ? parseInt(recipe.prep_time) : '',
cook_time = parseInt(recipe.cook_time) > 0 ? parseInt(recipe.cook_time) : '',
total_time = parseInt(recipe.total_time) > 0 ? parseInt(recipe.total_time) : '';
jQuery('#wprm-recipe-servings').val(servings);
jQuery('#wprm-recipe-calories').val(calories);
jQuery('#wprm-recipe-prep-time').val(prep_time);
jQuery('#wprm-recipe-cook-time').val(cook_time);
jQuery('#wprm-recipe-total-time').val(total_time);
if (prep_time) wprm_admin.prep_time_set = true;
if (cook_time) wprm_admin.cook_time_set = true;
if (total_time) wprm_admin.total_time_set = true;
for (var tag in recipe.tags) {
if (recipe.tags.hasOwnProperty(tag)) {
wprm_admin.set_recipe_tags(recipe, tag);
}
}
// Ingredients & Instructions
wprm_admin.set_recipe_ingredient_fields(recipe.ingredients);
wprm_admin.set_recipe_instruction_fields(recipe.instructions);
// Recipe Notes
if (typeof tinyMCE !== 'undefined' && tinyMCE.get('wprm_recipe_notes') && !tinyMCE.get('wprm_recipe_notes').isHidden()) {
tinyMCE.get('wprm_recipe_notes').focus(true);
tinyMCE.activeEditor.setContent(recipe.notes);
} else {
jQuery('#wprm_recipe_notes').val(recipe.notes);
}
};
wprm_admin.set_recipe_ingredient_fields = function(ingredients) {
jQuery('.wprm-recipe-ingredients .wprm-recipe-ingredients-instructions-delete').each(function() {
jQuery(this).click();
});
var i, l, group, j, m;
for (i = 0, l = ingredients.length; i < l; i++) {
group = ingredients[i];
if (i > 0 || group.name !== '') {
wprm_admin.add_ingredient_group(group.name);
}
for (j = 0, m = group.ingredients.length; j < m; j++) {
var ingredient = group.ingredients[j];
var uid = wprm_admin.add_ingredient(ingredient.amount, ingredient.unit, ingredient.name, ingredient.notes);
wprm_admin.editing_recipe_ingredients[uid] = ingredient;
}
}
};
wprm_admin.set_recipe_instruction_fields = function(instructions) {
jQuery('.wprm-recipe-instructions .wprm-recipe-ingredients-instructions-delete').each(function() {
jQuery(this).click();
});
var i, l, group, j, m;
for (i = 0, l = instructions.length; i < l; i++) {
group = instructions[i];
if (i > 0 || group.name !== '') {
wprm_admin.add_instruction_group(group.name);
}
for (j = 0, m = group.instructions.length; j < m; j++) {
var instruction = group.instructions[j];
var uid = wprm_admin.add_instruction(instruction.text, instruction.image);
wprm_admin.editing_recipe_instructions[uid] = instruction;
}
}
};
wprm_admin.set_recipe_tags = function(recipe, tag) {
var term_ids = [],
select = jQuery('#wprm-recipe-tag-' + tag);
for (var i = 0, l = recipe.tags[tag].length; i < l; i++) {
var term = recipe.tags[tag][i];
term_ids.push(term.term_id);
// Add term to options if not in there
if (select.find('option[value=' + term.term_id + ']').length === 0) {
select.append('<option value="' + term.term_id + '">' + term.name + '</option>');
}
}
select.val(term_ids).trigger('change');
};
wprm_admin.select_media_image = function(container) {
// Create a new media frame (don't reuse because we have multiple different inputs)
var frame = wp.media({
title: wprm_modal.text.media_title,
button: {
text: wprm_modal.text.media_button
},
multiple: false
});
// When an image is selected in the media frame...
frame.on('select', function() {
var attachment = frame.state().get('selection').first().toJSON();
wprm_admin.set_media_image(container, attachment.id, attachment.url);
});
// Finally, open the modal on click
frame.open();
};
wprm_admin.set_media_image = function(container, image_id, image_url) {
container.find('.wprm-recipe-image-preview').html('');
container.find('.wprm-recipe-image-preview').append('<img src="' + image_url + '" />');
container.find('input').val(image_id);
container.find('.wprm-recipe-image-add').addClass('hidden');
container.find('.wprm-recipe-image-remove').removeClass('hidden');
};
wprm_admin.remove_media_image = function(container) {
container.find('.wprm-recipe-image-preview').html('');
container.find('input').val('');
container.find('.wprm-recipe-image-add').removeClass('hidden');
container.find('.wprm-recipe-image-remove').addClass('hidden');
};
wprm_admin.start_loader = function(button) {
button
.prop('disabled', true)
.css('width', button.outerWidth())
.data('text', button.html())
.html('...');
};
wprm_admin.stop_loader = function(button) {
button
.prop('disabled', false)
.css('width', '')
.html(button.data('text'));
};
wprm_admin.add_ingredient = function(amount, unit, name, notes) {
amount = amount || '';
unit = unit || '';
name = name || '';
notes = notes || '';
var clone = jQuery('.wprm-recipe-ingredients-placeholder').find('.wprm-recipe-ingredient').clone();
jQuery('.wprm-recipe-ingredients').append(clone);
clone.find('.wprm-recipe-ingredient-amount').val(amount).focus();
clone.find('.wprm-recipe-ingredient-unit').val(unit);
clone.find('.wprm-recipe-ingredient-name').val(name);
clone.find('.wprm-recipe-ingredient-notes').val(notes);
while(true) {
var uid = Math.floor(Math.random() * 99999);
if(!wprm_admin.editing_recipe_ingredients.hasOwnProperty(uid)) {
clone.data('uid', uid);
wprm_admin.editing_recipe_ingredients[uid] = {};
return uid;
}
}
};
wprm_admin.add_ingredient_group = function(name) {
name = name || '';
var clone = jQuery('.wprm-recipe-ingredients-placeholder').find('.wprm-recipe-ingredient-group').clone();
jQuery('.wprm-recipe-ingredients').append(clone);
clone.find('input:first').val(name).focus();
};
wprm_admin.add_instruction = function(text, image_id) {
text = text || '';
image_id = image_id || 0;
var clone = jQuery('.wprm-recipe-instructions-placeholder').find('.wprm-recipe-instruction').clone();
clone.find('.wprm-recipe-instruction-text').addClass('wprm-rich-editor');
jQuery('.wprm-recipe-instructions').append(clone);
clone.find('.wprm-recipe-instruction-text').val(text);
wprm_admin.init_rich_editor();
clone.find('.wprm-recipe-instruction-text').focus();
// Get image thumbnail if there is an instruction image.
if (parseInt(image_id) > 0) {
var image_container = clone.find('.wprm-recipe-image-container'),
button = image_container.find('.wprm-recipe-image-add');
var data = {
action: 'wprm_get_thumbnail',
security: wprm_modal.nonce,
image_id: image_id
};
wprm_admin.start_loader(button);
jQuery.post(wprm_modal.ajax_url, data, function(out) {
wprm_admin.stop_loader(button);
if (out.success) {
wprm_admin.set_media_image(image_container, image_id, out.data.image_url);
}
}, 'json');
}
while(true) {
var uid = Math.floor(Math.random() * 99999);
if(!wprm_admin.editing_recipe_instructions.hasOwnProperty(uid)) {
clone.data('uid', uid);
wprm_admin.editing_recipe_instructions[uid] = {};
return uid;
}
}
};
wprm_admin.add_instruction_group = function(name) {
name = name || '';
var clone = jQuery('.wprm-recipe-instructions-placeholder').find('.wprm-recipe-instruction-group').clone();
jQuery('.wprm-recipe-instructions').append(clone);
clone.find('input:first').val(name).focus();
};
wprm_admin.insert_update_recipe = function(button) {
// Recipe Details
var recipe = {
image_id: jQuery('#wprm-recipe-image-id').val(),
name: jQuery('#wprm-recipe-name').val(),
summary: jQuery('#wprm-recipe-summary').val(),
author_display: jQuery('#wprm-recipe-author-display').val(),
author_name: jQuery('#wprm-recipe-author-name').val(),
author_link: jQuery('#wprm-recipe-author-link').val(),
servings: jQuery('#wprm-recipe-servings').val(),
servings_unit: jQuery('#wprm-recipe-servings-unit').val(),
prep_time: jQuery('#wprm-recipe-prep-time').val(),
cook_time: jQuery('#wprm-recipe-cook-time').val(),
total_time: jQuery('#wprm-recipe-total-time').val(),
nutrition: {
calories: jQuery('#wprm-recipe-calories').val()
},
tags: {
course: jQuery('#wprm-recipe-tag-course').val(),
cuisine: jQuery('#wprm-recipe-tag-cuisine').val()
}
};
// Recipe Tags
recipe.tags = {};
jQuery('.wprm-recipe-tags').each(function() {
recipe.tags[jQuery(this).data('key')] = jQuery(this).val();
});
// Recipe Ingredients
recipe.ingredients = wprm_admin.get_ingredients();
// Recipe Instructions
var instructions = [];
var instruction_group = {
name: '',
instructions: []
};
jQuery('.wprm-recipe-instructions').find('tr').each(function() {
var row = jQuery(this);
if (row.hasClass('wprm-recipe-instruction-group')) {
// Add current instruction group to instructions
instructions.push(instruction_group);
instruction_group = {
name: row.find('.wprm-recipe-instruction-group-name').val(),
instructions: []
};
} else {
instruction_group.instructions.push({
text: row.find('textarea.wprm-recipe-instruction-text').val(),
image: row.find('.wprm-recipe-instruction-image').val()
});
}
});
// Add remaining instruction group
instructions.push(instruction_group);
recipe.instructions = instructions;
// Recipe Notes
if (typeof tinyMCE !== 'undefined' && tinyMCE.get('wprm_recipe_notes') && !tinyMCE.get('wprm_recipe_notes').isHidden()) {
recipe.notes = tinyMCE.get('wprm_recipe_notes').getContent();
} else {
recipe.notes = jQuery('#wprm_recipe_notes').val();
}
// Add any Premium fields
if(typeof wprmp_admin !== 'undefined') {
recipe = wprmp_admin.insert_update_recipe(recipe);
}
// Ajax call to recipe saver
var data = {
action: 'wprm_save_recipe',
security: wprm_modal.nonce,
recipe_id: wprm_admin.editing_recipe,
recipe: recipe
};
jQuery('.wprm-button-action-save').prop('disabled', true);
wprm_admin.start_loader(button);
jQuery.post(wprm_modal.ajax_url, data, function(out) {
wprm_admin.stop_loader(button);
jQuery('.wprm-button-action-save').prop('disabled', false);
if (out.success) {
if (wprm_admin.editing_recipe === 0) {
wprm_admin.editing_recipe = out.data.id;
}
if(!button.hasClass('wprm-button-action-save')) {
if ('insert' === wprm_admin.editing_recipe_type) {
wprm_admin.add_text_to_editor('[wprm-recipe id="' + out.data.id + '"]');
} else if(wprm_admin.active_editor_id) {
// Refresh content in editor to reload recipe preview
if (typeof tinyMCE !== 'undefined' && tinyMCE.get(wprm_admin.active_editor_id) && !tinyMCE.get(wprm_admin.active_editor_id).isHidden()) {
tinyMCE.get(wprm_admin.active_editor_id).focus(true);
tinyMCE.activeEditor.setContent(tinyMCE.activeEditor.getContent());
}
}
if(jQuery('.wprm-manage-datatable').length > 0) {
jQuery('.wprm-manage-datatable').DataTable().ajax.reload(null, false);
}
wprm_admin.close_modal();
}
}
}, 'json');
};
wprm_admin.get_ingredients = function() {
var ingredients = [];
var ingredient_group = {
name: '',
ingredients: []
};
jQuery('.wprm-recipe-ingredients').find('tr').each(function() {
var row = jQuery(this);
if (row.hasClass('wprm-recipe-ingredient-group')) {
// Add current ingredient group to ingredients
ingredients.push(ingredient_group);
ingredient_group = {
name: row.find('.wprm-recipe-ingredient-group-name').val(),
ingredients: []
};
} else {
var uid = row.data('uid'),
ingredient = {};
// Get original values.
if(wprm_admin.editing_recipe_ingredients.hasOwnProperty(uid)) {
ingredient = wprm_admin.editing_recipe_ingredients[uid];
}
// Update ingredients.
ingredient['amount'] = row.find('.wprm-recipe-ingredient-amount').val();
ingredient['unit'] = row.find('.wprm-recipe-ingredient-unit').val();
ingredient['name'] = row.find('.wprm-recipe-ingredient-name').val();
ingredient['notes'] = row.find('.wprm-recipe-ingredient-notes').val();
// Unit Conversion.
var converted = jQuery('#wprm-ingredient-conversion-' + uid);
if (converted.length > 0) {
var amount = converted.find('.wprmuc-system-2-amount').val(),
unit = converted.find('.wprmuc-system-2-unit').val();
ingredient['converted'] = {
2: {
amount: amount,
unit: unit,
}
};
}
// Add ingredient to group.
ingredient_group.ingredients.push(ingredient);
}
});
// Add remaining ingredient group
ingredients.push(ingredient_group);
return ingredients;
};
jQuery(document).ready(function($) {
// Recipe and Instruction Image handler
jQuery('.wprm-recipe-details-form, .wprm-recipe-instructions-form').on('click', '.wprm-recipe-image-add', function(e) {
wprm_admin.select_media_image(jQuery(this).parents('.wprm-recipe-image-container'));
});
jQuery('.wprm-recipe-details-form, .wprm-recipe-instructions-form').on('click', '.wprm-recipe-image-remove', function(e) {
wprm_admin.remove_media_image(jQuery(this).parents('.wprm-recipe-image-container'));
});
// Initialize rich editor
wprm_admin.init_rich_editor();
// Author
jQuery('#wprm-recipe-author-display').select2_wprm({
width: '95%'
});
jQuery(document).on('change', '#wprm-recipe-author-display', function() {
var author_display = jQuery(this).val(),
default_display = jQuery(this).find('option:first').data('default');
if(author_display == 'custom' || (author_display == 'default' && default_display == 'custom')) {
jQuery('#wprm-recipe-author-name-container').show();
jQuery('#wprm-recipe-author-link-container').show();
} else {
jQuery('#wprm-recipe-author-name-container').hide();
jQuery('#wprm-recipe-author-link-container').hide();
}
});
jQuery('#wprm-recipe-author-display').change();
// Recipe Times
jQuery('.wprm-recipe-time').on('keyup change', function() {
var container = jQuery(this),
prep_time_container = jQuery('#wprm-recipe-prep-time'),
prep_time = prep_time_container.val(),
cook_time_container = jQuery('#wprm-recipe-cook-time'),
cook_time = cook_time_container.val(),
total_time_container = jQuery('#wprm-recipe-total-time'),
total_time = total_time_container.val();
if (container.is('#wprm-recipe-prep-time')) wprm_admin.prep_time_set = true;
if (container.is('#wprm-recipe-cook-time')) wprm_admin.cook_time_set = true;
if (container.is('#wprm-recipe-total-time')) wprm_admin.total_time_set = true;
if (prep_time && cook_time && !wprm_admin.total_time_set) total_time_container.val(parseInt(prep_time) + parseInt(cook_time));
if (total_time && prep_time && !wprm_admin.cook_time_set) cook_time_container.val(parseInt(total_time) - parseInt(prep_time));
if (total_time && cook_time && !wprm_admin.prep_time_set) prep_time_container.val(parseInt(total_time) - parseInt(cook_time));
});
// Recipe Tags
jQuery('.wprm-recipe-tags').select2_wprm({
width: '95%',
tags: true
});
// Add Recipe Ingredients and Instructions
jQuery('.wprm-recipe-ingredients-add').on('click', function() {
wprm_admin.add_ingredient();
});
jQuery('.wprm-recipe-ingredients-add-group').on('click', function() {
wprm_admin.add_ingredient_group();
});
jQuery('.wprm-recipe-instructions-add').on('click', function() {
wprm_admin.add_instruction('');
});
jQuery('.wprm-recipe-instructions-add-group').on('click', function() {
wprm_admin.add_instruction_group();
});
// Add new ingredient/instruction on TAB
jQuery('.wprm-recipe-ingredients').on('keydown', '.wprm-recipe-ingredient-notes, .wprm-recipe-ingredient-group-name', function(e) {
var keyCode = e.keyCode || e.which,
input = jQuery(this);
if (!e.shiftKey && keyCode == 9 && jQuery(this).parents('tr').is('tr:last-child')) {
e.preventDefault();
wprm_admin.add_ingredient();
}
});
jQuery('.wprm-recipe-instructions').on('keydown', '.wprm-recipe-instruction-text, .wprm-recipe-instruction-group-name', function(e) {
var keyCode = e.keyCode || e.which,
input = jQuery(this);
if (!e.shiftKey && keyCode == 9 && jQuery(this).parents('tr').is('tr:last-child')) {
e.preventDefault();
wprm_admin.add_instruction();
}
});
// Remove Recipe Ingredients and Instructions
jQuery('.wprm-recipe-ingredients-instructions-form').on('click', '.wprm-recipe-ingredients-instructions-delete', function() {
jQuery(this).parents('tr').remove();
});
// Sort Recipe Ingredients and Instructions
jQuery('.wprm-recipe-ingredients, .wprm-recipe-instructions').sortable({
opacity: 0.6,
revert: true,
cursor: 'move',
handle: '.wprm-recipe-ingredients-instructions-sort',
});
// Save recipe button.
jQuery('.wprm-button-action-save').on('click', function() {
wprm_admin.insert_update_recipe(jQuery(this));
});
});
|
florianduport/slowvan
|
wp-content/plugins/wp-recipe-maker/assets/js/admin/recipe-form.js
|
JavaScript
|
mit
| 22,762
|
var job = {
api: noddy.api,
url: '/job', // this should default to /job if this lib is to be generic
file: undefined,
filename: '',
results: [],
hash: undefined,
max:3000
};
job.url = job.api + job.url;
job.review = function() {
if ( $('#jobinfo').length ) {
var msg = '<p>';
msg += job.results.length;
msg += ' rows, with headers ' + job.headers + '</p>';
$('#jobinfo').html(msg).show();
}
}
job.transform = function(split,wrap) {
job.results = [];
if (split === undefined) split = ',';
if (wrap === undefined) wrap = '"';
var wrapreplace = new RegExp(wrap,"g");
job.file = job.file.replace(/\r\n/g,'\n').replace(/\n{2,}/g,'\n').replace(/\n*$/g,'');
var lines = [];
var fls = job.file.split('\n');
var il = '';
for ( var f in fls ) {
il += fls[f];
if ( il.split(wrap).length % 2 !== 0 ) {
lines.push(il);
il = '';
}
}
if (!job.max || lines.length > job.max) {
$('#jobinfo').html('<p style="color:black;">Sorry, the maximum amount of rows you can submit in one file is ' + job.max + '. Please reduce the size of your file and try again.</p>').show();
job.file = undefined;
job.filename = '';
} else {
job.headers = [];
var hline = lines.shift();
var hlines = hline.split(split);
var hl = '';
for ( var h in hlines ) {
if (hl.length > 0) hl += ',';
hl += hlines[h];
if ( hl.split(wrap).length % 2 !== 0 ) {
hl = hl.replace(wrapreplace,'').replace(/(^\s*)|(\s*$)/g,''); // strip whitespace leading and ending header names
//hl = hl.toLowerCase().replace(/ /g,'_').replace(/[^a-z0-9_]/g,'');; // could do additional header cleaning here
job.headers.push(hl);
hl = '';
}
}
for (var i = 0; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(split);
var cl = '';
var counter = 0;
var lengths = 0;
for ( var col in currentline ) {
if (cl.length > 0) cl += ',';
cl += currentline[col];
if ( cl.split(wrap).length % 2 !== 0 ) {
cl = cl.replace(wrapreplace,'');
if (job.headers[counter] && job.headers[counter].length > 0) obj[job.headers[counter]] = cl;
if (lengths === 0) lengths = cl.length;
cl = '';
counter += 1;
}
}
if (lengths) job.results.push(obj);
}
job.review();
}
}
job.prep = function(e) {
if ($(this).attr('id') !== 'jobupload') return;
var f;
if( window.FormData === undefined ) {
f = (e.files || e.dataTransfer.files);
} else {
f = e.target.files[0];
}
job.filename = f.name;
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
job.file = e.target.result;
job.transform();
};
})(f);
reader.readAsBinaryString(f);
}
job.error = function(data) {
$('#jobsubmit').attr('value','Submit');
$('#jobinfo').html('<p">Sorry, there has been an error with your submission. Please try again.<br>If you continue to receive an error, please contact us@cottagelabs.com attaching a copy of your file and with the following error information:<br>' + JSON.stringify(data) + '</p>').show();
}
job.polling = function(data) {
$('.jobupload').hide();
$('#jobinfo').show();
var progress = !data.progress ? 0 : data.progress;
var pc = (Math.floor(progress * 10))/10;
var status = '<p>Job ';
status += data.name ? data.name : '#' + data._id;
status += '</p>';
if (data.new === true) status += '<p>Your job is new, and is still being loaded into the system. For large jobs this may take a couple of minutes.</p>';
status += '<p>Your job is ' + pc + '% complete.</p>';
status += '<p><a id="jobdownload" href="' + job.url + '/' + job.hash + '/results?format=csv&apikey=' + noddy.apikey + '" class="btn btn-default btn-block">Download your results</a></p>';
if (data.progress !== 100) setTimeout(job.poll,10000);
$('#jobinfo').html(status);
}
job.poll = function(hash) {
if (hash === undefined) {
job.hash = window.location.hash.replace('#','');
hash = job.hash
}
if ( hash ) {
$.ajax({
url: job.url + '/' + hash + '/progress?apikey='+noddy.apikey,
method: 'GET',
success: job.polling,
error: job.error
});
}
}
job.success = function(data) {
$('.jobupload').hide();
try {
window.history.pushState("", "poll", '#' + data.job._id);
} catch (err) {}
job.hash = data.job._id;
job.poll(data.job._id);
}
job.submit = function(e) {
$('#jobinfo').html("").hide();
e.preventDefault();
if ( !job.filename ) {
$('#jobinfo').html('<p">You must upload a file in order to submit. Please provide more information and try again.</p>').show();
} else {
$('#jobsubmit').attr('value','Submitting...');
var payload = {list:job.results,name:job.filename};
$.ajax({
url: job.url + '?apikey='+noddy.apikey,
method: 'POST',
data: JSON.stringify(payload),
dataType: 'JSON', // TODO sort issue here, the POST invalidates preflight without jsonp but with jsonp we don't get back a jsonp object
contentType: "application/json; charset=utf-8",
success: job.success,
error: job.error
});
}
}
job.startup = function() {
$('input[type=file]').on('change', job.prep);
$('#jobsubmit').bind('click',job.submit);
if (window.location.hash && window.location.hash.replace('#','').length === 17) { // our job IDs are 17 digits long
setTimeout(function() {$('.jobupload').hide();},200);
$('#jobinfo').html('<p>One moment please, retrieving job status...</p>');
job.hash = window.location.hash.replace('#','');
job.poll(job.hash);
}
}
|
OAButton/oab_static
|
static/job.js
|
JavaScript
|
mit
| 5,610
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 5h-3v5.5c0 1.38-1.12 2.5-2.5 2.5S10 13.88 10 12.5s1.12-2.5 2.5-2.5c.57 0 1.08.19 1.5.51V5h4v2zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6z"
}), 'LibraryMusic');
exports.default = _default;
|
oliviertassinari/material-ui
|
packages/mui-icons-material/lib/LibraryMusic.js
|
JavaScript
|
mit
| 676
|
'use strict';
di('SvgIconSetScope', function(injector) {
var
AbstractRemoteSvgResourceScope = injector('AbstractRemoteSvgResourceScope'),
inherit = injector('inherit')
;
function SvgIconSetScope(id, urlConfig, options) {
AbstractRemoteSvgResourceScope.call(this, id, urlConfig, options);
}
return inherit(SvgIconSetScope, AbstractRemoteSvgResourceScope, {
_loadResource: function() {
var
SvgIconSet = injector('SvgIconSet');
return SvgIconSet.loadByUrl(this._resolveUrl(), this.options);
},
hasIcon: function(iconId, params) {
iconId = this._parseIconId(iconId, params);
return this._getResource()
.then(function(iconSet) {
return iconSet.exists(iconId);
})
},
getIcon: function(iconId, params) {
var
Promise = injector('Promise');
iconId = this._parseIconId(iconId, params);
return this._getResource()
.then(function(iconSet) {
var
icon = iconSet.getIconById(iconId);
return icon
? icon
: Promise.reject();
})
}
});
});
|
princesust/webicon
|
src/core/scope/SvgIconSetScope.js
|
JavaScript
|
mit
| 1,136
|
// set base url here
// At my office
var base_url = 'http://practice.com/mano/';
// At home
var base_url = 'http://localhost/mano/';
$(document).ready(function () {
$('#update').click(function () {
var res_field = document.getElementById("profile_image").value;
var extension = res_field.substr(res_field.lastIndexOf('.') + 1).toLowerCase();
var allowedExtensions = ['jpg', 'jpeg', 'png'];
if (isEmpty(res_field)) {
$('.errorMessage').text('Please browse your profile image!');
} else if (res_field.length > 0) {
if (allowedExtensions.indexOf(extension) === -1) {
$('.errorMessage').text('Invalid file Format. Only ' + allowedExtensions.join(', ') + ' are allowed!');
} else {
$('.errorMessage').text('');
var fd = new FormData(document.getElementById("fileinfo"));
$.ajax({
url: base_url + "admin/user-change-profile",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function (data) {
$('#imageLoading').toggle();
if (typeof data.error == 'undefined') {
location.reload();
} else {
$('#errorMessage').text(data.error);
}
});
return false;
}
}
})
// change / update password starts here
$('#changePasswordButton').click(function () {
$('#UpdatePasswordModal').modal('show');
});
});
var loadFile = function (event) {
var reader = new FileReader();
reader.onload = function () {
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
function isEmpty(str) {
return (!str || 0 === str.length);
}
/*
* Change status
*/
function changeStatus(id, status, url) {
$('#ChangeStatus').modal('show');
var header_text = (status == 0) ? 'Enable' : 'Disable';
var sub_url;
if (url == 'accounting') {
sub_url = 'accounting-user-change-status';
} else if (url == 'admin') {
sub_url = 'admin/';
} else if (url == 'employee') {
sub_url = 'employee-change-status';
}
$('#headerText').text(header_text);
$('#contentText').text('Are you sure to ' + header_text + ' the account ?');
$('#changeOkayButton').unbind().click(function () {
$.ajax({
url: base_url + 'admin/' + sub_url,
dataType: 'text',
type: 'post',
data: {
id: id,
status: status
},
success: function (data) {
location.reload();
},
error: function () {
console.log('error');
}
})
})
}
/*
* Delete everything
*/
function deleteSomething(id, url) {
$('#deleteModal').modal('show');
$('#deleteOkayButton').unbind().click(function () {
var sub_url;
if (url == 'accounting') {
sub_url = 'accounting-user-delete';
} else if (url == 'employee') {
sub_url = 'employee-delete';
} else {
sub_url = '';
}
$.ajax({
url: base_url + 'admin/' + sub_url,
dataType: 'text',
type: 'post',
data: {
id: id
},
success: function (data) {
location.reload();
},
error: function (error) {
}
})
})
}
// update employee
function updateEmployee(id) {
$('#updateEmployeeModal').modal('show');
$.ajax({
url: base_url + 'admin/single-employee',
dataType: 'json',
type: 'post',
data: {
id: id
},
success: function (data) {
$('#firstname').val(data[0].employee_firstname);
$('#lastname').val(data[0].employee_lastname);
$('#address').val(data[0].employee_address);
$('#gender').val(data[0].employee_gender);
$('#birthdate').val(data[0].employee_birthdate);
$('#date_employed').val(data[0].employee_date_employed);
$('#UpdateButton').unbind().click(function () {
var msg = ' is required.';
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var address = $('#address').val();
var gender = $('#gender').val();
var birthdate = $('#birthdate').val();
var date_employed = $('#date_employed').val();
var firstname_err_val = (firstname == '') ? 'The Firstname' + msg : '';
var lastname_err_val = (lastname == '') ? 'The Lastname' + msg : '';
var address_err_val = (address == '') ? 'The Address' + msg : '';
var gender_err_val = (gender == '') ? 'The Gender' + msg : '';
var birth_err_val = (birthdate == '') ? 'The Birthdate' + msg : '';
var employed_err_val = (date_employed == '') ? 'The date employed' + msg : '';
$('#firstname_err').text(firstname_err_val);
$('#lastname_err').text(lastname_err_val);
$('#address_err').text(address_err_val);
$('#gender_err').text(gender_err_val);
$('#birth_err').text(birth_err_val);
$('#employed_err').text(employed_err_val);
if (firstname_err_val.length == 0 && lastname_err_val.length == 0 && address_err_val.length == 0 && gender_err_val.length == 0 && birth_err_val.length == 0 && employed_err_val.length == 0) {
$.ajax({
url: base_url + 'admin/update-employee',
dataType: 'text',
type: 'post',
data: {
id: id,
firstname: firstname,
lastname: lastname,
address: address,
gender: gender,
birthdate: birthdate,
date_employed: date_employed
},
success: function (data) {
location.reload();
},
error: function (error) {
console.log('error');
}
})
} else {
console.log('error');
}
})
},
error: function (error) {
}
})
}
|
johnrobox/mano
|
js/lib/custome.js
|
JavaScript
|
mit
| 6,961
|
'use strict';
angular.module('angular-client-side-auth')
.factory('Auth', function($http, $cookieStore){
var accessLevels = routingConfig.accessLevels
, userRoles = routingConfig.userRoles
, currentUser = $cookieStore.get('user') || { username: '', role: userRoles.public };
$cookieStore.remove('user');
function changeUser(user) {
angular.extend(currentUser, user);
};
return {
authorize: function(accessLevel, role) {
if(role === undefined)
role = currentUser.role;
return accessLevel.bitMask & role.bitMask;
},
isLoggedIn: function(user) {
if(user === undefined)
user = currentUser;
return user.role.title == userRoles.user.title || user.role.title == userRoles.admin.title;
},
register: function(user, success, error) {
$http.post('/register', user).success(function(res) {
changeUser(res);
success();
}).error(error);
},
login: function(user, success, error) {
$http.post('/login', user).success(function(user){
changeUser(user);
success(user);
}).error(error);
},
logout: function(success, error) {
$http.post('/logout').success(function(){
changeUser({
username: '',
role: userRoles.public
});
success();
}).error(error);
},
accessLevels: accessLevels,
userRoles: userRoles,
user: currentUser
};
});
angular.module('angular-client-side-auth')
.factory('Users', function($http) {
return {
getAll: function(success, error) {
$http.get('/users').success(success).error(error);
}
};
});
|
thecreazy/Angular-auth-nodejs-mongodb-html
|
client/js/services.js
|
JavaScript
|
mit
| 1,889
|
var gulp = require('gulp');
var babel = require('gulp-babel');
var mocha = require('gulp-mocha');
gulp.task('babel', function() {
return gulp.src('src/*.js')
.pipe(babel())
.pipe(gulp.dest('dist/'));
});
gulp.task('watch', function() {
gulp.watch('*.js', ['babel']);
});
gulp.task('test', ['babel'], function() {
return gulp.src(['test/*.js'])
.pipe(mocha({ reporter: 'spec' }))
.on('error', function(err) {
console.log(err.stack);
});
});
// Default Task
gulp.task('default', ['babel', 'test']);
|
anvk/easy-sql-tests
|
gulpfile.js
|
JavaScript
|
mit
| 534
|
declare interface $npm$mocha$SetupOptions {
slow?: number;
timeout?: number;
ui?: string;
globals?: Array<any>;
reporter?: any;
bail?: boolean;
ignoreLeaks?: boolean;
grep?: any;
}
declare type $npm$mocha$done = (error?: any) => any;
// declare interface $npm$mocha$SuiteCallbackContext {
// timeout(ms: number): void;
// retries(n: number): void;
// slow(ms: number): void;
// }
// declare interface $npm$mocha$TestCallbackContext {
// skip(): void;
// timeout(ms: number): void;
// retries(n: number): void;
// slow(ms: number): void;
// [index: string]: any;
// }
declare interface $npm$mocha$Suite {
parent: $npm$mocha$Suite;
title: string;
fullTitle(): string;
}
declare type $npm$mocha$ContextDefinition = {|
(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): $npm$mocha$Suite;
only(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): $npm$mocha$Suite;
skip(description: string, callback: (/* this: $npm$mocha$SuiteCallbackContext */) => void): void;
timeout(ms: number): void;
|}
declare type $npm$mocha$TestDefinition = {|
(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): $npm$mocha$Test;
only(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): $npm$mocha$Test;
skip(expectation: string, callback?: (/* this: $npm$mocha$TestCallbackContext, */ done: $npm$mocha$done) => mixed): void;
timeout(ms: number): void;
state: 'failed' | 'passed';
|}
declare interface $npm$mocha$Runner {}
declare class $npm$mocha$BaseReporter {
stats: {
suites: number,
tests: number,
passes: number,
pending: number,
failures: number,
...
};
constructor(runner: $npm$mocha$Runner): $npm$mocha$BaseReporter;
}
declare class $npm$mocha$DocReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$DotReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$HTMLReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$HTMLCovReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$JSONReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$JSONCovReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$JSONStreamReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$LandingReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$ListReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$MarkdownReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$MinReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$NyanReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$ProgressReporter extends $npm$mocha$BaseReporter {
constructor(runner: $npm$mocha$Runner, options?: {
open?: string,
complete?: string,
incomplete?: string,
close?: string,
...
}): $npm$mocha$ProgressReporter;
}
declare class $npm$mocha$SpecReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$TAPReporter extends $npm$mocha$BaseReporter {}
declare class $npm$mocha$XUnitReporter extends $npm$mocha$BaseReporter {
constructor(runner: $npm$mocha$Runner, options?: any): $npm$mocha$XUnitReporter;
}
declare class $npm$mocha$Mocha {
currentTest: $npm$mocha$TestDefinition;
constructor(options?: {
grep?: RegExp,
ui?: string,
reporter?: string,
timeout?: number,
reporterOptions?: any,
slow?: number,
bail?: boolean,
...
}): $npm$mocha$Mocha;
setup(options: $npm$mocha$SetupOptions): this;
bail(value?: boolean): this;
addFile(file: string): this;
reporter(name: string): this;
reporter(reporter: (runner: $npm$mocha$Runner, options: any) => any): this;
ui(value: string): this;
grep(value: string): this;
grep(value: RegExp): this;
invert(): this;
ignoreLeaks(value: boolean): this;
checkLeaks(): this;
throwError(error: Error): void;
growl(): this;
globals(value: string): this;
globals(values: Array<string>): this;
useColors(value: boolean): this;
useInlineDiffs(value: boolean): this;
timeout(value: number): this;
slow(value: number): this;
enableTimeouts(value: boolean): this;
asyncOnly(value: boolean): this;
noHighlighting(value: boolean): this;
run(onComplete?: (failures: number) => void): $npm$mocha$Runner;
static reporters: {
Doc: $npm$mocha$DocReporter,
Dot: $npm$mocha$DotReporter,
HTML: $npm$mocha$HTMLReporter,
HTMLCov: $npm$mocha$HTMLCovReporter,
JSON: $npm$mocha$JSONReporter,
JSONCov: $npm$mocha$JSONCovReporter,
JSONStream: $npm$mocha$JSONStreamReporter,
Landing: $npm$mocha$LandingReporter,
List: $npm$mocha$ListReporter,
Markdown: $npm$mocha$MarkdownReporter,
Min: $npm$mocha$MinReporter,
Nyan: $npm$mocha$NyanReporter,
Progress: $npm$mocha$ProgressReporter,
...
};
}
// declare interface $npm$mocha$HookCallbackContext {
// skip(): void;
// timeout(ms: number): void;
// [index: string]: any;
// }
declare interface $npm$mocha$Runnable {
title: string;
fn: Function;
async: boolean;
sync: boolean;
timedOut: boolean;
}
declare interface $npm$mocha$Test extends $npm$mocha$Runnable {
parent: $npm$mocha$Suite;
pending: boolean;
state: 'failed' | 'passed' | void;
fullTitle(): string;
}
// declare interface $npm$mocha$BeforeAndAfterContext extends $npm$mocha$HookCallbackContext {
// currentTest: $npm$mocha$Test;
// }
declare var mocha: $npm$mocha$Mocha;
declare var describe: $npm$mocha$ContextDefinition;
declare var xdescribe: $npm$mocha$ContextDefinition;
declare var context: $npm$mocha$ContextDefinition;
declare var suite: $npm$mocha$ContextDefinition;
declare var it: $npm$mocha$TestDefinition;
declare var xit: $npm$mocha$TestDefinition;
declare var test: $npm$mocha$TestDefinition;
declare var specify: $npm$mocha$TestDefinition;
type Run = () => void;
declare var run: Run;
type Setup = (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
type Teardown = (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
type SuiteSetup = (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type SuiteTeardown = (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type Before =
| (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type After =
| (callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$HookCallbackContext, */ done: $npm$mocha$done) => mixed) => void;
type BeforeEach =
| (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
type AfterEach =
| (callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void
| (description: string, callback: (/* this: $npm$mocha$BeforeAndAfterContext, */ done: $npm$mocha$done) => mixed) => void;
declare var setup: Setup;
declare var teardown: Teardown;
declare var suiteSetup: SuiteSetup;
declare var suiteTeardown;
declare var before: Before
declare var after: After;
declare var beforeEach: BeforeEach;
declare var afterEach: AfterEach;
declare module "mocha" {
declare export var mocha: $npm$mocha$TestDefinition;
declare export var describe: $npm$mocha$ContextDefinition;
declare export var xdescribe: $npm$mocha$ContextDefinition;
declare export var context: $npm$mocha$ContextDefinition;
declare export var suite: $npm$mocha$ContextDefinition;
declare export var it: $npm$mocha$TestDefinition;
declare export var xit: $npm$mocha$TestDefinition;
declare export var test: $npm$mocha$TestDefinition;
declare export var specify: $npm$mocha$TestDefinition;
declare export var run: Run;
declare export var setup: Setup;
declare export var teardown: Teardown;
declare export var suiteSetup: SuiteSetup;
declare export var suiteTeardown: SuiteTeardown;
declare export var before: Before;
declare export var after: After;
declare export var beforeEach: BeforeEach;
declare export var afterEach: AfterEach;
declare export default $npm$mocha$Mocha;
}
|
splodingsocks/FlowTyped
|
definitions/npm/mocha_v4.x.x/flow_v0.104.x-/mocha_v4.x.x.js
|
JavaScript
|
mit
| 8,656
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var FileCloud = React.createClass({
displayName: 'FileCloud',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96z' })
);
}
});
module.exports = FileCloud;
|
checkraiser/material-ui2
|
lib/svg-icons/file/cloud.js
|
JavaScript
|
mit
| 488
|
import errors from 'feathers-errors';
export default function() {
return function(hook) {
if (hook.type !== 'before') {
throw new Error(`The 'restrictToAuthenticated' hook should only be used as a 'before' hook.`);
}
if (hook.params.provider && hook.params.user === undefined) {
throw new errors.NotAuthenticated('You are not authenticated.');
// TODO (EK): Add debug log to check to see if the user is populated, if the token was verified and warn appropriately
}
};
}
|
m1ch3lcl/feathers-authentication
|
src/hooks/restrict-to-authenticated.js
|
JavaScript
|
mit
| 510
|