code stringlengths 2 1.05M |
|---|
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "2");
design.checkVersion("zrf", "3.0");
design.checkVersion("smart-moves", "from");
design.checkVersion("sliding-puzzle", "true");
design.addDirection("w");
design.addDirection("e");
design.addDirection("s");
design.addDirection("n");
design.addPlayer("You", [1, 0, 3, 2]);
design.addPosition("a5", [0, 1, 4, 0]);
design.addPosition("b5", [-1, 1, 4, 0]);
design.addPosition("c5", [-1, 1, 4, 0]);
design.addPosition("d5", [-1, 0, 4, 0]);
design.addPosition("a4", [0, 1, 4, -4]);
design.addPosition("b4", [-1, 1, 4, -4]);
design.addPosition("c4", [-1, 1, 4, -4]);
design.addPosition("d4", [-1, 0, 4, -4]);
design.addPosition("a3", [0, 1, 4, -4]);
design.addPosition("b3", [-1, 1, 4, -4]);
design.addPosition("c3", [-1, 1, 4, -4]);
design.addPosition("d3", [-1, 0, 4, -4]);
design.addPosition("a2", [0, 1, 4, -4]);
design.addPosition("b2", [-1, 1, 4, -4]);
design.addPosition("c2", [-1, 1, 4, -4]);
design.addPosition("d2", [-1, 0, 4, -4]);
design.addPosition("a1", [0, 1, 0, -4]);
design.addPosition("b1", [-1, 1, 0, -4]);
design.addPosition("c1", [-1, 1, 0, -4]);
design.addPosition("d1", [-1, 0, 0, -4]);
design.addCommand(0, ZRF.FUNCTION, 24); // from
design.addCommand(0, ZRF.PARAM, 0); // $1
design.addCommand(0, ZRF.FUNCTION, 22); // navigate
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addPiece("G01001", 0);
design.addAttribute(0, 0, 1);
design.addAttribute(0, 1, 'G0100');
design.addMove(0, 0, [3], 0);
design.addMove(0, 0, [2], 0);
design.addMove(0, 0, [0], 0);
design.addMove(0, 0, [1], 0);
design.addPiece("G10001", 1);
design.addAttribute(1, 0, 1);
design.addAttribute(1, 1, 'G1000');
design.addMove(1, 0, [3], 0);
design.addMove(1, 0, [2], 0);
design.addMove(1, 0, [0], 0);
design.addMove(1, 0, [1], 0);
design.addPiece("G01002", 2);
design.addAttribute(2, 0, 2);
design.addAttribute(2, 1, 'G0100');
design.addMove(2, 0, [3], 0);
design.addMove(2, 0, [2], 0);
design.addMove(2, 0, [0], 0);
design.addMove(2, 0, [1], 0);
design.addPiece("G10002", 3);
design.addAttribute(3, 0, 2);
design.addAttribute(3, 1, 'G1000');
design.addMove(3, 0, [3], 0);
design.addMove(3, 0, [2], 0);
design.addMove(3, 0, [0], 0);
design.addMove(3, 0, [1], 0);
design.addPiece("G00103", 4);
design.addAttribute(4, 0, 3);
design.addAttribute(4, 1, 'G0010');
design.addMove(4, 0, [3], 0);
design.addMove(4, 0, [2], 0);
design.addMove(4, 0, [0], 0);
design.addMove(4, 0, [1], 0);
design.addPiece("G00013", 5);
design.addAttribute(5, 0, 3);
design.addAttribute(5, 1, 'G0001');
design.addMove(5, 0, [3], 0);
design.addMove(5, 0, [2], 0);
design.addMove(5, 0, [0], 0);
design.addMove(5, 0, [1], 0);
design.addPiece("R0110F4", 6);
design.addAttribute(6, 0, 4);
design.addAttribute(6, 1, 'R0110F');
design.addMove(6, 0, [3], 0);
design.addMove(6, 0, [2], 0);
design.addMove(6, 0, [0], 0);
design.addMove(6, 0, [1], 0);
design.addPiece("R1010F4", 7);
design.addAttribute(7, 0, 4);
design.addAttribute(7, 1, 'R1010F');
design.addMove(7, 0, [3], 0);
design.addMove(7, 0, [2], 0);
design.addMove(7, 0, [0], 0);
design.addMove(7, 0, [1], 0);
design.addPiece("R0101F4", 8);
design.addAttribute(8, 0, 4);
design.addAttribute(8, 1, 'R0101F');
design.addMove(8, 0, [3], 0);
design.addMove(8, 0, [2], 0);
design.addMove(8, 0, [0], 0);
design.addMove(8, 0, [1], 0);
design.addPiece("R1001F4", 9);
design.addAttribute(9, 0, 4);
design.addAttribute(9, 1, 'R1001F');
design.addMove(9, 0, [3], 0);
design.addMove(9, 0, [2], 0);
design.addMove(9, 0, [0], 0);
design.addMove(9, 0, [1], 0);
design.addPiece("G00105", 10);
design.addAttribute(10, 0, 5);
design.addAttribute(10, 1, 'G0010');
design.addMove(10, 0, [3], 0);
design.addMove(10, 0, [2], 0);
design.addMove(10, 0, [0], 0);
design.addMove(10, 0, [1], 0);
design.addPiece("G00015", 11);
design.addAttribute(11, 0, 5);
design.addAttribute(11, 1, 'G0001');
design.addMove(11, 0, [3], 0);
design.addMove(11, 0, [2], 0);
design.addMove(11, 0, [0], 0);
design.addMove(11, 0, [1], 0);
design.addPiece("B00006", 12);
design.addAttribute(12, 0, 6);
design.addAttribute(12, 1, 'B0000');
design.addMove(12, 0, [3], 0);
design.addMove(12, 0, [2], 0);
design.addMove(12, 0, [0], 0);
design.addMove(12, 0, [1], 0);
design.addPiece("G01007", 13);
design.addAttribute(13, 0, 7);
design.addAttribute(13, 1, 'G0100');
design.addMove(13, 0, [3], 0);
design.addMove(13, 0, [2], 0);
design.addMove(13, 0, [0], 0);
design.addMove(13, 0, [1], 0);
design.addPiece("G10007", 14);
design.addAttribute(14, 0, 7);
design.addAttribute(14, 1, 'G1000');
design.addMove(14, 0, [3], 0);
design.addMove(14, 0, [2], 0);
design.addMove(14, 0, [0], 0);
design.addMove(14, 0, [1], 0);
design.addPiece("B00008", 15);
design.addAttribute(15, 0, 8);
design.addAttribute(15, 1, 'B0000');
design.addMove(15, 0, [3], 0);
design.addMove(15, 0, [2], 0);
design.addMove(15, 0, [0], 0);
design.addMove(15, 0, [1], 0);
design.addPiece("B00009", 16);
design.addAttribute(16, 0, 9);
design.addAttribute(16, 1, 'B0000');
design.addMove(16, 0, [3], 0);
design.addMove(16, 0, [2], 0);
design.addMove(16, 0, [0], 0);
design.addMove(16, 0, [1], 0);
design.addPiece("B000010", 17);
design.addAttribute(17, 0, 10);
design.addAttribute(17, 1, 'B0000');
design.addMove(17, 0, [3], 0);
design.addMove(17, 0, [2], 0);
design.addMove(17, 0, [0], 0);
design.addMove(17, 0, [1], 0);
design.setup("You", "G01001", 0);
design.setup("You", "G10001", 1);
design.setup("You", "G01002", 2);
design.setup("You", "G10002", 3);
design.setup("You", "G00103", 4);
design.setup("You", "G00013", 8);
design.setup("You", "R0110F4", 5);
design.setup("You", "R1010F4", 6);
design.setup("You", "R0101F4", 9);
design.setup("You", "R1001F4", 10);
design.setup("You", "G00105", 7);
design.setup("You", "G00015", 11);
design.setup("You", "B00006", 12);
design.setup("You", "G01007", 13);
design.setup("You", "G10007", 14);
design.setup("You", "B00008", 15);
design.setup("You", "B00009", 16);
design.setup("You", "B000010", 19);
design.goal(0, "You", "R0110F4", [13]);
design.goal(0, "You", "R1010F4", [14]);
design.goal(0, "You", "R0101F4", [17]);
design.goal(0, "You", "R1001F4", [18]);
}
Dagaz.View.configure = function(view) {
view.defPiece("YouG01001", "You G01001");
view.defPiece("YouG10001", "You G10001");
view.defPiece("YouG01002", "You G01002");
view.defPiece("YouG10002", "You G10002");
view.defPiece("YouG00103", "You G00103");
view.defPiece("YouG00013", "You G00013");
view.defPiece("YouR0110F4", "You R0110F4");
view.defPiece("YouR1010F4", "You R1010F4");
view.defPiece("YouR0101F4", "You R0101F4");
view.defPiece("YouR1001F4", "You R1001F4");
view.defPiece("YouG00105", "You G00105");
view.defPiece("YouG00015", "You G00015");
view.defPiece("YouB00006", "You B00006");
view.defPiece("YouG01007", "You G01007");
view.defPiece("YouG10007", "You G10007");
view.defPiece("YouB00008", "You B00008");
view.defPiece("YouB00009", "You B00009");
view.defPiece("YouB000010", "You B000010");
view.defPosition("a5", 0, 0, 100, 100);
view.defPosition("b5", 100, 0, 100, 100);
view.defPosition("c5", 200, 0, 100, 100);
view.defPosition("d5", 300, 0, 100, 100);
view.defPosition("a4", 0, 100, 100, 100);
view.defPosition("b4", 100, 100, 100, 100);
view.defPosition("c4", 200, 100, 100, 100);
view.defPosition("d4", 300, 100, 100, 100);
view.defPosition("a3", 0, 200, 100, 100);
view.defPosition("b3", 100, 200, 100, 100);
view.defPosition("c3", 200, 200, 100, 100);
view.defPosition("d3", 300, 200, 100, 100);
view.defPosition("a2", 0, 300, 100, 100);
view.defPosition("b2", 100, 300, 100, 100);
view.defPosition("c2", 200, 300, 100, 100);
view.defPosition("d2", 300, 300, 100, 100);
view.defPosition("a1", 0, 400, 100, 100);
view.defPosition("b1", 100, 400, 100, 100);
view.defPosition("c1", 200, 400, 100, 100);
view.defPosition("d1", 300, 400, 100, 100);
}
|
import endOfWeek from '../endOfWeek/index.js'
/**
* @name endOfISOWeek
* @category ISO Week Helpers
* @summary Return the end of an ISO week for the given date.
*
* @description
* Return the end of an ISO week for the given date.
* The result will be in the local timezone.
*
* ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* @param {Date|Number} date - the original date
* @returns {Date} the end of an ISO week
* @throws {TypeError} 1 argument required
*
* @example
* // The end of an ISO week for 2 September 2014 11:55:00:
* var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0))
* //=> Sun Sep 07 2014 23:59:59.999
*/
export default function endOfISOWeek(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError(
'1 argument required, but only ' + arguments.length + ' present'
)
}
return endOfWeek(dirtyDate, { weekStartsOn: 1 })
}
|
import { collection, clickable, create, isVisible, text } from 'ember-cli-page-object';
import editor from './competency-title-editor';
import newCompetency from './new-competency';
const definition = {
scope: '[data-test-school-competencies-manager]',
domains: collection('[data-test-domain]', {
details: {
scope: '[data-test-domain-details]',
editor,
},
remove: clickable('[data-test-remove-domain]'),
isRemovable: isVisible('[data-test-remove-domain]'),
competencies: collection('[data-test-competency]', {
remove: clickable('[data-test-remove-competency]'),
isRemovable: isVisible('[data-test-remove-competency]'),
objectivesCount: text('[data-test-objectives-count]'),
editor,
}),
newCompetency,
}),
newDomain: {
scope: '[data-test-new-domain]',
newCompetency,
},
};
export default definition;
export const component = create(definition);
|
export { default } from 'ember-data-endpoints/serializer';
|
import EmberObject from '@ember/object';
import fetch from 'fetch';
import { assign } from '@ember/polyfills';
import { Promise, reject, resolve } from 'rsvp';
import { isEmpty } from '@ember/utils';
import Base from 'ember-simple-auth/authenticators/base';
import config from 'ember-get-config';
/**
Authenticator that works with token-based authentication like JWT.
_The factory for this authenticator is registered as `'authenticator:token'` in Ember's container._
@class Token
@namespace SimpleAuth.Authenticators
@module ember-simple-auth-token/authenticators/token
@extends Base
*/
export default Base.extend({
/**
@method init
*/
init() {
this._super(...arguments);
const conf = config['ember-simple-auth-token'] || {};
this.serverTokenEndpoint = conf.serverTokenEndpoint || '/api/token-auth/';
this.tokenPropertyName = conf.tokenPropertyName || 'token';
this.headers = conf.headers || {};
},
/**
Restores the session from a set of session properties; __will return a resolving promise when there's a non-empty `token` in the `properties`__ and a rejecting promise otherwise.
@method restore
@param {Object} properties The properties to restore the session from
@return {Promise} A promise that when it resolves results in the session being authenticated
*/
restore(properties) {
const propertiesObject = EmberObject.create(properties);
return new Promise((resolve, reject) => {
if (!isEmpty(propertiesObject.get(this.tokenPropertyName))) {
return resolve(properties);
} else {
return reject();
}
});
},
/**
Authenticates the session with the specified `credentials`; the credentials are `POST`ed to the [`Authenticators.Token#serverTokenEndpoint`](#SimpleAuth-Authenticators-Token-serverTokenEndpoint) and if they are valid the server returns an auth token in response. __If the credentials are valid and authentication succeeds, a promise that resolves with the server's response is returned__, otherwise a promise that rejects with the server error is returned.
@method authenticate
@param {Object} credentials The credentials to authenticate the session with
@param {Object} headers Optional headers to send with the authentication request
@return {Promise} A promise that resolves when an auth token is successfully acquired from the server and rejects otherwise
*/
authenticate(credentials, headers) {
return this.makeRequest(this.serverTokenEndpoint, credentials, assign({}, this.headers, headers)).then(response => {
return response.json;
});
},
/**
Does nothing
@method invalidate
@return {Promise} A resolving promise
*/
invalidate() {
return resolve();
},
/**
@method makeRequest
@param {Object} url Server endpoint
@param {Object} data Object that will be sent to server
@param {Object} headers Additional headers that will be sent to server
*/
makeRequest(url, data, headers) {
return fetch(url, {
method: 'POST',
headers: assign({
'Accept': 'application/json',
'Content-Type': 'application/json'
}, headers),
body: JSON.stringify(data)
}).then(response => {
const res = {
statusText: response.statusText,
status: response.status,
headers: response.headers
};
return response.text().then(text => {
res.text = text;
try {
res.json = JSON.parse(text);
} catch (e) {
return reject(res);
}
if (response.ok) {
return res;
} else {
return reject(res);
}
}).catch(() => {
return reject(res);
});
});
}
});
|
import React from 'react';
import store from '../../../store/index.js';
import img from '../../../constants/images.js';
import styles from '../../../styles/index.js';
import commonMessages from '../../../translations/common.js';
function onClickHome() {
store.dispatch({ type: (state) => ({
...state,
sidebarHome: {
...state.sidebarHome,
open: !state.sidebarHome.open,
},
sidebarLayers: {
...state.sidebarLayers,
open: false,
},
sidebarInfo: {
...state.sidebarInfo,
open: false,
},
}) });
}
function onClickInfo() {
store.dispatch({ type: (state) => ({
...state,
sidebarHome: {
...state.sidebarHome,
open: false,
},
sidebarLayers: {
...state.sidebarLayers,
open: false,
},
sidebarInfo: {
...state.sidebarInfo,
open: !state.sidebarInfo.open,
},
}) });
}
function onClickLayers() {
store.dispatch({ type: (state) => ({
...state,
sidebarHome: {
...state.sidebarHome,
open: false,
},
sidebarLayers: {
...state.sidebarLayers,
open: !state.sidebarLayers.open,
},
sidebarInfo: {
...state.sidebarInfo,
open: false,
},
}) });
}
export default ({ state, messages }) => (
<div className={`${styles.flex.horizontalCenterY} ${styles.menu.toolbarDefault}`}>
<img alt="home"
className={styles.menu.toolbarImage}
onClick={onClickHome}
src={img.MENU} />
<div className={styles.media.hiddenMobile}>
{commonMessages.titleLong[state.lang]}
</div>
<div className={styles.media.hiddenDesktop}>
{commonMessages.titleShort[state.lang]}
</div>
<div> - </div>
<div className={styles.media.hiddenMobile}>
{messages.titleLong[state.lang]}
</div>
<div className={styles.media.hiddenDesktop}>
{messages.titleShort[state.lang]}
</div>
<div className={styles.flex.itemSpace} />
<img alt="info"
className={styles.menu.toolbarImage}
onClick={onClickInfo}
src={img.INFO} />
<img alt="layers"
className={styles.menu.toolbarImage}
onClick={onClickLayers}
src={img.LAYERS} />
</div>
);
|
import config from "../config";
import * as Kit from "../kit";
import * as Scope from "../scope";
import * as Operations from "../operations";
import * as Optimization from "../optimization";
import * as CFG from "../cfg";
import * as Emit from "../emit";
import * as Meta from "../meta";
import * as Eval from "../eval";
export default function debuggerTransform(ast) {
config.loopsSubScopes = config.timeTravel ? "always" : "closure";
config.reuseTempVars = !config.timeTravel;
config.expInjectTempSetters = false;
config.debug = true;
if (Kit.hasDirective(ast.program, "no-debug")) return;
const root = Kit.produce(ast);
Scope.prepare(root);
Eval.replaceEvalDir();
if (!config.blackbox) Meta.injectBrk();
Scope.split();
Operations.normalizeAssign();
if (config.implictCalls && config.timeTravel) Operations.implicitCalls();
CFG.build();
if (config.timeTravel) {
Operations.setters();
Operations.deleters();
if (config.inlineImplicitOps) Operations.implicitCallsInlined();
}
Optimization.prepare();
if (!config.expInlineCalls) Operations.methodCalls();
Operations.assignCall();
Scope.forEach(Optimization.composeItems);
Scope.forEach(CFG.prepare);
Scope.forEach(Optimization.assignBindVar);
Scope.injectVarGetters();
Scope.forEach(Emit.calcFrames);
Scope.forEach(Optimization.sortFrames);
Scope.forEach(Meta.all);
if (config.timeTravel) Operations.replaceSymNames();
Emit.module();
Kit.consume(root);
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux'
import uuid from 'node-uuid'
import {createSelector} from 'reselect'
import {bindDispatch} from '../common/util/redux'
import { browserHistory } from 'react-router';
export default class ChatTextBox extends React.Component {
render() {
const {name } = this.props;
console.log("entering into child");
console.log(this.props.name);
return (
<div>
</div>
);
}
}
|
/*!
* Expose `RemoteObjects`.
*/
module.exports = RemoteObjects;
/*!
* Module dependencies.
*/
var EventEmitter = require('eventemitter2').EventEmitter2;
var debug = require('debug')('strong-remoting:remotes');
var util = require('util');
var urlUtil = require('url');
var inherits = util.inherits;
var assert = require('assert');
var Dynamic = require('./dynamic');
var SharedClass = require('./shared-class');
var ExportsHelper = require('./exports-helper');
// require the rest adapter for browserification
// TODO(ritch) remove this somehow...?
require('./rest-adapter');
/**
* Create a new `RemoteObjects` with the given `options`.
*
* ```js
* var remoteObjects = require('strong-remoting').create();
* ```
*
* @param {Object} options
* @return {RemoteObjects}
* @class
* @property {Object} auth Authentication options used by underlying adapters
* to set authorization metadata. **The `rest` adapter supports:**
*
* - **basic** - `username` and `password` are required.
* - **digest** - `username` and `password` required and `sendImmediately` must
* be false.
* - **bearer** - `bearer` must be set as the bearer token
*
* @property {String} auth.username
* @property {String} auth.password
* @property {String} auth.bearer The **bearer token**.
* @property {Boolean} auth.sendImmediately Defaults to `false`.
*/
function RemoteObjects(options) {
EventEmitter.call(this, {wildcard: true});
// Avoid warning: possible EventEmitter memory leak detected
this.setMaxListeners(16);
this.options = options || {};
this.exports = this.options.exports || {};
this._classes = {};
}
/*!
* Inherit from `EventEmitter`.
*/
inherits(RemoteObjects, EventEmitter);
/*!
* Simplified APIs
*/
RemoteObjects.create = function(options) {
return new RemoteObjects(options);
};
RemoteObjects.extend = function(exports) {
return new ExportsHelper(exports);
};
/**
* Create a handler from the given adapter.
*
* @param {String} name Adapter name
* @param {Object} options Adapter options
* @return {Function}
*/
RemoteObjects.prototype.handler = function(name, options) {
var Adapter = this.adapter(name);
var adapter = new Adapter(this, options);
var handler = adapter.createHandler();
if (handler) {
// allow adapter reference from handler
handler.adapter = adapter;
}
return handler;
};
/**
* Create a connection to a remoting server.
*
* @param {String} url Server root
* @param {String} name Name of the adapter (eg. "rest")
*/
RemoteObjects.prototype.connect = function(url, name) {
// parse URL for auth
var urlWithoutAuth = url;
var auth;
var parsedUrl = urlUtil.parse(url);
// If base parsedUrl contains auth, extract it so we can set it separately
if (parsedUrl.auth) {
auth = this.auth = {};
auth.username = parsedUrl.auth.split(':')[0];
auth.password = parsedUrl.auth.split(':')[1];
// set base without auth so request honours our auth options
delete parsedUrl.auth;
urlWithoutAuth = urlUtil.format(parsedUrl);
// ensure a "/" hasn't been appended where there wasn't one before
if (url[url.length - 1] !== urlWithoutAuth[urlWithoutAuth.length - 1]) {
urlWithoutAuth = urlWithoutAuth.slice(0, -1);
}
}
var Adapter = this.adapter(name);
var adapter = new Adapter(this);
this.serverAdapter = adapter;
return adapter.connect(urlWithoutAuth);
};
/**
* Invoke a method on a remote server using the connected adapter.
*
* @param {String} method The remote method string
* @param {String} [ctorArgs] Constructor arguments (for prototype methods)
* @param {String} [args] Method arguments
* @callback {Function} [callback] callback
* @param {Error} err
* @param {Any} arg...
* @end
*/
RemoteObjects.prototype.invoke = function(method, ctorArgs, args, callback) {
assert(this.serverAdapter,
'Cannot invoke method without an adapter. See RemoteObjects#connect().');
return this.serverAdapter.invoke.apply(this.serverAdapter, arguments, callback);
};
/**
* Get an adapter by name.
* @param {String} name The adapter name
* @return {Adapter}
*/
RemoteObjects.prototype.adapter = function(name) {
return require('./' + name + '-adapter');
};
/**
* Get all classes.
*/
RemoteObjects.prototype.classes = function(options) {
options = options || {};
var exports = this.exports;
var result = [];
var sharedClasses = this._classes;
Object
.keys(exports)
.forEach(function(name) {
result.push(new SharedClass(name, exports[name], options));
});
Object
.keys(sharedClasses)
.forEach(function(name) {
result.push(sharedClasses[name]);
});
return result;
};
/**
* Add a shared class.
*
* @param {SharedClass} sharedClass
*/
RemoteObjects.prototype.addClass = function(sharedClass) {
assert(sharedClass instanceof SharedClass);
this._classes[sharedClass.name] = sharedClass;
};
/**
* Find a method by its string name.
*
* Example Method Strings:
*
* - `MyClass.prototype.myMethod`
* - `MyClass.staticMethod`
* - `obj.method`
*
* @param {String} methodString
*/
RemoteObjects.prototype.findMethod = function(methodString) {
var methods = this.methods();
for (var i = 0; i < methods.length; i++) {
if (methods[i].stringName === methodString) return methods[i];
}
};
/**
* List all methods.
*/
RemoteObjects.prototype.methods = function() {
var methods = [];
this
.classes()
.forEach(function(sc) {
methods = sc.methods().concat(methods);
});
return methods;
};
/**
* Get as JSON.
*/
RemoteObjects.prototype.toJSON = function() {
var result = {};
var methods = this.methods();
methods.forEach(function(sharedMethod) {
result[sharedMethod.stringName] = {
http: sharedMethod.fn && sharedMethod.fn.http,
accepts: sharedMethod.accepts,
returns: sharedMethod.returns,
errors: sharedMethod.errors
};
});
return result;
};
/**
* Execute the given function before the matched method string.
*
* **Examples:**
*
* ```js
* // Do something before our `user.greet` example, earlier.
* remotes.before('user.greet', function(ctx, next) {
* if ((ctx.req.param('password') || '').toString() !== '1234') {
* next(new Error('Bad password!'));
* } else {
* next();
* }
* });
*
* // Do something before any `user` method.
* remotes.before('user.*', function(ctx, next) {
* console.log('Calling a user method.');
* next();
* });
*
* // Do something before a `dog` instance method.
* remotes.before('dog.prototype.*', function(ctx, next) {
* var dog = this;
* console.log('Calling a method on "%s".', dog.name);
* next();
* });
* ```
*
* @param {String} methodMatch The glob to match a method string
* @callback {Function} hook
* @param {Context} ctx The adapter specific context
* @param {Function} next Call with an optional error object
* @param {SharedMethod} method The SharedMethod object
*/
RemoteObjects.prototype.before = function(methodMatch, fn) {
this.on('before.' + methodMatch, fn);
};
/**
* Execute the given `hook` function after the matched method string.
*
* **Examples:**
*
* ```js
* // Do something after the `speak` instance method.
* // NOTE: you cannot cancel a method after it has been called.
* remotes.after('dog.prototype.speak', function(ctx, next) {
* console.log('After speak!');
* next();
* });
*
* // Do something before all methods.
* remotes.before('**', function(ctx, next, method) {
* console.log('Calling:', method.name);
* next();
* });
*
* // Modify all returned values named `result`.
* remotes.after('**', function(ctx, next) {
* ctx.result += '!!!';
* next();
* });
* ```
*
* @param {String} methodMatch The glob to match a method string
* @callback {Function} hook
* @param {Context} ctx The adapter specific context
* @param {Function} next Call with an optional error object
* @param {SharedMethod} method The SharedMethod object
*/
RemoteObjects.prototype.after = function(methodMatch, fn) {
this.on('after.' + methodMatch, fn);
};
/*!
* Create a middleware style emit that supports wildcards.
*/
RemoteObjects.prototype.execHooks = function(when, method, scope, ctx, next) {
var stack = [];
var ee = this;
var isStatic = method.isStatic ||
method.sharedMethod && method.sharedMethod.isStatic;
var type;
// Commented-out by bajtos: init is not defined.
// this._events || init.call(this);
var handler;
// context
this.objectName = method.sharedClass && method.sharedClass.name ||
method.restClass && method.restClass.name;
this.methodName = method.name;
if (method.fullName) {
type = when + '.' + method.fullName;
} else {
type = when + '.' + this.objectName +
(isStatic ? '.' : '.prototype.') + this.methodName;
}
if (this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
} else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
addToStack(handler);
return execStack();
} else if (handler) {
var l = arguments.length;
var i;
var args = new Array(l - 1);
for (i = 1; i < l; i++) {
args[i - 1] = arguments[i];
}
var listeners = handler.slice();
for (i = 0, l = listeners.length; i < l; i++) {
addToStack(listeners[i]);
}
}
function addToStack(fn) {
stack.push(fn);
}
function execStack(err) {
if (err) return next(err);
var cur = stack.shift();
if (cur) {
try {
var result = cur.call(scope, ctx, execStack, method);
if (result && typeof result.then === 'function') {
result.then(function() { next(); }, next);
}
} catch (err) {
next(err);
}
} else {
next();
}
}
return execStack();
};
// from EventEmitter2
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners = [];
var leaf;
var len;
var branch;
var xTree;
var xxTree;
var isolatedBranch;
var endReached;
var typeLength = type.length;
var currentType = type[i];
var nextType = type[i + 1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
if (handlers) handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
if (handlers) handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(
searchListenerTree(handlers, type, tree[branch], i + 1));
}
}
return listeners;
} else if (currentType === '**') {
endReached = (i + 1 === typeLength || (i + 2 === typeLength && nextType === '*'));
if (endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(
searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if (branch === '*' || branch === '**') {
if (tree[branch]._listeners && !endReached) {
listeners = listeners.concat(
searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(
searchListenerTree(handlers, type, tree[branch], i));
} else if (branch === nextType) {
listeners = listeners.concat(
searchListenerTree(handlers, type, tree[branch], i + 2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(
searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(
searchListenerTree(handlers, type, tree[currentType], i + 1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i + 1);
}
xxTree = tree['**'];
if (xxTree) {
if (i < typeLength) {
if (xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for (branch in xxTree) {
if (branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if (branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i + 2);
} else if (branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i + 1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i + 1);
}
}
}
} else if (xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if (xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
/**
* Invoke the given shared method using the supplied context.
* Execute registered before/after hooks.
* @param {Object} ctx
* @param {Object} method
* @param {function(Error=)} cb
*/
RemoteObjects.prototype.invokeMethodInContext = function(ctx, method, cb) {
var self = this;
var scope = this.getScope(ctx, method);
self.execHooks('before', method, scope, ctx, function(err) {
if (err) return cb(err);
ctx.invoke(scope, method, function(err, result) {
if (err) return cb(err);
ctx.result = result;
self.execHooks('after', method, scope, ctx, function(err) {
if (err) return cb(err);
cb();
});
});
});
};
/**
* Determine what scope object to use when invoking the given remote method in
* the given context.
* @private
*/
RemoteObjects.prototype.getScope = function(ctx, method) {
// Static methods are invoked on the constructor (this = constructor fn)
// Prototype methods are invoked on the instance (this = instance)
return ctx.instance ||
method.ctor ||
method.sharedMethod && method.sharedMethod.ctor;
};
/**
* Define a named type conversion. The conversion is used when a
* `SharedMethod` argument defines a type with the given `name`.
*
* ```js
* remotes.defineType('MyType', function(val, ctx) {
* // use the val and ctx objects to return the concrete value
* return new MyType(val);
* });
* ```
*
* **Note: the alias `remotes.convert()` is deprecated.**
*
* @param {String} name The type name
* @param {Function} converter
*/
RemoteObjects.defineType =
RemoteObjects.convert =
RemoteObjects.prototype.defineType =
RemoteObjects.prototype.convert = function(name, fn) {
Dynamic.define(name, fn);
};
|
function recusar(name)
{
var dados= document.getElementById('tabela'+name);
var ref ='ref'+name;
var href = document.getElementById(ref).getAttribute("href");
var target = document.getElementById(ref).getAttribute("target");
var text = document.getElementById(ref).innerHTML;
$('#tabela3 > tbody:last-child').append('<tr><td>'+'<a href="'+href+'" target="'+target+'">'+text+'</a>'+'</td></tr>');
var row = document.getElementById("tr"+name);
row.parentNode.removeChild(row);
}
function aprovar(name)
{
var dados= document.getElementById('tabela'+name);
var ref ='ref'+name;
//var href = document.getElementById(ref).getAttribute("href");
var target = document.getElementById(ref).getAttribute("target");
var text = document.getElementById(ref).innerHTML;
var href = document.getElementById(ref).getAttribute("href");
$('#tabela2 > tbody:last-child').append('<tr><td>'+'<a href="'+href+'" target="'+target+'">'+text+'</a>'+'</td></tr>');
var row = document.getElementById("tr"+name);
row.parentNode.removeChild(row);
}
|
import React from 'react'
import Moment from 'moment'
import update from 'immutability-helper';
import cloneDeep from "lodash/cloneDeep";
import map from 'lodash/map';
import reduce from 'lodash/reduce';
import ReactMarkdown from 'react-markdown'
import popcount from '@f/popcount';
//this implements a pricing policy for large camps
import FontAwesomeIcon from '@fortawesome/react-fontawesome'
import faTimes from '@fortawesome/fontawesome-free-solid/faTimes'
import {
Row,
Col,
FormGroup,
Input,
Table,
InputGroup,
Button,
Label
} from 'reactstrap';
import {
Item,
Span,
A,
Box
} from 'react-html-email'
let bucketKey = parseInt(Math.random() * 10000);
import moment from 'moment';
export const name = "big";
export const selection = "Big Camp Pricing Policy";
export class Config extends React.Component {
constructor(props) {
super(props);
this.addBucket = this.addBucket.bind(this);
this.deleteBucket = this.deleteBucket.bind(this);
this.updateDate = this.updateDate.bind(this);
this.update = this.update.bind(this);
this.updateAmount = this.updateAmount.bind(this);
}
update(field) {
return e => {
this.props.update(update(this.props.fee, {[field]: {$set: e.target.value}}));
e.preventDefault();
}
}
updateDate(id) {
return e => {
const buckets = cloneDeep(this.props.fee.buckets);
buckets.forEach(b => {
if (b.id === id) b.date = e.target.value;
});
this.props.update(update(this.props.fee, {buckets: {$set: buckets}}));
e.preventDefault();
}
}
updateAmount(id) {
return item => e => {
const buckets = cloneDeep(this.props.fee.buckets);
buckets.forEach(b => {
if (b.id === id) b[item] = e.target.value;
});
this.props.update(update(this.props.fee, {buckets: {$set: buckets}}));
e.preventDefault();
}
}
addBucket(e) {
const buckets = [...(this.props.fee.buckets || [])];
buckets.push({id: "bucket" + bucketKey, date: new Date()});
bucketKey++;
this.props.update(update(this.props.fee, {buckets: {$set: buckets}}));
e.preventDefault();
}
deleteBucket(id) {
return e => {
const buckets = cloneDeep(this.props.fee.buckets).filter(b => b.id !== id);
this.props.update(update(this.props.fee, {buckets: {$set: buckets}}));
e.preventDefault();
}
}
render() {
//Thou shalt not ever use JS numbers for currency...
const dateBuckets = this.props.fee.buckets || [];
const bucketRows = dateBuckets.map(b => {
const feeBoxes = <React.Fragment>
<FormGroup row>
<Label sm={4}>Whole Event:</Label>
<Col sm={8}>
<InputGroup>
<div className="input-group-prepend">
<span className="input-group-text">£</span>
</div>
<Input type="number" className="form-control" value={b.whole}
onChange={this.updateAmount(b.id)('whole')}/>
</InputGroup>
</Col>
</FormGroup>
<p>Partial attendance fee = A + B * (nights attending)</p>
<FormGroup row>
<Label sm={2}>A:</Label>
<Col sm={4}>
<InputGroup>
<div className="input-group-prepend">
<span className="input-group-text">£</span>
</div>
<Input type="number" className="form-control" placeholder="35" value={b.a}
onChange={this.updateAmount(b.id)('a')}/>
</InputGroup>
</Col>
<Label sm={2}>B:</Label>
<Col sm={4}>
<InputGroup>
<div className="input-group-prepend">
<span className="input-group-text">£</span>
</div>
<Input type="number" className="form-control" placeholder="35" value={b.b}
onChange={this.updateAmount(b.id)('b')}/>
</InputGroup>
</Col>
</FormGroup>
</React.Fragment>;
return <tr key={b.id}>
<td><Input type="date" onChange={this.updateDate(b.id)} value={Moment(b.date).format("YYYY-MM-DD")}/>
</td>
<td>{feeBoxes}</td>
<td>
<Button onClick={this.deleteBucket(b.id)} color="warning">
<span style={{color: 'white'}}><FontAwesomeIcon icon={faTimes}/></span>
</Button>
</td>
</tr>
});
return (<React.Fragment>
<Row>
<Col>
<FormGroup>
<Label>Description (Markdown supported):</Label>
<Input type="textarea" name="description" value={this.props.fee.desc}
onChange={this.update('desc')}/>
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<h4>Date buckets</h4>
<Table>
<thead>
<tr>
<th>Up Until Date</th>
<th>Fee</th>
<th></th>
</tr>
</thead>
<tbody>
{bucketRows}
</tbody>
</Table>
<Button onClick={this.addBucket}>Add Bucket</Button>
</Col>
</Row>
<Row>
<Col>
<FormGroup row>
<Label sm={4}>Cancellation Fee:</Label>
<Col sm={2}>
<InputGroup>
<div className="input-group-prepend">
<span className="input-group-text">£</span>
</div>
<Input type="number" className="form-control" placeholder="50"
value={this.props.fee.cancel}
onChange={this.update('cancel')}/>
</InputGroup>
</Col>
</FormGroup>
</Col>
</Row>
</React.Fragment>)
}
}
export class BookingForm extends React.Component {
render() {
//this.props.participants
//this.props.event.startDate
//this.props.feeData.amount
//
const feesOwed = getFeesOwed(this.props.event, this.props.participants, this.props.booking);
const tableLines = feesOwed.map(l => <tr key={l.line}>
<td>{l.line}</td>
<td>£{l.total}</td>
</tr>);
return (<Row>
<Col sm={12}>
<ReactMarkdown escapeHtml={true} source={this.props.event.feeData.desc}/>
</Col>
<Col>
<Table>
<thead></thead>
<tbody>{tableLines}
<tr>
<td><b>Total:</b></td>
<td><b>£{feesOwed.reduce((a, c) => {
return a + c.total
}, 0)}</b></td>
</tr>
</tbody>
</Table>
</Col>
</Row>)
}
}
export class ThanksRow extends React.Component {
render() {
//this.props.participants
//this.props.event.startDate
//this.props.feeData.amount
//
const feesOwed = getFeesOwed(this.props.event, this.props.booking.participants, this.props.booking);
const tableLines = feesOwed.map(l => <tr key={l.line}>
<td>{l.line}</td>
<td>£{l.total}</td>
</tr>);
return (<Row>
<Col>
<Table>
<thead></thead>
<tbody>{tableLines}
<tr>
<td><b>Total:</b></td>
<td><b>£{feesOwed.reduce((a, c) => {
return a + c.total
}, 0)}</b></td>
</tr>
</tbody>
</Table>
</Col>
</Row>)
}
}
export function emailHTML(event, booking) {
const rows = getFeesOwed(event, booking.participants, booking).map((r, i) => <tr key={i}>
<td>{r.line}</td>
<td><b>£{r.total}</b></td>
</tr>);
const total = rows.length > 1 ? <tr>
<td><b>Total</b></td>
<td><b>£{getFeesOwed(event, booking.participants, booking).reduce((a, c) => {
return a + c.total
}, 0)}</b></td>
</tr> : null;
return (<Item>
<p><b>Money:</b></p>
<table>
<tbody>
{rows}
{total}
</tbody>
</table>
</Item>)
}
export function getFeesOwed(event, participants, booking) {
switch (event.partialDates) {
case 'whole':
return owedWholeEvent(event, participants, booking);
case 'presets':
return owedPresetEvent(event, participants, booking);
case 'free':
return owedFreeEvent(event, participants, booking);
default:
return [{line: "Unsupported attendance/fee combo", total: 0}]
}
}
const owedFreeEvent = (event, participants, booking) => {
const wholeMask = 2 ** (Moment(event.endDate).diff(Moment(event.startDate), 'days') + 1) - 1
const sortedBuckets = event.feeData.buckets.sort((a, b) => a.date < b.date ? 1 : a.date === b.date ? 0 : -1);
const filteredParticipants = cloneDeep(participants)
.filter(p => p.name && p.age && (p.days > 0))
.map(p => {
if (!p.updatedAt) p.updatedAt = Moment().format("YYYY-MM-DD");
return p;
});
const rawCosts = filteredParticipants.map(p => sortedBuckets.reduce((a, c) => {
if (new Date(p.updatedAt) < new Date(c.date)) return {
type: p.days === wholeMask ? 'whole' : 'partial',
days: popcount(p.days),
date: c.date,
fee: p.days === wholeMask ? parseInt(c.whole) : parseInt(c.a) + (parseInt(c.b) * (popcount(p.days) - 1))
};
else return a;
}, {}));
const combinedCosts = rawCosts.reduce((a, c) => {
a[c.date] = a[c.date] || {};
a[c.date][c.days] = a[c.date][c.days] || {count: 0, fee: c.fee, type: c.type};
a[c.date][c.days].count++;
return a;
}, {});
const lines = reduce(combinedCosts, (a, c, i) => [...a, ...reduce(c, (a1, c1, i1) => [...a1, {
line: `${c1.count} ${c1.count > 1 ? 'people' : 'person'} booked for ${c1.type === 'whole' ? 'whole event' : (i1 - 1) + ' nights'} before ${Moment(i).format('MMMM Do YYYY')} at £${c1.fee}`,
total: c1.count * c1.fee
}], [])], []);
return lines;
};
const owedWholeEvent = (event, participants, booking) => {
const sortedBuckets = event.feeData.buckets.sort((a, b) => a.date < b.date ? 1 : a.date === b.date ? 0 : -1);
const filteredParticipants = cloneDeep(participants)
.filter(p => p.name && p.age)
.map(p => {
if (!p.updatedAt) p.updatedAt = Moment().format("YYYY-MM-DD");
return p;
});
const rawCosts = filteredParticipants.map(p => sortedBuckets.reduce((a, c) => {
if (new Date(p.updatedAt) < new Date(c.date)) return {
type: isWoodchip(event, p) ? 'woodchip' : 'normal',
date: c.date,
mask: p.days,
amount: c.amount * (isWoodchip(event, p) ? event.feeData.woodchips : 1)
};
else return a;
}, {}));
const combinedCosts = rawCosts.reduce((a, c) => {
if (a[c.date] && a[c.date][c.type]) a[c.date][c.type].count++;
else {
a[c.date] = a[c.date] || {};
a[c.date][c.type] = {count: 1, amount: c.amount};
}
return a;
}, {});
return [...linesWithoutPartial(combinedCosts), ...cancelledFee(event, participants, booking)];
};
const owedPresetEvent = (event, participants, booking) => {
const sortedBuckets = event.feeData.buckets.sort((a, b) => a.date < b.date ? 1 : a.date === b.date ? 0 : -1);
const filteredParticipants = cloneDeep(participants)
.filter(p => p.name && p.age)
.map(p => {
if (!p.updatedAt) p.updatedAt = Moment().format("YYYY-MM-DD");
p.days = event.partialDatesData.find(d => d.mask === p.days);
p.days = p.days ? p.days.name : event.partialDatesData[0].name;
return p;
});
const rawCosts = filteredParticipants.map(p => sortedBuckets.reduce((a, c) => {
if (new Date(p.updatedAt) < new Date(c.date)) return {
type: isWoodchip(event, p) ? 'woodchip' : 'normal',
date: c.date,
mask: p.days,
amount: c.amount[p.days] * (isWoodchip(event, p) ? event.feeData.woodchips : 1)
};
else return a;
}, {}));
const combinedCosts = rawCosts.reduce((a, c) => {
if (a[c.date] && a[c.date][c.mask] && a[c.date][c.mask][c.type]) a[c.date][c.mask][c.type].count++;
else {
a[c.date] = a[c.date] || {};
a[c.date][c.mask] = a[c.date][c.mask] || {};
a[c.date][c.mask][c.type] = {count: 1, amount: c.amount};
}
return a;
}, {});
return [...linesWithPartial(combinedCosts), ...cancelledFee(event, participants, booking)];
};
const linesWithoutPartial = combined => reduce(combined, (a, c, i) => [...a, ...map(c, (l, t) => {
if (t === 'normal') return {
line: `${l.count} ${l.count > 1 ? 'people' : 'person'} booked before ${Moment(i).format('MMMM Do YYYY')} at £${l.amount}`,
total: l.count * l.amount
};
else return {
line: `${l.count} ${l.count > 1 ? 'woodchips' : 'woodchip'} booked before ${Moment(i).format('MMMM Do YYYY')} at £${l.amount}`,
total: l.count * l.amount
}
})], []);
const linesWithPartial = (combined, event) => reduce(combined, (a, c, i) => [...a, ...reduce(c, (a1, c1, i1) => [...a1, ...map(c1, (l, t) => {
if (t === 'normal') return {
line: `${l.count} ${l.count > 1 ? 'people' : 'person'} booked for ${i1} before ${Moment(i).format('MMMM Do YYYY')} at £${l.amount}`,
total: l.count * l.amount
};
else return {
line: `${l.count} ${l.count > 1 ? 'woodchips' : 'woodchip'} booked for ${i1} before ${Moment(i).format('MMMM Do YYYY')} at £${l.amount}`,
total: l.count * l.amount
}
})], [])], []);
const cancelledFee = (event, participants, booking) => {
if (!booking.maxParticipants || booking.maxParticipants <= participants.length || event.feeData.cancel === 0) return [];
return [{
line: `${booking.maxParticipants - participants.length} cancelled bookings at £${event.feeData.cancel}`,
total: (booking.maxParticipants - participants.length) * event.feeData.cancel
}]
};
const isWoodchip = (e, p) => {
return Date.parse(e.startDate) - Date.parse(p.age) < 189216000000
};
|
/*!
* numeral.js language configuration
* language : spanish
* author : Hernan Garcia : https://github.com/hgarcia
*/
(function () {
var language = {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'mm',
billion: 'b',
trillion: 't'
},
ordinal: function (number) {
var b = number % 10;
return (b === 1 || b === 3) ? 'er' :
(b === 2) ? 'do' :
(b === 7 || b === 0) ? 'mo' :
(b === 8) ? 'vo' :
(b === 9) ? 'no' : 'to';
},
currency: {
symbol: '$'
}
};
// Node
if (typeof module !== 'undefined' && module.exports) {
module.exports = language;
}
// Browser
if (typeof window !== 'undefined' && this.numeral && this.numeral.language) {
this.numeral.language('es', language);
}
}());
|
var config = {
start: 'gulp',
jarVersion: "2.3.23"
};
module.exports = config; |
/** @jsx React.DOM */
'use strict';
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var Message = React.createClass({
close: function() {
var node = this.refs.message.getDOMNode();
$(node).fadeOut();
},
render: function() {
return (
<div ref="message" className="ui message {this.props.className}">
<i className="close icon" onClick={this.close}></i>
{this.props.children}
</div>
);
}
});
/****
an Item can be **locked** or **unlocked** depending on some server conditions.
clicking a button sends a POST request. if it's done then it refreshes/rerenders
itself by calling refreshItem.
an initial item list (on ItemList) looks like this:
[
{"id": 1372, "url": "http://127.0.0.1:8000/api/v1/items/1372/", "name": "item 1" , "locked_by": null, "desc": null, "can_be_locked": null, "created": "2014-10-25T15:33:33.625", "modified": "2014-10-25T15:33:33.625"},
{"id": 1364, "url": "http://127.0.0.1:8000/api/v1/items/1364/", "name": "item 2" , "locked_by": null, "desc": null, "can_be_locked": null, "created": "2014-10-25T15:33:32.532", "modified": "2014-10-25T15:33:32.533"},
{"id": 1355, "url": "http://127.0.0.1:8000/api/v1/items/1355/", "name": "item 3" , "locked_by": {"username": "slafs", "first_name": "", "last_name": ""}, "desc": null, "can_be_locked": null, "created": "2014-10-25T15:33:31.298", "modified": "2014-10-25T15:33:31.298"},
...
]
*/
var Item = React.createClass({
itemErrorMsgs: {
forbidden_lock: 'You can\'t lock this item',
forbidden_unlock: 'You can\'t unlock this item'
},
getInitialState: function() {
return {
// if item is locked
locked: this.props.locked_by ? true : false,
// if we are waiting for lock/unlock
is_syncing: false,
// who locked the item
locked_by: this.props.locked_by,
// errors while trying to lock/unlock
errors: []
}
},
refreshItem: function() {
var req = $.get(this.props.url);
req.done(function(data) {
this.setState({
is_syncing: false,
locked_by: data.locked_by,
locked: data.locked_by ? true : false
});
}.bind(this));
req.fail(function (data, status, headers) {
console.error("error refresh " + status);
}.bind(this));
req.always(function () {
this.setState({
is_syncing: false
})
}.bind(this));
},
lockItem: function(command) {
this.setState({is_syncing: true});
var req = $.ajax({
type: 'POST',
url: this.props.url + command + '/',
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
req.done(function(data) {
this.refreshItem();
}.bind(this));
req.fail(function(xhr) {
var errors = this.state.errors;
if (xhr.status == 403) {
var new_errors = errors.concat([this.itemErrorMsgs["forbidden_" + command]]);
this.setState({ errors: new_errors
});
}
this.setState({
is_syncing: false
});
}.bind(this));
return req;
},
render: function() {
var buttonClasses = "ui " + (this.state.locked ? "red" : "primary") + " button" + (this.state.is_syncing ? " disabled": "");
var headerClasses = "ui top attached " + (this.state.locked ? "red" : "green") + " label";
var lock_button = this.state.locked ?
<button onClick={this.lockItem.bind(null, 'unlock')} className={buttonClasses}><i className="icon unlock"></i>Unlock</button>
:
<button onClick={this.lockItem.bind(null, 'lock')} className={buttonClasses}><i className="icon lock"></i>Lock</button>
;
var errorMsgs = this.state.errors.map(function(error, index) {
return (
<Message key={index} className="error">{error}</Message>
);
});
console.log('errors ', errorMsgs);
return (
<div className="four wide column">
<div className="ui segment">
<div className={headerClasses}>{this.props.name}</div>
<br/>
<p> {this.props.desc} </p>
{errorMsgs}
{lock_button}
<br/>
<br/>
<br/>
{this.state.locked ? <div className="ui bottom attached label">Locked by: {this.state.locked_by}</div> : ''}
</div>
</div>
)
}
});
var ItemList = React.createClass({
listenForItemChanges: function() {
var sse = new EventSource('/stream');
var index = null;
sse.addEventListener('itemChange', function (e) {
// e.data has an item identifier
index = this.state.items.findIndex(function(element) {
return (element.id.toString() === e.data);
}.bind(this));
if (index !== null) {
// ??????????????? what now?
console.log("item " + index + " should be rendered");
}
});
return sse;
},
componentDidMount: function() {
this.sse = this.listenForItemChanges();
},
render: function() {
var items = [];
if (!this.props.itemsAreLoading) {
items = this.props.items.map(function(item) {
return (
<Item key={item.id} {...item}/>
)
});
}
return (
<div className="ui page grid">
{this.props.itemsAreLoading ? <p>Loading...</p> : items}
</div>
);
}
});
var DibsApp = React.createClass({
getInitialState: function() {
return {
items: [],
items_are_loading: true
};
},
componentDidMount: function() {
this.req = this.getItems();
},
componentWillUnmount: function () {
this.req.abort();
},
getItems: function() {
var req = $.get(this.props.items_url, this.props.items_url_args);
req.done(function(data) {
this.setState({
items: data
});
}.bind(this));
req.fail(function(data) {
this.setState({
items: []
});
}.bind(this));
req.always(function(data) {
this.setState({
items_are_loading: false
});
}.bind(this));
return req;
},
render: function() {
return (
<ItemList items={this.state.items} itemsAreLoading={this.state.items_are_loading} />
);
}
});
var container = document.getElementById('main_container');
React.render(
<DibsApp items_url="/api/v1/items/" />,
container
);
|
'use strict';
angular.module('core').controller('ReviewController', ['$scope',
function() {
this.review = [];
this.addReview = function(product) {
product.reviews.push(this.review);
this.review = [];
};
}
]); |
import { assign } from 'lodash';
import { toQueryString } from '../helpers';
import googleCSE from '../apis/google_cse';
import httpLoader from './http';
const {
GOOGLE_CSE_KEY,
GOOGLE_CSE_CX,
} = process.env;
export const googleCSELoader = httpLoader(googleCSE);
export default (options = {}) => {
const queryString = toQueryString(assign(options, {
key: GOOGLE_CSE_KEY,
cx: GOOGLE_CSE_CX,
}));
return googleCSELoader.load(`?${queryString}`);
};
|
(function() {
var Parser, X2JS, _, entities, sax;
_ = require('underscore');
sax = require('sax');
X2JS = require('x2js');
entities = require('entities');
Parser = (function() {
function Parser(options) {
if (options == null) {
options = {};
}
this.parser = null;
this.position = [];
this.openTag = null;
this.collect = null;
this.xml = '';
this.collectCurrentNode = false;
this.collectOpenTags = [];
}
Parser.prototype.createStream = function() {
this.parser = sax.createStream(true, {
trim: true,
normalize: true
});
this.parser.on("opentag", (function(_this) {
return function() {
return _this.onOpenTag.apply(_this, arguments);
};
})(this));
this.parser.on("closetag", (function(_this) {
return function() {
return _this.onCloseTag.apply(_this, arguments);
};
})(this));
this.parser.on("text", (function(_this) {
return function() {
return _this.onText.apply(_this, arguments);
};
})(this));
return this.parser;
};
Parser.prototype.onOpenTag = function(tag) {
var collectRules, key, nodeAttrs, nodeName, props, val;
nodeName = tag.name;
nodeAttrs = tag.attributes;
this.position.push(nodeName);
this.openTag = nodeName;
this.collectCurrentNode = false;
collectRules = this.getCollectRules();
for (key in collectRules) {
props = collectRules[key];
if (this.isPositionEq(props.start)) {
this.startCollect(key);
}
}
if (this.collect && this.shallCollect()) {
this.collectCurrentNode = true;
this.xml += "<" + nodeName;
this.collectOpenTags.push(nodeName);
if (nodeAttrs && _.isObject(nodeAttrs)) {
for (key in nodeAttrs) {
val = nodeAttrs[key];
this.xml += " " + key + "=\"" + val + "\"";
}
}
return this.xml += ">";
}
};
Parser.prototype.shallCollect = function() {
var j, key, len, position, props, ref, ref1;
ref = this.getCollectRules();
for (key in ref) {
props = ref[key];
if (this.isPositionEq(props.start)) {
return true;
}
if ('include' in props && _.isArray(props.include)) {
ref1 = props.include;
for (j = 0, len = ref1.length; j < len; j++) {
position = ref1[j];
if (this.isPositionEq(position, 'begin')) {
return true;
}
}
}
}
return false;
};
Parser.prototype.startCollect = function(key) {
if (this.collect) {
this.emitCollected();
}
return this.collect = key;
};
Parser.prototype.emitCollected = function() {
var i, j, ref, x2js;
if (this.collectOpenTags.length > 0) {
for (i = j = ref = this.collectOpenTags.length - 1; ref <= 0 ? j <= 0 : j >= 0; i = ref <= 0 ? ++j : --j) {
this.xml += "</" + this.collectOpenTags[i] + ">";
}
}
x2js = new X2JS();
this.parser.emit(this.collect, x2js.xml2js(this.xml));
this.collectOpenTags = [];
this.collect = null;
return this.xml = '';
};
Parser.prototype.onText = function(text) {
if (this.openTag && this.collectCurrentNode) {
return this.xml += entities.encodeXML(text);
}
};
Parser.prototype.onCloseTag = function(nodeName) {
var rules;
if (this.collect) {
if (this.shallCollect()) {
this.xml += "</" + nodeName + ">";
this.reduceLastPosition(this.collectOpenTags);
}
rules = this.getCollectRules();
if (this.isPositionEq(rules[this.collect].start)) {
this.emitCollected();
}
}
this.reduceLastPosition(this.position);
this.collectCurrentNode = false;
return this.openTag = null;
};
Parser.prototype.reduceLastPosition = function(position) {
var lastIndex;
lastIndex = position.length - 1;
return position.splice(lastIndex, 1);
};
Parser.prototype.getJoinedPosition = function() {
return this.position.join('/');
};
Parser.prototype.isPositionEq = function(position, mode) {
var i, item, j, len;
if (mode == null) {
mode = 'eq';
}
switch (mode) {
case 'eq':
if (position.length !== this.position.length) {
return false;
}
break;
case 'begin':
if (this.position.length < position.length) {
return false;
}
}
for (i = j = 0, len = position.length; j < len; i = ++j) {
item = position[i];
if (item !== this.position[i]) {
return false;
}
}
return true;
};
Parser.prototype.getCollectRules = function() {
return {};
};
return Parser;
})();
module.exports = Parser;
}).call(this);
|
import Ember from 'ember';
export function initialize(/* container, application */) {
['Checkbox', 'Component', 'TextArea', 'TextField'].forEach(function(instanceName) {
Ember[instanceName].reopen({
attributeBindings: ['dataTest:data-test'],
dataTest: null,
});
});
}
export default {
name: 'test-attributes',
initialize: initialize
};
|
$(function() {
var TestModel = Uppercut.Model.derive({
init: function (data) {
this.id = data.id;
this.name = data.name;
}
});
test('Collection.append', function () {
var collection = new Uppercut.Collection();
var a1 = [
new TestModel({ id: 1, name: "model 1" }),
new TestModel({ id: 2, name: "model 2" })
];
collection.append(a1);
equals(collection.models[0].id, 1);
equals(collection.models[1].id, 2);
});
test('Collection.append with model', function () {
var collection = new Uppercut.Collection();
var a1 = [
{ id: 1, name: "model 1" },
{ id: 2, name: "model 2" }
];
collection.append(a1, { model: TestModel });
ok(collection.models[0] instanceof TestModel);
equals(collection.models[0].id, 1);
ok(collection.models[1] instanceof TestModel);
equals(collection.models[1].id, 2);
});
asyncTest('Endpoint.fetch', function () {
var ep = new Uppercut.Endpoint();
var collection = new Uppercut.Collection();
ep.fetch(collection, {
url: '/api/testmodel',
model: TestModel,
success: function(coll) {
equals(coll.models[0].id, 1);
equals(coll.models[0].name, 'name one');
equals(coll.models[1].id, 2);
equals(coll.models[1].name, 'name two');
start();
}
});
});
asyncTest('Endpoint.add', function () {
var ep = new Uppercut.Endpoint();
var collection = new Uppercut.Collection(null, { url: '/api/testmodel' });
var m1 = new TestModel({ name: "new model" });
ep.add(collection, m1, {
success: function(coll, model) {
equals(model.id, 3);
equals(coll.models.length, 1);
start();
}
});
});
asyncTest('Endpoint.fetch and .add', function () {
var ep = new Uppercut.Endpoint();
var collection = new Uppercut.Collection(null, { url: '/api/testmodel', model: TestModel });
ep.fetch(collection, {
success: function(coll) {
equals(coll.models[0].id, 1);
equals(coll.models[0].name, 'name one');
equals(coll.models[1].id, 2);
equals(coll.models[1].name, 'name two');
start();
}
});
var m1 = new TestModel({ name: "new model" });
ep.add(collection, m1, {
success: function(coll, model) {
equals(model.id, 3);
equals(coll.models.length, 3);
start();
}
});
});
asyncTest('Endpoint.add and .fetch', function () {
var ep = new Uppercut.Endpoint();
var collection = new Uppercut.Collection(null, { url: '/api/testmodel', model: TestModel });
var m1 = new TestModel({ name: "new model" });
ep.add(collection, m1, {
success: function(coll, model) {
equals(model.id, 3);
equals(coll.models.length, 1);
start();
}
});
ep.fetch(collection, {
success: function(coll) {
equals(coll.models[0].id, 1);
equals(coll.models[0].name, 'name one');
equals(coll.models[1].id, 2);
equals(coll.models[1].name, 'name two');
start();
}
});
});
asyncTest('Endpoint.add and .fetch with append', function () {
var ep = new Uppercut.Endpoint();
var collection = new Uppercut.Collection(null, { url: '/api/testmodel', model: TestModel });
var m1 = new TestModel({ name: "new model" });
ep.add(collection, m1, {
success: function(coll, model) {
equals(model.id, 3);
equals(coll.models.length, 1);
start();
}
});
ep.fetch(collection, {
append: true,
success: function(coll) {
equals(coll.models[0].id, 3);
equals(coll.models[0].name, 'new model');
equals(coll.models[1].id, 1);
equals(coll.models[1].name, 'name one');
equals(coll.models[2].id, 2);
equals(coll.models[2].name, 'name two');
equals(coll.models.length, 3);
start();
}
});
});
});
|
var PaneShowRequests = function() {
this.$container = $('#PaneShowRequests');
this.apiBridge = new ApiBridge();
this.preview = new UiPreview(); // The preview window object
this.bindEvents();
};
// Draw pane
PaneShowRequests.prototype.draw = function() {
var that = this;
// Remove old content in order to add data to the already existing data and draw the table anew
var $contentTableBody = that.$container.find('tbody');
$contentTableBody.empty();
// Get requests and fill table
this.apiBridge.getRequestList(function (requestList) {
var tableContent = '';
// Draw table content
requestList.forEach(function (entry) {
var rowContent = '';
rowContent += '<td><label>' + entry.request.uri + '</label></td>';
rowContent += '<td><label>' + entry.request.method + '</label></td>';
rowContent += '<td><label>' + entry.statusCode + '</label></td>';
rowContent += '<td><label>' + entry.info + '</label></td>';
rowContent += '<td>';
rowContent += '<button data-request-id="' + entry.id + '" data-action="addToMock">Add</button>';
rowContent += '<button data-request-data="' + encodeURI(entry.response.body) + '" data-action="requestPreview">Preview</button>';
rowContent += '</td>';
tableContent += '<tr>' + rowContent + '</tr>';
});
$contentTableBody.append($(tableContent));
});
};
// Bind buttons to actions
PaneShowRequests.prototype.bindEvents = function() {
var that = this;
this.$container.find('*.PaneShowRequests').off();
// Show preview
this.$container.on('click.PaneShowRequests', 'button[data-action=requestPreview]', function() {
console.log(this);
var requestData = decodeURI($(this).data('request-data'));
that.preview.setContent(requestData).show();
});
// Delete all requests
this.$container.on('click.PaneShowRequests', 'button[data-action=deleteRequests]', function() {
that.apiBridge.clearRequestList(function (response) {
console.log('Cleared requests.', response);
that.draw();
});
});
// Get the request which is associated with the button and fill its data into the create mock pane
this.$container.on('click.PaneShowRequests', 'button[data-action=addToMock]', function() {
that.apiBridge.getRequest($(this).data('request-id'), function (request) {
new UiNavigation().switchPanel('PaneCreateMock', that.transformRequestLogToMockObject(request));
});
});
};
// transform log entry to mock object
PaneShowRequests.prototype.transformRequestLogToMockObject = function(requestLog) {
// Check if the request body is an empty object and call the create mock method with null if it is the case
// to avoid the [Object object] string
var body = "";
if(requestLog.message.request.body && requestLog.message.request.body !== null && Object.keys(requestLog.message.request.body).length > 0) {
body = requestLog.message.request.body;
}
return {
'id': null,
'name': null,
'description': null,
'statusCode': requestLog.message.statusCode,
'request': {
'uri': requestLog.message.request.uri,
'method': requestLog.message.request.method,
'body': body
},
'response': {
'body': requestLog.message.response.body
}
}
};
|
module.exports = getName;
var FUNCTION_NAME = /function\s+([^\s(]+)/;
/**
* Get the name of a function (e.g. constructor)
* @param {Function} f
* @return {String} The function name.
*/
function getName(f)
{
var name = '';
if (f instanceof Function) {
if (f.name) {
return f.name;
}
var match = f.toString().match(FUNCTION_NAME);
if (match) {
name = match[1];
}
} else if (f && f.constructor instanceof Function) {
name = getName(f.constructor);
}
return name;
}
|
var fs = require('fs');
var path = require('path');
var utils = require('../utils');
var runBinary = require('./run-binary');
var mypkg = require(path.join(__dirname, '..', '..', 'package.json'));
module.exports = function(folder, opts) {
return utils.mkdirp(folder)
.then(function(folderPath) {
var folderModules = path.join(folderPath, 'node_modules');
// create an empty node_modules inside the target `folder`, this
// will prevent npm to install the dependencies in any node_modules
// folder but the one inside `folder`.
if (!fs.existsSync(folderModules)) {
fs.mkdirSync(folderModules);
}
console.log('Initializing new DoneJS application at', folderPath);
console.log('Installing donejs-cli');
return installCli(mypkg.version, { cwd: folderPath })
.then(function() {
return runCliInit(folderPath, opts);
});
});
};
// install donejs-cli
function installCli(version, options) {
var pkg = 'donejs-cli@' + utils.versionRange(version);
var npmArgs = [ 'install', pkg, '--no-shrinkwrap', '--loglevel', 'error' ];
return utils.spawn('npm', npmArgs, options);
}
// run donejs-cli init
function runCliInit(folderPath, options) {
var initArgs = ['init'];
// cd into the newly created folder, this way runBinary
// gets the root folder correctly.
process.chdir(folderPath);
if (options.skipInstall) {
initArgs.push('--skip-install');
}
if (options.type) {
initArgs.push('--type', options.type);
}
if (options.yes) {
initArgs.push('--yes');
}
options.cwd = folderPath;
return runBinary(initArgs, options);
}
|
/**
*@Author: chad.ding
*@Date: 2017-06-21 17:40:41
*/
import { GET_DOMAIN_LIST } from '../../consts/action';
export default function domainReducer(state = { domainList: [], fetched: false }, action) {
switch (action.type) {
case GET_DOMAIN_LIST:
return Object.assign({}, state, { domainList: action.data });
default:
return state;
}
}; |
'use strict';
/**
* @ngdoc filter
* @name djangoBulstradApp.filter:propFilter
* @function
* @description
* # propFilter
* Filter in the djangoBulstradApp.
*/
angular.module('djangoBulstradApp')
.filter('propFilter', function () {
return function(items, props) {
var out = [];
if (angular.isArray(items)) {
items.forEach(function(item) {
var itemMatches = false;
var keys = Object.keys(props);
for (var i = 0; i < keys.length; i++) {
var prop = keys[i];
var text = props[prop].toLowerCase();
if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
itemMatches = true;
break;
}
}
if (itemMatches) {
out.push(item);
}
});
} else {
// Let the output be the input untouched
out = items;
}
return out;
};
});
|
process.env.NODE_ENV = 'development';
const WebpackDevServer = require('webpack-dev-server');
const webpack = require('webpack');
const { blue, underline } = require('chalk');
const exceptionFormatter = require('exception-formatter');
const { checkHosts, getAppHosts } = require('../lib/hosts');
const allocatePort = require('../lib/allocatePort');
const openBrowser = require('../lib/openBrowser');
const getSiteForHost = require('../lib/getSiteForHost');
const resolveEnvironment = require('../lib/resolveEnvironment');
const routeMatcher = require('../lib/routeMatcher');
const {
port,
initialPath,
paths,
routes,
sites,
httpsDevServer,
useDevServerMiddleware,
} = require('../context');
const statsConfig = require('../config/webpack/statsConfig');
const createHtmlRenderPlugin = require('../config/webpack/plugins/createHtmlRenderPlugin');
const makeWebpackConfig = require('../config/webpack/webpack.config');
const getCertificate = require('../lib/certificate');
const {
getLanguageFromRoute,
getRouteWithLanguage,
} = require('../lib/language-utils');
const { watchVocabCompile } = require('../lib/runVocab');
const localhost = '0.0.0.0';
const hot = process.env.SKU_HOT !== 'false';
(async () => {
console.log(blue(`sku start`));
await watchVocabCompile();
const environment = resolveEnvironment();
console.log();
const availablePort = await allocatePort({
port: port.client,
host: localhost,
});
const htmlRenderPlugin = createHtmlRenderPlugin();
const [clientWebpackConfig, renderWebpackConfig] = makeWebpackConfig({
port: availablePort,
isDevServer: true,
htmlRenderPlugin,
metrics: true,
hot,
});
const clientCompiler = webpack(clientWebpackConfig);
const renderCompiler = webpack(renderWebpackConfig);
await checkHosts();
renderCompiler.watch({}, (err, stats) => {
if (err) {
console.error(err);
}
console.log(stats.toString(statsConfig));
});
const appHosts = getAppHosts();
const devServerConfig = {
devMiddleware: {
publicPath: paths.publicPath,
},
host: appHosts[0],
allowedHosts: appHosts,
hot,
static: [
{
directory: paths.public,
serveIndex: false,
},
],
client: {
overlay: false,
},
};
if (httpsDevServer) {
const pems = await getCertificate();
devServerConfig.https = {
key: pems,
cert: pems,
};
}
const devServer = new WebpackDevServer(clientCompiler, {
...devServerConfig,
onAfterSetupMiddleware: ({ app }) => {
if (useDevServerMiddleware) {
const devServerMiddleware = require(paths.devServerMiddleware);
if (devServerMiddleware && typeof devServerMiddleware === 'function') {
devServerMiddleware(app);
}
}
app.get('*', (req, res, next) => {
const matchingSiteName = getSiteForHost(req.hostname);
const matchingRoute = routes.find(({ route, siteIndex }) => {
if (
typeof siteIndex === 'number' &&
matchingSiteName !== sites[siteIndex].name
) {
return false;
}
return routeMatcher(route)(req.path);
});
if (!matchingRoute) {
return next();
}
let chosenLanguage;
try {
chosenLanguage = getLanguageFromRoute(req, matchingRoute);
} catch (e) {
return res.status(500).send(
exceptionFormatter(e, {
format: 'html',
inlineStyle: true,
basepath: 'webpack://static/./',
}),
);
}
htmlRenderPlugin
.renderWhenReady({
route: getRouteWithLanguage(matchingRoute.route, chosenLanguage),
routeName: matchingRoute.name,
site: matchingSiteName,
language: chosenLanguage,
environment,
})
.then((html) => res.send(html))
.catch((renderError) => {
res.status(500).send(
exceptionFormatter(renderError, {
format: 'html',
inlineStyle: true,
basepath: 'webpack://static/./',
}),
);
});
});
},
});
devServer.listen(availablePort, localhost, (err) => {
if (err) {
console.log(err);
return;
}
const url = `${httpsDevServer ? 'https' : 'http'}://${
appHosts[0]
}:${availablePort}${initialPath}`;
console.log();
console.log(blue(`Starting the development server on ${underline(url)}`));
console.log();
openBrowser(url);
});
})();
|
/**
* Each instance of events stream subscribes to the /_events/ endpoint of GraphIT
* Filters can be applied to each stream and events are emitted.
* The GraphIT connection does not keep hold of these eventstreams, the consumer does.
* The streams are clever enough to keep track of their position and reconnect (with current
* filters) on the event of connection failure. Should the token expire and connection fail,
* if it is renewed by any other part of the app that shares the `Token` object, it will reconnect
* and continue to emit events.
*/
import qs from 'querystring';
import { w3cwebsocket as WebSocket } from 'websocket';
import { ensureWebSocketsAvailable } from './transport-websocket';
import { channel } from './subscriber-fanout';
import timer from './timer';
import { EVENTS_WS_API_BASE } from './api-version';
const noop = () => {};
const RECONNECT_TIMEOUT = 5e3;
const EVENTS_PROTOCOL = 'events-1.0.0';
export default class EventStream {
static OFFSET_NEWEST_MSG = 'largest';
static OFFSET_OLDEST_MSG = 'smallest';
constructor(
{ endpoint, token },
{
groupId,
offset = EventStream.OFFSET_NEWEST_MSG,
filters = [],
scopeId,
} = {},
emit = noop, // this function is used to hook into all internal events.
) {
ensureWebSocketsAvailable();
this._token = token;
this._endpoint = endpoint
.replace(/^http/, 'ws') //replace http(s) with ws(s)
.replace(/\/?$/, `${EVENTS_WS_API_BASE}/?`); // replace possible trailing slash with api endpoint
const query = {};
if (groupId) {
query.groupId = groupId;
}
if (offset) {
query.offset = offset;
}
if (scopeId) {
query.allscopes = false;
}
this._scopeId = scopeId;
this._endpoint += qs.stringify(query);
this._groupId = groupId;
this._offset = offset;
this._filters = filters.map((content) => ({
'filter-id': content,
'filter-type': 'jfilter',
'filter-content': content,
}));
this._emit = emit;
this._socket = null;
//we don't connect immediately.
// but via a pubsub interface.
this.subscribe = channel((fanout) => {
// connect, then apply filters, then start emitting events.
// we only need the client here.
let reconnectTimeout;
let shouldShutdown = false;
let reconnects = 0; // start at -1 and the first connect
const t = timer({ laps: false });
emit({
name: 'es:power-up',
data: { filters, groupId, offset },
});
const shutdown = () => {
emit({
name: 'es:power-down',
data: t(),
});
clearTimeout(reconnectTimeout);
shouldShutdown = true;
if (this._socket) {
emit({
name: 'es:closing',
data: { time: t(), reconnects },
});
this._socket.close();
}
this._socket = null;
};
const reconnect = () =>
(reconnectTimeout = setTimeout(
() => connect(true),
RECONNECT_TIMEOUT,
));
// this is the loop that gets the connection and uses it, reconnecting
// until it's told to shutdown.
const connect = (isReconnect = false) => {
if (shouldShutdown) {
return;
}
const conntime = timer();
return this._token
.get()
.then((initialToken) => {
emit({
name: 'token:get',
data: { time: conntime(), token: initialToken },
});
if (shouldShutdown) {
return;
}
return this.__createWebSocket(
initialToken,
fanout,
() => {
if (!shouldShutdown) {
reconnect();
}
},
emit,
).then((_socket) => {
this._socket = _socket;
if (isReconnect) {
reconnects++;
}
emit({
name: 'es:connect',
data: { time: conntime(), reconnects },
});
});
})
.catch((e) => {
emit({ name: 'es:error', data: e });
reconnect();
});
};
// start the recurrent connect process
connect();
// return shutdown function.
return shutdown;
});
}
/**
* Register new filter for the same connection.
* All updates for newly registered filters will be passed to subscribed callback.
*
* @param filter - String
*/
register(filter) {
const filterObj = {
'filter-id': filter,
'filter-type': 'jfilter',
'filter-content': filter,
};
this._filters.push(filterObj);
// If there is still no connection it's ok. We'll subscribe latter
if (this._socket) {
this._socket.send(
JSON.stringify({
type: 'register',
args: filterObj,
}),
);
}
// Emit unregister filter just in case
this._emit({
name: 'es:register-filter',
data: { filter, offset: this._offset, groupId: this._groupId },
});
}
/**
* Unregisters existing filter by sending request to server with type unregister.
* Stop getting events for this filter
*
* @param filterId - String
*/
unregister(filterId) {
this._filters = this._filters.filter(
(filter) => filter['filter-id'] !== filterId,
);
//If there is still no connection it's ok. We won't subscribe
if (this._socket) {
this._socket.send(
JSON.stringify({
type: 'unregister',
args: {
'filter-id': filterId,
},
}),
);
}
// Emit unregister filter just in case
this._emit({
name: 'es:unregister-filter',
data: { 'filter-id': filterId },
});
}
/**
* Creates a WebSocket connection, with the initial token.
*
* Similiar logic to the websocket-transport
*
* confusingly, "fanout" is to fanout events from the eventstream
* and "emit" is the pubsub emitter passes to all hiro-graph-client components for
* introspection
*/
__createWebSocket(initialToken, fanout, onClose, emit) {
//we do all this in a promise, so the result is shared between
//all requests that come in during connection.
const t = timer();
return new Promise((resolve, reject) => {
const ws = new WebSocket(this._endpoint, [
EVENTS_PROTOCOL,
`token-${initialToken}`,
]);
//this keeps track of whether we have resolved yet.
let hasResolved = false;
//when the connection closes we need to tidy up.
ws.onclose = () => {
emit({ name: 'es:sock-close', data: t() });
//if we haven't resolved yet, then this is an *immediate* close by GraphIT.
//therefore we probably have an invalid token, and we should definitely reject.
if (!hasResolved) {
hasResolved = true;
this._token.invalidate();
emit({ name: 'es:invalidate', data: null });
reject();
} else {
onClose();
}
};
//on connection error, we almost certainly close after this anyway, so just
//log the error
ws.onerror = (err) => {
emit({ name: 'es:sock-error', data: err });
};
//how to handle inbound messages, find the inflight it matches and return
ws.onmessage = (msg) => {
//we can only handle string messages
if (typeof msg.data !== 'string') {
//we don't handle messages like this.
emit({ name: 'es:bad-message', data: msg.data });
return;
}
//try and parse as JSON
let object;
try {
object = JSON.parse(msg.data);
} catch (e) {
emit({ name: 'es:bad-message', data: msg.data });
return;
}
emit({ name: 'es:message', data: object });
//this event should have properties:
//
// id: the id of the object entity (who it was done to)
// identity: the id of the subject entity (who did it)
// type: what was done (CREATE, UPDATE, ...)
// timestamp: hammertime (milliseconds since unix epoch)
// nanotime: ??? (does not appear to be nanoseconds since unix epoch)
// body: the full content of the object entity
fanout(object);
};
//now the socket is opened we can resolve our promise with a client API
ws.onopen = () => {
emit({
name: 'es:sock-open',
data: { time: t(), protocol: ws.protocol },
});
//actually if we send a bad token, we need to wait for a moment before resolving.
//otherwise, the connection will shut straightaway.
//testing shows this usually takes about 10ms, but the largest time I saw was
//32ms. We use 100ms just in case. This makes the initial connection slower, but
//is a one off cost and not a problem with the events stream. Also, we might as well
//try and apply the filters immediately.
// now apply all filters.
this._filters.forEach((filter) =>
ws.send(
JSON.stringify({
type: 'register',
args: filter,
}),
),
);
if (this._scopeId) {
if (Array.isArray(this._scopeId)) {
this._scopeId.forEach((id) =>
ws.send(
JSON.stringify({
type: 'subscribe',
id,
}),
),
);
} else {
ws.send(
JSON.stringify({
type: 'subscribe',
id: this._scopeId,
}),
);
}
}
setTimeout(() => {
if (hasResolved) {
//crap, we did fail.
return;
}
//now mark this as resolving so we don't invalidate our token accidentally.
hasResolved = true;
resolve(ws);
}, 100);
};
});
}
}
|
var expect = require('chai').expect;
var BackChannel = require('../../dist-lib/backchannel');
var EventEmitter = require('events').EventEmitter;
var sinon = require('sinon');
var common = require('../../dist-lib/common');
var ObjectId = require('mongoose').Types.ObjectId;
describe('BackChannel', function() {
describe('#prepareJob()', function() {
var bc = null;
var emitter = null;
var ws = null;
var Project = null;
var Job = null;
var Runner = require('strider-simple-runner').Runner;
before(function(done) {
var provider = require('../fixtures/issue_477/common.extensions.provider.json');
provider.github.getFile = sinon
.stub()
.yields(new Error('no strider.json'), null);
common.extensions = { provider: provider, runner: {} };
var models = require('../../dist-lib/models');
Project = models.Project;
Job = models.Job;
var User = models.User;
var project = require('../fixtures/issue_477/realworld_project.json');
project.creator = new User(project.creator);
project.branch = sinon.stub().returns({ runner: { id: 'runner-id' } });
sinon.stub(Project, 'findOne').returns({
populate: sinon.stub().returns({
exec: sinon.stub().yields(null, project)
})
});
sinon
.stub(Job, 'create')
.yields(null, new Job(require('../fixtures/issue_477/mjob.json')));
var job = require('../fixtures/issue_477/realworld_job.json');
sinon.stub(BackChannel.prototype, 'newJob');
emitter = new EventEmitter();
bc = new BackChannel(emitter, ws);
emitter.emit('job.prepare', job);
done();
});
after(function() {
Project.findOne.restore();
Job.create.restore();
BackChannel.prototype.newJob.restore();
});
it('calls #newJob() only once', function() {
expect(BackChannel.prototype.newJob.callCount).to.eq(1);
});
it('sends the correct arguments to #newJob()', function() {
var call = BackChannel.prototype.newJob.getCall(0);
var job = call.args[0];
var config = call.args[1];
expect(Object.keys(job)).to.have.length(13);
expect(config).to.deep.eq({ runner: { id: 'runner-id' } });
});
});
});
|
import Icon from '../../components/Icon.vue'
Icon.register({
'brands/stackpath': {
width: 448,
height: 512,
paths: [
{
d: 'M244.6 232.4c0 8.5-4.3 20.5-21.3 20.5h-19.6v-41.5h19.6c17.1 0 21.3 12.4 21.3 21zM448 32v448h-448v-448h448zM151.3 287.8c0-21.2-12.1-34.5-46.7-44.8-20.6-7.4-26-10.9-26-18.6 0-7.7 7-14.6 20.4-14.6 14.1 0 20.8 8.5 20.8 18.3h30.7l0.2-0.6c0.5-19.6-15.1-41.7-51.1-41.7-23.4 0-52.5 10.8-52.5 38.3 0 19.4 9.3 31.3 50.7 44.4 17.3 6.2 21.9 10.4 21.9 19.5 0 15.2-19.1 14.2-19.5 14.2-20.4 0-25.6-9.1-25.6-21.9h-30.8l-0.2 0.6c-0.7 31.3 28.4 45.2 56.6 45.2 30 0 51.1-13.5 51.1-38.3zM276.7 232.2c0-25.3-18.4-45.5-53.4-45.5h-51.8v138.2h32.2v-47.4h19.6c30.3 0 53.4-16 53.4-45.4zM297.9 325l49.1-138.2h-31.1l-47.9 138.2h29.9zM404.5 186.8h-31.1l-47.9 138.2h29.9z'
}
]
}
})
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'specialchar', 'ku', {
options: 'هەڵبژاردەی نووسەی تایبەتی',
title: 'هەڵبژاردنی نووسەی تایبەتی',
toolbar: 'دانانی نووسەی تایبەتی'
} );
|
/** @constructor */
ScalaJS.c.scala_scalajs_js_Dynamic$ = (function() {
ScalaJS.c.java_lang_Object.call(this)
});
ScalaJS.c.scala_scalajs_js_Dynamic$.prototype = new ScalaJS.inheritable.java_lang_Object();
ScalaJS.c.scala_scalajs_js_Dynamic$.prototype.constructor = ScalaJS.c.scala_scalajs_js_Dynamic$;
ScalaJS.c.scala_scalajs_js_Dynamic$.prototype.newInstance__Lscala_scalajs_js_Dynamic__Lscala_collection_Seq__ = (function(clazz, args) {
return this.newInstance__Lscala_scalajs_js_Dynamic__Lscala_collection_Seq__Lscala_scalajs_js_Dynamic(clazz, args)
});
ScalaJS.c.scala_scalajs_js_Dynamic$.prototype.global__ = (function() {
return this.global__Lscala_scalajs_js_Dynamic()
});
/** @constructor */
ScalaJS.inheritable.scala_scalajs_js_Dynamic$ = (function() {
/*<skip>*/
});
ScalaJS.inheritable.scala_scalajs_js_Dynamic$.prototype = ScalaJS.c.scala_scalajs_js_Dynamic$.prototype;
ScalaJS.is.scala_scalajs_js_Dynamic$ = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_scalajs_js_Dynamic$)))
});
ScalaJS.as.scala_scalajs_js_Dynamic$ = (function(obj) {
if ((ScalaJS.is.scala_scalajs_js_Dynamic$(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.scalajs.js.Dynamic")
}
});
ScalaJS.isArrayOf.scala_scalajs_js_Dynamic$ = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_scalajs_js_Dynamic$)))
});
ScalaJS.asArrayOf.scala_scalajs_js_Dynamic$ = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_scalajs_js_Dynamic$(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.scalajs.js.Dynamic;", depth)
}
});
ScalaJS.data.scala_scalajs_js_Dynamic$ = new ScalaJS.ClassTypeData({
scala_scalajs_js_Dynamic$: 0
}, false, "scala.scalajs.js.Dynamic$", ScalaJS.data.java_lang_Object, {
scala_scalajs_js_Dynamic$: 1,
java_lang_Object: 1
});
ScalaJS.c.scala_scalajs_js_Dynamic$.prototype.$classData = ScalaJS.data.scala_scalajs_js_Dynamic$;
ScalaJS.moduleInstances.scala_scalajs_js_Dynamic = undefined;
ScalaJS.modules.scala_scalajs_js_Dynamic = (function() {
if ((!ScalaJS.moduleInstances.scala_scalajs_js_Dynamic)) {
ScalaJS.moduleInstances.scala_scalajs_js_Dynamic = new ScalaJS.c.scala_scalajs_js_Dynamic$().init___()
};
return ScalaJS.moduleInstances.scala_scalajs_js_Dynamic
});
//@ sourceMappingURL=Dynamic$.js.map
|
var assert = require("assert");
var path = require('path');
var fis = require('fis');
var fs = require('fs');
var path = require('path');
var tmp = require('tmp');
// 标记是否要输出 coverage
var coverage = !!process.env.istanbul;
// 因为 istanbul 不支持 chid_progress
// 所以现在的处理办法是正如这里面说的:
// https://github.com/gotwarlost/istanbul/issues/115
//
// Yes, you will need to call the equivalent of
// `istanbul cover --dir <generated-dir-name> <js-program>` every time
// you need to run tests in a child process.
//
// Then you can use istanbul report to collect information from all these
// directories and spit out a single coverage report from it.
var Fis = (function() {
var spawn = require('child_process').spawn;
var fisbin = path.resolve('node_modules/fis/bin/fis');
var slice = [].slice;
var preArgs = [fisbin, 'release', '-c'];
var command = coverage ? 'istanbul' : 'node';
var reportDirs = [];
var count = 0;
if (coverage) {
preArgs.splice(0, 0, '--report', 'none', '--');
}
return {
run: function() {
var args = slice.call(arguments);
var argsPre = preArgs.concat();
var cb, child, reportDir;
if (args.length && typeof args[args.length - 1] === 'function') {
cb = args.pop();
}
tmp.dir(function(err, path) {
if (err) throw err;
argsPre.push('-cd', path);
if (coverage) {
reportDir = 'coverage/sub' + count++;
argsPre.splice(0, 0, 'cover', '--dir', reportDir);
reportDirs.push(reportDir);
}
child = spawn(command, argsPre.concat(args));
// child.stdout.pipe(process.stdout);
// child.stderr.pipe(process.stderr);
child.on('close', function() {
cb && cb(path);
});
});
},
finish: function(cb) {
if (!coverage) {
cb && cb();
return;
}
var args = ['report', process.env.istanbul_report || 'html'];
var child;
// reportDirs.forEach(function(val) {
// args.splice(1, 0, '--root', val);
// });
args.splice(1, 0, '--root', 'coverage');
Object.keys(process.env).forEach(function(key) {
var m = /^istanbul_(.*)$/.exec(key);
var k, v;
if (!m || m[1] === 'report') {
return;
}
k = m[1];
v = process.env[key];
args.splice(1, 0, '--' + k, v ? v : undefined);
});
// console.log(args.join(' '));
child = spawn('istanbul', args);
// child.stdout.pipe(process.stdout);
// child.stderr.pipe(process.stderr);
child.on('exit', function() {
cb && cb();
});
}
}
})();
function resolve(name) {
return path.join(__dirname, name);
}
function listEntries(entry, prefix) {
var list = [];
var stat = fs.statSync(entry);
prefix = prefix || '';
if (stat.isDirectory()) {
fs.readdirSync(entry).forEach(function(child) {
if (child[0] != '.') {
var stat = fs.statSync(path.join(entry, child));
if (stat && stat.isDirectory()) {
list = list.concat(listEntries(path.join(entry, child), prefix + child + "/" ));
} else {
list.push(prefix + child);
}
}
});
}
return list.sort();
}
function compareFolder(src, dst, iterator) {
var srcFiles = listEntries(src);
var dstFiles = listEntries(dst);
srcFiles.forEach(function(file) {
var exist = !!~dstFiles.indexOf(file);
if (exist) {
iterator(file, fis.util.read(path.join(src, file)), fis.util.read(path.join(dst, file)));
} else {
iterator(file);
}
});
}
// ------------------------------------------------------
// ----- Let's get started.
describe('Tests', function() {
it('amd wrap', function(done) {
Fis.run('-r', resolve('fixtures/basic'), '-f', resolve('fixtures/basic/fis-conf.js'), function(path) {
// console.log(path);
compareFolder(resolve('expected/basic'), path, function(name, src, dst) {
if (typeof src === 'undefined') {
assert.ok(false, name + ' file not match');
} else {
assert.ok(src === dst, name + ' content not match');
}
});
fis.util.del(path);
done();
});
});
});
// 收尾输出 coverage
describe('finish', function() {
it('ignore this', function(callback) {
Fis.finish(callback);
});
})
|
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
nums.splice(nums.length - k, k).reverse().forEach(function(val) {nums.unshift(val)});
};
|
'use strict';
module.exports = {
conditions: [''],
name: 'FunctionStatementList',
rules: ['StatementList_Return'],
handlers: ['$$ = $1'],
subRules: [require('./StatementList_Return')]
}; |
(function() {
var IABVerifier,
crypto = require('crypto'),
algorithm = 'RSA-SHA1';
IABVerifier = (function() {
function IABVerifier(publicKeyString) {
this.publicKeyString = generateFormattedPublickey(publicKeyString)
};
// gotta give credit to nothing2lose for this function
function generateFormattedPublickey(publicKeyStr) {
var KEY_PREFIX, KEY_SUFFIX, chunkSize, chunks, str;
KEY_PREFIX = "-----BEGIN PUBLIC KEY-----\n";
KEY_SUFFIX = '\n-----END PUBLIC KEY-----';
str = publicKeyStr;
chunks = [];
chunkSize = 64;
while (str) {
if (str.length < chunkSize) {
chunks.push(str);
break;
} else {
chunks.push(str.substr(0, chunkSize));
str = str.substr(chunkSize);
}
}
str = chunks.join("\n");
str = KEY_PREFIX + str + KEY_SUFFIX;
return str;
};
IABVerifier.prototype.verifyReceipt = function(signedData, signature) {
var verifier;
verifier = crypto.createVerify(algorithm);
verifier.update(signedData);
return verifier.verify(this.publicKeyString, signature, 'base64');
};
return IABVerifier;
})();
module.exports = IABVerifier;
}).call(this);
|
var passify = require('../index');
var myPassword = passify.create();
passify.hash(myPassword, function(err, hash) {
console.log(hash);
});
|
/**
* ueditor完整配置项
* 可以在这里配置整个编辑器的特性
*/
/**************************提示********************************
* 所有被注释的配置项均为UEditor默认值。
* 修改默认配置请首先确保已经完全明确该参数的真实用途。
* 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。
* 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。
**************************提示********************************/
(function () {
/**
* 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。
* 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。
* "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/ueditor/"这样的路径。
* 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。
* 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。
* window.UEDITOR_HOME_URL = "/xxxx/xxxx/";
*/
var URL = window.UEDITOR_HOME_URL || getUEBasePath();
/**
* 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
*/
window.UEDITOR_CONFIG = {
//为编辑器实例添加一个路径,这个不能被注释
UEDITOR_HOME_URL: URL
// 服务器统一请求接口路径
, serverUrl: URL
//工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的从新定义
, toolbars: [[
'fullscreen', 'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
'print', 'preview', 'searchreplace', 'help', 'drafts'
]]
//当鼠标放在工具栏上时显示的tooltip提示,留空支持自动多语言配置,否则以配置值为准
//,labelMap:{
// 'anchor':'', 'undo':''
//}
//语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件:
//lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase()
//,lang:"zh-cn"
//,langPath:URL +"lang/"
//主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件:
//现有如下皮肤:default
//,theme:'default'
//,themePath:URL +"themes/"
//,zIndex : 900 //编辑器层级的基数,默认是900
//针对getAllHtml方法,会在对应的head标签中增加该编码设置。
//,charset:"utf-8"
//若实例化编辑器的页面手动修改的domain,此处需要设置为true
//,customDomain:false
//常用配置项目
//,isShow : true //默认显示编辑器
//,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值
//,initialContent:'欢迎使用ueditor!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子
//,autoClearinitialContent:true //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了
//,focus:false //初始化时,是否让编辑器获得焦点true或false
//如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感
//,initialStyle:'p{line-height:1em}'//编辑器层级的基数,可以用来改变字体等
//,iframeCssUrl: URL + '/themes/iframe.css' //给编辑器内部引入一个css文件
//indentValue
//首行缩进距离,默认是2em
//,indentValue:'2em'
//,initialFrameWidth:1000 //初始化编辑器宽度,默认1000
//,initialFrameHeight:320 //初始化编辑器高度,默认320
//,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false
//,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况)
//启用自动保存
//,enableAutoSave: true
//自动保存间隔时间, 单位ms
//,saveInterval: 500
//,fullscreen : false //是否开启初始化时即全屏,默认关闭
//,imagePopup:true //图片操作的浮层开关,默认打开
//,autoSyncData:true //自动同步编辑器要提交的数据
//,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹
//粘贴只保留标签,去除标签所有属性
//,retainOnlyLabelPasted: false
//,pasteplain:false //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴
//纯文本粘贴模式下的过滤规则
//'filterTxtRules' : function(){
// function transP(node){
// node.tagName = 'p';
// node.setStyle();
// }
// return {
// //直接删除及其字节点内容
// '-' : 'script style object iframe embed input select',
// 'p': {$:{}},
// 'br':{$:{}},
// 'div':{'$':{}},
// 'li':{'$':{}},
// 'caption':transP,
// 'th':transP,
// 'tr':transP,
// 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
// 'td':function(node){
// //没有内容的td直接删掉
// var txt = !!node.innerText();
// if(txt){
// node.parentNode.insertAfter(UE.uNode.createText(' '),node);
// }
// node.parentNode.removeChild(node,node.innerText())
// }
// }
//}()
//,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串
//insertorderedlist
//有序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准
//,'insertorderedlist':{
// //自定的样式
// 'num':'1,2,3...',
// 'num1':'1),2),3)...',
// 'num2':'(1),(2),(3)...',
// 'cn':'一,二,三....',
// 'cn1':'一),二),三)....',
// 'cn2':'(一),(二),(三)....',
// //系统自带
// 'decimal' : '' , //'1,2,3...'
// 'lower-alpha' : '' , // 'a,b,c...'
// 'lower-roman' : '' , //'i,ii,iii...'
// 'upper-alpha' : '' , lang //'A,B,C'
// 'upper-roman' : '' //'I,II,III...'
//}
//insertunorderedlist
//无序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准
//,insertunorderedlist : { //自定的样式
// 'dash' :'— 破折号', //-破折号
// 'dot':' 。 小圆圈', //系统自带
// 'circle' : '', // '○ 小圆圈'
// 'disc' : '', // '● 小圆点'
// 'square' : '' //'■ 小方块'
//}
//,listDefaultPaddingLeft : '30'//默认的左边缩进的基数倍
//,listiconpath : 'http://bs.baidu.com/listicon/'//自定义标号的路径
//,maxListLevel : 3 //限制可以tab的级数, 设置-1为不限制
//,autoTransWordToList:false //禁止word中粘贴进来的列表自动变成列表标签
//fontfamily
//字体设置 label留空支持多语言自动切换,若配置,则以配置值为准
//,'fontfamily':[
// { label:'',name:'songti',val:'宋体,SimSun'},
// { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'},
// { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'},
// { label:'',name:'heiti',val:'黑体, SimHei'},
// { label:'',name:'lishu',val:'隶书, SimLi'},
// { label:'',name:'andaleMono',val:'andale mono'},
// { label:'',name:'arial',val:'arial, helvetica,sans-serif'},
// { label:'',name:'arialBlack',val:'arial black,avant garde'},
// { label:'',name:'comicSansMs',val:'comic sans ms'},
// { label:'',name:'impact',val:'impact,chicago'},
// { label:'',name:'timesNewRoman',val:'times new roman'}
//]
//fontsize
//字号
//,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36]
//paragraph
//段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准
//,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''}
//rowspacingtop
//段间距 值和显示的名字相同
//,'rowspacingtop':['5', '10', '15', '20', '25']
//rowspacingBottom
//段间距 值和显示的名字相同
//,'rowspacingbottom':['5', '10', '15', '20', '25']
//lineheight
//行内间距 值和显示的名字相同
//,'lineheight':['1', '1.5','1.75','2', '3', '4', '5']
//customstyle
//自定义样式,不支持国际化,此处配置值即可最后显示值
//block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置
//尽量使用一些常用的标签
//参数说明
//tag 使用的标签名字
//label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同,
//style 添加的样式
//每一个对象就是一个自定义的样式
//,'customstyle':[
// {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'},
// {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'},
// {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'},
// {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'}
//]
//打开右键菜单功能
//,enableContextMenu: true
//右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准
//,contextMenu:[
// {
// label:'', //显示的名称
// cmdName:'selectall',//执行的command命令,当点击这个右键菜单时
// //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName
// exec:function () {
// //this是当前编辑器的实例
// //this.ui._dialogs['inserttableDialog'].open();
// }
// }
//]
//快捷菜单
//,shortcutMenu:["fontfamily", "fontsize", "bold", "italic", "underline", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist"]
//elementPathEnabled
//是否启用元素路径,默认是显示
//,elementPathEnabled : true
//wordCount
//,wordCount:true //是否开启字数统计
//,maximumWords:10000 //允许的最大字符数
//字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示
//,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符
//超出字数限制提示 留空支持多语言自动切换,否则按此配置显示
//,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span>
//tab
//点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位
//,tabSize:4
//,tabNode:' '
//removeFormat
//清除格式时可以删除的标签和属性
//removeForamtTags标签
//,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var'
//removeFormatAttributes属性
//,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign'
//undo
//可以最多回退的次数,默认20
//,maxUndoCount:20
//当输入的字符数超过该值时,保存一次现场
//,maxInputCount:1
//autoHeightEnabled
// 是否自动长高,默认true
//,autoHeightEnabled:true
//scaleEnabled
//是否可以拉伸长高,默认true(当开启时,自动长高失效)
//,scaleEnabled:false
//,minFrameWidth:800 //编辑器拖动时最小宽度,默认800
//,minFrameHeight:220 //编辑器拖动时最小高度,默认220
//autoFloatEnabled
//是否保持toolbar的位置不动,默认true
//,autoFloatEnabled:true
//浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面
//,topOffset:30
//编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效)
//,toolbarTopOffset:400
//pageBreakTag
//分页标识符,默认是_ueditor_page_break_tag_
//,pageBreakTag:'_ueditor_page_break_tag_'
//autotypeset
//自动排版参数
//,autotypeset: {
// mergeEmptyline: true, //合并空行
// removeClass: true, //去掉冗余的class
// removeEmptyline: false, //去掉空行
// textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
// imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
// pasteFilter: false, //根据规则过滤没事粘贴进来的内容
// clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
// clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
// removeEmptyNode: false, // 去掉空节点
// //可以去掉的标签
// removeTagNames: {标签名字:1},
// indent: false, // 行首缩进
// indentValue : '2em', //行首缩进的大小
// bdc2sb: false,
// tobdc: false
//}
//tableDragable
//表格是否可以拖拽
//,tableDragable: true
//,disabledTableInTable:true //禁止表格嵌套
//sourceEditor
//源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror
//注意默认codemirror只能在ie8+和非ie中使用
//,sourceEditor:"codemirror"
//如果sourceEditor是codemirror,还用配置一下两个参数
//codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js"
//,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js"
//codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css"
//,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css"
//编辑器初始化完成后是否进入源码模式,默认为否。
//,sourceEditorFirst:false
//iframeUrlMap
//dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径
//,iframeUrlMap:{
// 'anchor':'~/dialogs/anchor/anchor.html',
//}
//webAppKey 百度应用的APIkey,每个站长必须首先去百度官网注册一个key后方能正常使用app功能,注册介绍,http://app.baidu.com/static/cms/getapikey.html
//, webAppKey: ""
};
function getUEBasePath(docUrl, confUrl) {
return getBasePath(docUrl || self.document.URL || self.location.href, confUrl || getConfigFilePath());
}
function getConfigFilePath() {
var configPath = document.getElementsByTagName('script');
return configPath[ configPath.length - 1 ].src;
}
function getBasePath(docUrl, confUrl) {
var basePath = confUrl;
if (/^(\/|\\\\)/.test(confUrl)) {
basePath = /^.+?\w(\/|\\\\)/.exec(docUrl)[0] + confUrl.replace(/^(\/|\\\\)/, '');
} else if (!/^[a-z]+:/i.test(confUrl)) {
docUrl = docUrl.split("#")[0].split("?")[0].replace(/[^\\\/]+$/, '');
basePath = docUrl + "" + confUrl;
}
return optimizationPath(basePath);
}
function optimizationPath(path) {
var protocol = /^[a-z]+:\/\//.exec(path)[ 0 ],
tmp = null,
res = [];
path = path.replace(protocol, "").split("?")[0].split("#")[0];
path = path.replace(/\\/g, '/').split(/\//);
path[ path.length - 1 ] = "";
while (path.length) {
if (( tmp = path.shift() ) === "..") {
res.pop();
} else if (tmp !== ".") {
res.push(tmp);
}
}
return protocol + res.join("/");
}
window.UE = {
getUEBasePath: getUEBasePath
};
})();
|
import * as mathUtil from './math/math_util.js';
import { Rect } from './math/rect.js';
import { Vec2 } from './math/vec2.js';
/**
* Class for rendering and interacting with UI elements on a canvas.
* @constructor
*/
const CanvasUI = function(options) {
this.clear();
};
/**
* Update UI element state and animations.
* @param {number} deltaTime Time passed since the last update in seconds.
*/
CanvasUI.prototype.update = function(deltaTime) {
for (var i = 0; i < this.uiElements.length; ++i) {
this.uiElements[i].update(deltaTime);
}
};
/**
* Render the UI.
* @param {CanvasRenderingContext2D} ctx The canvas rendering context to use.
* @param {function=} matchFunc Set this to only render the matching elements. By default all elements are rendered.
*/
CanvasUI.prototype.render = function(ctx, matchFunc) {
var activeCursors = this._getActiveCursors();
var draggedElements = [];
var i;
for (i = 0; i < this.uiElements.length; ++i) {
if (matchFunc === undefined || matchFunc(this.uiElements[i])) {
if (!this.uiElements[i].dragged) {
this.uiElements[i].render(ctx, activeCursors);
} else {
draggedElements.push(this.uiElements[i]);
}
}
}
for (i = 0; i < draggedElements.length; ++i) {
draggedElements[i].render(ctx, activeCursors);
}
};
/**
* @return {Array.<Object>} Active cursors.
* @protected
*/
CanvasUI.prototype._getActiveCursors = function() {
var activeCursors = [];
for (var i = 0; i < this.cursors.length; ++i) {
if (this.cursors[i].active) {
activeCursors.push(this.cursors[i]);
}
}
return activeCursors;
};
/**
* Clear the UI from all elements.
*/
CanvasUI.prototype.clear = function() {
this.uiElements = [];
this.cursors = [];
};
CanvasUI.prototype.addElement = function(element) {
this.uiElements.push(element);
};
/**
* @param {Object} cursor Cursor with the following keys:
* currentPosition: an x,y vector indicating the last known position of the pointer.
* index: numerical index identifying the pointer.
* @return {boolean} True if an element was pressed.
*/
CanvasUI.prototype.canvasPress = function(cursor) {
while (this.cursors.length <= cursor.index) {
this.cursors.push(new CanvasUICursor(this));
}
this.cursors[cursor.index].active = true;
return this.cursors[cursor.index].press(cursor.currentPosition);
};
/**
* @param {Object} cursor Cursor with the following keys:
* index: numerical index identifying the pointer.
* @param {boolean} makeInactive Set to true to make the cursor inactive at the same time. Useful for touch cursors.
*/
CanvasUI.prototype.canvasRelease = function(cursor, makeInactive) {
while (this.cursors.length <= cursor.index) {
this.cursors.push(new CanvasUICursor(this));
}
this.cursors[cursor.index].release();
this.cursors[cursor.index].active = !makeInactive;
};
/**
* @param {Object} cursor Cursor with the following keys:
* currentPosition: an x,y vector indicating the last known position of the pointer.
* index: numerical index identifying the pointer.
*/
CanvasUI.prototype.canvasMove = function(cursor) {
while (this.cursors.length <= cursor.index) {
this.cursors.push(new CanvasUICursor(this));
}
this.cursors[cursor.index].active = true;
this.cursors[cursor.index].setPosition(cursor.currentPosition);
};
/**
* A single cursor.
* @param {CanvasUI} ui UI this cursor belongs to.
* @constructor
*/
const CanvasUICursor = function(ui) {
this.ui = ui;
this.active = false;
this.x = -Infinity;
this.y = -Infinity;
this.downButton = null;
this.dragging = false;
};
/**
* Set the cursor position.
* @param {Vec2} vec New position to set. Relative to the canvas coordinate space.
*/
CanvasUICursor.prototype.setPosition = function(pos) {
this.x = pos.x;
this.y = pos.y;
if (this.dragging) {
this.downButton.draggedX = this.downButton.centerX + (this.x - this.dragStartX);
this.downButton.draggedY = this.downButton.centerY + (this.y - this.dragStartY);
} else if (this.downButton) {
var hit = this.downButton.hitTest(this.x, this.y);
if (this.downButton.moveWhenDownCallback !== null) {
this.downButton.moveWhenDownCallback(this.downButton, pos);
}
if (!hit) {
this.downButton.release(false);
} else {
this.downButton.down();
}
}
};
/**
* Handle a mouse / touch down event.
* @param {Object|Vec2} pos New position to set. Needs to have x and y coordinates. Relative to the canvas coordinate
* space.
* @return {boolean} True if an element was pressed.
*/
CanvasUICursor.prototype.press = function(pos) {
this.setPosition(pos);
var uiElements = this.ui.uiElements;
for (var i = 0; i < uiElements.length; ++i) {
if (uiElements[i].active && !uiElements[i].locked &&
uiElements[i].hitTest(this.x, this.y) && !uiElements[i].isDown)
{
this.downButton = uiElements[i];
this.downButton.down();
if (uiElements[i].draggable && !uiElements[i].dragged) {
this.downButton.dragged = true;
this.dragStartX = this.x;
this.dragStartY = this.y;
this.dragging = true;
}
}
}
this.setPosition(pos);
return this.downButton !== null;
};
/**
* Handle a mouse / touch up event.
* @param {Object|Vec2=} pos New position to set. Needs to have x and y coordinates. Relative to the canvas coordinate
* space. May be undefined, in which case the last known position will be used to evaluate the effects.
*/
CanvasUICursor.prototype.release = function(pos) {
if (pos !== undefined) {
this.setPosition(pos);
}
if (this.downButton !== null) {
var clicked = false;
var uiElements = this.ui.uiElements;
for (var i = 0; i < uiElements.length; ++i) {
if (uiElements[i].active && uiElements[i].hitTest(this.x, this.y)) {
if (this.downButton === uiElements[i]) {
clicked = true;
} else if (uiElements[i].dragTargetCallback !== null && this.downButton.dragged) {
uiElements[i].dragTargetCallback(this.downButton.draggedObjectFunc());
}
}
}
this.downButton.release(clicked);
if (this.dragging) {
this.downButton.dragged = false;
this.dragging = false;
}
this.downButton = null;
}
console.log(this.x, this.y);
};
/**
* A single UI element to draw on a canvas, typically either a button or a label.
* Will be rendered with text by default, but can also be drawn with a custom rendering function renderFunc.
* @param {Object} options Options for the UI element.
* @constructor
*/
const CanvasUIElement = function(options) {
var defaults = {
label: 'Button',
labelFunc: null, // Function that returns the current text to draw on the element. Overrides label if set.
renderFunc: CanvasUIElement.defaultRenderFunc, // Function to draw the element. Takes CanvasRenderingContext2D, CanvasUIElement, cursorOver (boolean), pressedExtent (0 to 1), label (string)
centerX: 0,
centerY: 0,
width: 100,
height: 50,
clickCallback: null, // Function that is called when the UI element is clicked or tapped.
moveWhenDownCallback: null, // Function that is called while the cursor is moved when the element is down. Takes CanvasUIElement, cursor position (Vec2).
dragTargetCallback: null, // Called when something is dragged onto this object, with the dragged object as parameter.
draggedObjectFunc: null, // Function that returns the dragged object associated with this UI element.
active: true, // Active elements are visible and can be interacted with. Inactive elements are invisible and can't be interacted with.
locked: false, // Locked elements can't be interacted with. Often they'd render with a lock on top.
draggable: false,
pressSpeed: CanvasUIElement.defaultPressSpeed,
depressSpeed: CanvasUIElement.defaultDepressSpeed
};
for(var key in defaults) {
if (!options.hasOwnProperty(key)) {
this[key] = defaults[key];
} else {
this[key] = options[key];
}
}
this.draggedX = this.centerX;
this.draggedY = this.centerY;
this.dragged = false;
this.time = 0.5;
this.isDown = false;
this.lastClick = 0;
this.lastDownTime = -1;
this.lastUpTime = -1;
};
/**
* Minimum interval between clicks on the same button in seconds.
*/
CanvasUIElement.minimumClickInterval = 0.5;
/**
* Visual press/depress speed that affects how fast pressedExtent changes for the element.
*/
CanvasUIElement.defaultPressSpeed = 8.0;
CanvasUIElement.defaultDepressSpeed = 3.0;
/**
* The default font for UI elements used in defaultRenderFunc.
*/
CanvasUIElement.defaultFont = 'sans-serif';
/**
* Font size used by defaultRenderFunc in px.
*/
CanvasUIElement.defaultFontSize = 20;
/**
* Default render function.
* @param {CanvasRenderingContext2D} ctx
* @param {CanvasUIElement} element
* @param {boolean} cursorOver
* @param {number} pressedExtent Between 0 and 1. 1 means fully pressed.
* @param {string} label
*/
CanvasUIElement.defaultRenderFunc = function(ctx, element, cursorOver, pressedExtent, label) {
var isButton = element.clickCallback !== null;
if (isButton) {
var rect = element.getRect();
ctx.fillStyle = '#000';
if (pressedExtent > 0) {
ctx.globalAlpha = 1.0 - pressedExtent * 0.2;
} else if (cursorOver) {
ctx.globalAlpha = 1.0;
} else {
ctx.globalAlpha = 0.5;
}
ctx.fillRect(rect.left, rect.top, rect.width(), rect.height());
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
if (!element.canClick()) {
ctx.globalAlpha *= 0.6;
}
ctx.strokeRect(rect.left, rect.top, rect.width(), rect.height());
}
ctx.globalAlpha = 1.0;
ctx.textAlign = 'center';
ctx.fillStyle = '#fff';
ctx.font = CanvasUIElement.defaultFontSize + 'px ' + CanvasUIElement.defaultFont;
ctx.fillText(label, element.centerX, element.centerY + 7);
};
/**
* Update UI element state and animations.
* @param {number} deltaTime Time passed since the last update in seconds.
*/
CanvasUIElement.prototype.update = function(deltaTime) {
this.time += deltaTime;
};
/**
* Render the element. Will call renderFunc if it is defined.
* @param {CanvasRenderingContext2D} ctx Context to render to.
* @param {Array.<CanvasUICursor>} cursors A list of all active cursors.
*/
CanvasUIElement.prototype.render = function(ctx, cursors) {
if (!this.active) {
return;
}
var pressedExtent = this.isDown ? (this.time - this.lastDownTime) * this.pressSpeed
: 1.0 - (this.time - this.lastUpTime) * this.depressSpeed;
pressedExtent = mathUtil.clamp(0, 1, pressedExtent);
var cursorOver = false;
for (var i = 0; i < cursors.length; ++i) {
var cursor = cursors[i];
if (cursor.active && this.hitTest(cursor.x, cursor.y)) {
cursorOver = true;
}
}
var label = this.label;
if (this.labelFunc !== null) {
label = this.labelFunc();
}
this.renderFunc(ctx, this, cursorOver, pressedExtent, label);
};
/**
* @return {number} The horizontal position to draw the element at. May be different from the logical position if the
* element is being dragged.
*/
CanvasUIElement.prototype.visualX = function() {
if (this.dragged) {
return this.draggedX;
} else {
return this.centerX;
}
};
/**
* @return {number} The vertical position to draw the element at. May be different from the logical position if the
* element is being dragged.
*/
CanvasUIElement.prototype.visualY = function() {
if (this.dragged) {
return this.draggedY;
} else {
return this.centerY;
}
};
/**
* @return {boolean} True when the element is being dragged.
*/
CanvasUIElement.prototype.isDragged = function() {
return this.dragged;
};
/**
* @param {number} x Horizontal coordinate to test.
* @param {number} y Vertical coordinate to test.
* @return {boolean} Whether the coordinate is within the area of the element.
*/
CanvasUIElement.prototype.hitTest = function(x, y) {
if (this.clickCallback !== null || this.moveWhenDownCallback !== null) {
return this.getRect().containsVec2(new Vec2(x, y));
}
return false;
};
/**
* @return boolean True if the element can generate click events right now. False if the click cooldown hasn't
* completed.
*/
CanvasUIElement.prototype.canClick = function() {
var sinceClicked = this.time - this.lastClick;
return sinceClicked >= CanvasUIElement.minimumClickInterval;
};
/**
* @return {Rect} Rectangle of the element centered around its centerX, centerY.
*/
CanvasUIElement.prototype.getRect = function() {
return new Rect(
this.centerX - this.width * 0.5,
this.centerX + this.width * 0.5,
this.centerY - this.height * 0.5,
this.centerY + this.height * 0.5
);
};
/**
* Mark the element as down, for visual purposes only.
*/
CanvasUIElement.prototype.down = function() {
if (!this.isDown) {
this.isDown = true;
this.lastDownTime = this.time;
}
};
/**
* Mark the element as up. Will generate a click event if clicked is true.
* @param {boolean} clicked True when clicked, false when the cursor position has left the area of the element.
*/
CanvasUIElement.prototype.release = function(clicked) {
if (this.isDown) {
this.isDown = false;
this.lastUpTime = this.time;
}
if (!clicked || !this.canClick()) {
return;
}
this.lastClick = this.time;
if (this.clickCallback !== null) {
this.clickCallback();
}
};
export { CanvasUI, CanvasUIElement, CanvasUICursor }
|
var fs = require('fs'),
colors = require('colors'),
program = require('commander'),
prompt = require('prompt'),
async = require('async'),
Table = require('cli-table'),
taghub = require('../lib/taghub');
var configFile = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'] + "/.taghub";
var taghubCli = {
config: null,
/**
* Start of the CLI
**/
run: function(args) {
this.load();
program
.version('0.0.2')
.option('-l, --list', 'show a list of compare tasks')
.option('-a, --add [name]', 'create a compare task with [name]')
.option('-r, --remove [name]', 'remove the compare task [name]')
.option('-t, --task [name]', 'only compare the tag versions of task [name]')
.parse(args);
if(program.list) {
this.list();
}
else if(program.add) {
this.add(program.add);
}
else if(program.remove) {
this.remove(program.remove);
}
else if(program.task) {
this.check(program.task);
}
else {
this.check();
}
},
/**
* Shows a list of added tasks
**/
list: function() {
var table = new Table({
head: ['name', 'source', 'target']
});
this.config.tasks.forEach(function(task) {
var yours = task.yours.full.yellow;
var theirs = task.theirs.full.grey;
table.push(['[' + task.name.green + ']', yours, theirs]);
});
console.log(table.toString());
},
/**
* Asks additional information to add the task
*
* @param {String} name Name of the task to add
**/
add: function(name) {
prompt.start();
if(name !== true) {
prompt.override = {name: name};
}
var ask = {
properties: {
name: {
description: 'task name'
},
yours: {
pattern: /^[a-zA-Z0-9-_]+(\/)+[a-zA-Z0-9-_]+$/,
description: 'specify your repository ' + 'username/repo'.white,
required: true
},
theirs: {
pattern: /^[a-zA-Z0-9-_]+(\/)+[a-zA-Z0-9-_]+$/,
description: 'specify their repository ' + 'username/repo'.white,
required: true
}
}
};
var that = this;
prompt.get(ask, function(err, result) {
var task = taghub.createTask(result.name, result.yours, result.theirs);
that.config.tasks.push(task);
that.save();
});
},
/**
* Removes a task from the config
*
* @param {String} name Name of the task to remove
* @return {Boolean} Returns true on success
**/
remove: function(name) {
if(name === true) {
console.log('Please specify the "task name" to remove'.red);
return;
}
for(var i=0; i<this.config.tasks.length; i++) {
var task = this.config.tasks[i];
if(task.name === name) {
this.config.tasks.splice(i, 1);
console.log('Task: %s is removed'.green, name);
this.save();
return true;
}
}
console.log('Unable to find task: %s'.red, name);
return false;
},
/**
* Check (all) task(s) or just the one matching the name
*
* @param {String} name Name of the task to check (optional)
**/
check: function(name) {
var tasks = [];
if(name === undefined) {
// check all tasks
tasks = this.config.tasks;
}
else {
// find the task by name and check it
var task = this.findTask(name);
if(task === undefined) {
console.log('Unable to find task: %s'.red, name);
return;
}
tasks.push(task);
}
this.performCheckTasks(tasks);
},
/**
* Find a task based by its name
*
* @param {String} name Name of the task to find
* @return {Object} Returns the task on success
**/
findTask: function(name) {
for(var i=0; i<this.config.tasks.length; i++) {
var task = this.config.tasks[i];
if(task.name === name) {
return task;
}
}
},
/**
* Checks the collection of tasks if tag version matches
*
* @param {Array} tasks The tasks to check
**/
performCheckTasks: function(tasks) {
var table = new Table({
head: ['name', 'description', 'target', 'source']
});
// default check all tasks
async.each(tasks, function(task, callback) {
taghub.checkTask(task, function(err, result) {
var row = [];
if(err) {
row.push('[' + task.name.red + ']');
row.push('[ERROR]'.red + ' - returned "' + err.message.grey + '"');
row.push('???');
row.push('???');
}
else {
switch(result.compareState) {
case 0:
row.push('[' + task.name.green + ']');
row.push('versions are equal');
row.push('v' + result.targetVersion.grey);
row.push('v' + result.sourceVersion.grey);
break;
case 1:
row.push('[' + task.name.red + ']');
row.push('their version is ahead of yours');
row.push('v' + result.targetVersion.yellow);
row.push('v' + result.sourceVersion.grey);
break;
case -1:
row.push('[' + task.name.red + ']');
row.push('your version is ahead of the theirs?? ' + 'WuT!?!?!'.rainbow);
row.push('v' + result.targetVersion.grey);
row.push('v' + result.sourceVersion.yellow);
break;
}
}
table.push(row);
callback();
});
}, function() {
console.log(table.toString());
});
},
/**
* Loads the tasks from the config file
**/
load: function() {
if(this.config !== null) {
return;
}
try {
var data = fs.readFileSync(configFile);
this.config = JSON.parse(data);
}
catch (err) {
console.log('No config file found, creating a new one at %s'.grey,
configFile);
this.config = {tasks: []};
this.save();
}
},
/**
* Save the tasks to the config file
**/
save: function() {
var data = JSON.stringify(this.config);
fs.writeFile(configFile, data, function (err) {
if (err) {
console.log('There has been an error saving this config file.'.red);
console.log(err.message);
return;
}
});
}
};
module.exports = taghubCli;
|
/*
* Copyright (c) 2014 airbug Inc. All rights reserved.
*
* All software, both binary and source contained in this work is the exclusive property
* of airbug Inc. Modification, decompilation, disassembly, or any other means of discovering
* the source code of this software is prohibited. This work is protected under the United
* States copyright law and other international copyright treaties and conventions.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@Export('redis.DummyRedisExistsQuery')
//@Require('Class')
//@Require('Set')
//@Require('redis.DummyRedisQuery')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// Bugpack Modules
//-------------------------------------------------------------------------------
var Class = bugpack.require('Class');
var Set = bugpack.require('Set');
var DummyRedisQuery = bugpack.require('redis.DummyRedisQuery');
//-------------------------------------------------------------------------------
// Declare Class
//-------------------------------------------------------------------------------
/**
* @class
* @extends {DummyRedisQuery}
*/
var DummyRedisExistsQuery = Class.extend(DummyRedisQuery, {
_name: "redis.DummyRedisExistsQuery",
//-------------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------------
/**
* @constructs
* @param {DummyRedisClient} dummyRedisClient
* @param {string} key
*/
_constructor: function(dummyRedisClient, key) {
this._super(dummyRedisClient);
//-------------------------------------------------------------------------------
// Private Properties
//-------------------------------------------------------------------------------
/**
* @private
* @type {string}
*/
this.key = key;
},
//-------------------------------------------------------------------------------
// DummyRedisQuery Methods
//-------------------------------------------------------------------------------
/**
* @return {number}
*/
query: function() {
var dummyRedisClient = this.getDummyRedisClient();
if (!dummyRedisClient.isSubscribedState()) {
var dataMap = dummyRedisClient.getKeyToEntryMap();
if (dataMap.containsKey(this.key)) {
return 1;
} else {
return 0;
}
} else {
throw new Error("Connection in subscriber mode, only subscriber commands may be used");
}
}
});
//-------------------------------------------------------------------------------
// Exports
//-------------------------------------------------------------------------------
bugpack.export('redis.DummyRedisExistsQuery', DummyRedisExistsQuery);
});
|
var http = require('http');
var config = require('./config');
var city = '';
var state = '';
var apiKey = config.apiKey; // ********* Enter API key in config file *********** //
// Print out location message
function printMessage(zip, city, state) {
var message = city + ', ' + state + ' ' + zip;
console.log(message);
}
// Print out current conditions
function printConditions(temp, weather, city, state) {
var message = 'It is currently ' + temp + ' F' + ' and ' + weather.toLowerCase() + ' in ' + city + ', ' + state;
console.log(message);
}
// Print out error message
function printError(error) {
console.error(error.message);
}
// Get location data
function getLocation(zip) {
var request = http.get('http://api.wunderground.com/api/' + apiKey + '/geolookup/q/' + zip + '.json', function(response){
var body = '';
response.on('data', function(dataChunk){
body += dataChunk;
});
response.on('end', function(){
if(response.statusCode === 200) {
try {
var city = JSON.parse(body);
// console.log(city.location.city, city.location.state);
getConditions(city.location.city, city.location.state);
} catch(error) {
printError(error);
}
}
});
});
}
// Get current conditions
function getConditions(city, state) {
var requestConditions = http.get('http://api.wunderground.com/api/' + apiKey + '/conditions/q/' + state + '/' + city + '.json', function(response){
var body = '';
response.on('data', function(dataChunk){
body += dataChunk;
});
response.on('end', function(){
if (response.statusCode === 200) {
try {
var conditions = JSON.parse(body);
printConditions(conditions.current_observation.temp_f, conditions.current_observation.weather, city, state);
} catch (error) {
printError(error);
}
}
});
});
}
module.exports.get = getLocation; |
// ou yea
$(function() {
$('#mandar').click(function() {
/* Rock n Roll */
var data = {
name: $("#nombre").val(),
email: $("#email").val(),
message: $("#ta").val()
};
$.ajax({
type: "POST",
url: "sendbymail.php",
data: data,
success: function(){
// hara que un "enviado con exito" en hide con .succes aparezca
$('.success').fadeIn(1000);
// limpio los inputs tras el envio, ya tu sabeh.
$('#nombre').val('');
$('#email').val('');
$('#ta').val('');
$('#ta').focus();
// oculto el mensaje pasado 5sec
setTimeout("$('.success').fadeOut(3000);", 5000);
}
});
return false;
});
});
// mi codigo comentado hace llorar al niño Jesús pero me ayuda con mis milongas |
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter',
[
'ionic',
'starter.controllers',
'starter.constants',
'starter.factories',
'user.controllers',
'user.services'
]
)
.run(function ($ionicPlatform, $rootScope, $state, API) {
$rootScope.$on('$stateChangeError',
function (event, toState, toParams, fromState, fromParams, error) {
//debugger;
console.log('$stateChangeError ' + error && (error.debug || error.message || error));
// if the error is "noUser" the go to login state
if (error && error.error === "noUser") {
event.preventDefault();
$state.go('auth-login', {});
}
});
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
if (!ionic.Platform.isWebView()) {
facebookConnectPlugin.browserInit(API.facebookAppId);
// version is optional. It refers to the version of API you may want to use.
}
});
})
.config(function ($stateProvider, $urlRouterProvider, API) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('auth-login', {
url: "/login",
templateUrl: "templates/user/login.html",
controller: "UserController"
})
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
.state('tab.dash', {
url: '/dash',
views: {
'tab-dash': {
templateUrl: 'templates/tab-dash.html',
controller: 'DashCtrl'
}
},
resolve: {
user: function (UserService) {
var value = UserService.init();
return value;
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'UserController'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
});
|
module.exports = {
"nycCoverage": false,
"coverage": false,
"auto_compose": true,
"node": "16",
"tester_flavour": "rdkafka-tester",
"parallel": 1,
"test_framework": "jest --config ./jest.config.js --runTestsByPath",
"tests": "__tests__/**/*.spec.ts",
"arbitrary_exec": ["node scripts/rebuild-kafka.js"],
"extras": {
"tester": {
"working_dir": "/src/packages/plugin-kafka",
volumes: [
'${PWD}/../..:/src:cached',
'${PWD}/../../node_modules:/src/node_modules:cached',
],
environment: {
TS_NODE_TRANSPILE_ONLY: "true",
TS_NODE_TYPE_CHECK: "false",
TS_NODE_FILES: "true"
}
}
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:271fad2636d00ce96de971012a1cbc2513ce0aa915438b21220e4aa0c9abcdfb
size 5862
|
var searchData=
[
['handle_5ftag',['handle_tag',['../item_8php.html#abd0e603a6696051af16476eb968d52e7',1,'item.php']]],
['has_5fpermissions',['has_permissions',['../items_8php.html#a77051724d1784074ff187e73a4db93fe',1,'items.php']]],
['hcard_2ephp',['hcard.php',['../hcard_8php.html',1,'']]],
['hcard_5faside',['hcard_aside',['../hcard_8php.html#a956c7cae2009652a37900306e5b7b73d',1,'hcard.php']]],
['hcard_5finit',['hcard_init',['../hcard_8php.html#ac34f26b0e6a37eef44fa49bea135136d',1,'hcard.php']]],
['head_5fadd_5fcss',['head_add_css',['../plugin_8php.html#a23c4fccf1eb5fcd63b24783ba1f05f7a',1,'plugin.php']]],
['head_5fadd_5fjs',['head_add_js',['../plugin_8php.html#a516591850f4fd49fd1425cfa54089db8',1,'plugin.php']]],
['head_5fget_5fcss',['head_get_css',['../plugin_8php.html#af92789f559b89a380e49d303218aeeca',1,'plugin.php']]],
['head_5fget_5ficon',['head_get_icon',['../classApp.html#af17df107f2216ddf5ad2a7e0f2ba2166',1,'App\head_get_icon()'],['../boot_8php.html#a24a7a70afedd5d85fe0eadc85afa9f77',1,'head_get_icon(): boot.php']]],
['head_5fget_5fjs',['head_get_js',['../plugin_8php.html#a65ab52cb1a7030d5190e247211bef2a1',1,'plugin.php']]],
['head_5fset_5ficon',['head_set_icon',['../classApp.html#a8863703a0305eaa45eb970dbd2046291',1,'App\head_set_icon()'],['../boot_8php.html#a0e4701c9742c3ef88f02ac450a042a84',1,'head_set_icon(): boot.php']]],
['help',['help',['../namespacefriendica-to-smarty-tpl.html#af6b2c793958aae2aadc294577431f749',1,'friendica-to-smarty-tpl.help()'],['../namespaceupdatetpl.html#ac9d11279fed403a329a719298feafc4f',1,'updatetpl.help()']]],
['help_2ephp',['help.php',['../help_8php.html',1,'']]],
['help_5fcontent',['help_content',['../help_8php.html#af055e15f600ffa6fbca9386fdf715224',1,'help.php']]],
['home_2ephp',['home.php',['../home_8php.html',1,'']]],
['hostxrd_2ephp',['hostxrd.php',['../hostxrd_8php.html',1,'']]],
['hostxrd_5finit',['hostxrd_init',['../hostxrd_8php.html#aa37ffc8e7900bc76c4828bd25916db92',1,'hostxrd.php']]],
['html2bb_5fvideo',['html2bb_video',['../text_8php.html#a138a3a611fa7f4f3630674145fc826bf',1,'text.php']]],
['html2bbcode',['html2bbcode',['../html2bbcode_8php.html#a5ad726995ac4070213abdb3bd09f4837',1,'html2bbcode.php']]],
['html2bbcode_2ephp',['html2bbcode.php',['../html2bbcode_8php.html',1,'']]],
['html2plain',['html2plain',['../html2plain_8php.html#ab3e121fa9f3feb16f9f942e705bc6c04',1,'html2plain.php']]],
['html2plain_2ephp',['html2plain.php',['../html2plain_8php.html',1,'']]],
['http_5fstatus_5fexit',['http_status_exit',['../include_2network_8php.html#a4cfb2c05a1c295317283d762440ce0b2',1,'network.php']]],
['hubloc_5fflags_5fprimary',['HUBLOC_FLAGS_PRIMARY',['../boot_8php.html#a3ad9cc5d4354be741fa1de12b96e9955',1,'boot.php']]],
['hubloc_5fflags_5funverified',['HUBLOC_FLAGS_UNVERIFIED',['../boot_8php.html#ab54b24cc302e1a42a67a49d788b6b764',1,'boot.php']]]
];
|
/* global require, describe, it */
'use strict';
var mpath = './../lib/async.js';
// MODULES //
var chai = require( 'chai' ),
mkdirp = require( 'mkdirp' ),
path = require( 'path' ),
fs = require( 'fs' ),
proxyquire = require( 'proxyquire' ),
cp = require( mpath );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'async', function tests() {
it( 'should export a function', function test() {
expect( cp ).to.be.a( 'function' );
});
it( 'should throw an error if not provided a destination', function test() {
expect( foo ).to.throw( Error );
function foo() {
cp();
}
});
it( 'should throw an error if not provided a valid destination directory', function test() {
var values = [
5,
null,
true,
undefined,
NaN,
[],
{},
function(){}
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( TypeError );
}
function badValue( value ) {
return function() {
cp( value );
};
}
});
it( 'should throw an error if not provided a valid options argument', function test() {
var values = [
'beep',
5,
null,
true,
undefined,
NaN,
[],
// function(){} // allowed as fcn is variadic
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue1( values[i] ) ).to.throw( TypeError );
expect( badValue2( values[i] ) ).to.throw( TypeError );
}
function badValue1( value ) {
return function() {
cp( './beep/boop', value );
};
}
function badValue2( value ) {
return function() {
cp( './beep/boop', value, function(){} );
};
}
});
it( 'should throw an error if provided an invalid option', function test() {
var values = [
5,
null,
true,
undefined,
NaN,
[],
{},
function(){}
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( TypeError );
}
function badValue( value ) {
return function() {
cp( './beep/boop', {
'name': value
});
};
}
});
it( 'should throw an error if provided a callback argument which is not a function', function test() {
var values = [
'beep',
5,
null,
true,
undefined,
NaN,
[],
{}
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( TypeError );
}
function badValue( value ) {
return function() {
cp( './beep/boop', {}, value );
};
}
});
it( 'should create a package.json file in a specified directory', function test( done ) {
var dirpath;
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
mkdirp.sync( dirpath );
cp( dirpath, onFinish );
function onFinish( error ) {
var bool;
if ( error ) {
assert.ok( false );
} else {
bool = fs.existsSync( path.join( dirpath, 'package.json' ) );
assert.isTrue( bool );
}
done();
}
});
it( 'should create a configured package.json file in a specified directory', function test( done ) {
var dirpath;
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
mkdirp.sync( dirpath );
cp( dirpath, {
'template': 'default',
'name': 'my-really-cool-module-which-no-one-has-ever-done-before-beep-boop',
'desc': 'Beep boop.',
'author': 'Jane Doe',
'email': 'jane@doe.com',
'repo': 'jane/beep',
'cmd': 'beepboop',
'license': 'MIT',
'keywords': ['beep','boop','bop'],
'private': true
}, onFinish );
function onFinish( error ) {
var fpath1,
fpath2,
f1, f2;
if ( error ) {
assert.ok( false );
done();
return;
}
fpath1 = path.join( dirpath, 'package.json' );
fpath2 = path.join( __dirname, 'fixtures', 'package.json' );
f1 = require( fpath1 );
f2 = require( fpath2 );
assert.deepEqual( f1, f2 );
done();
}
});
it( 'should pass any errors encountered while checking package name availability to a provided callback', function test( done ) {
var dirpath,
cp;
cp = proxyquire( mpath, {
'./package_name.js': function isAvailable( name , clbk ) {
clbk( new Error() );
}
});
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
cp( dirpath, {
'name': 'beep'
}, onFinish );
function onFinish( error ) {
if ( error ) {
assert.ok( true );
} else {
assert.ok( false );
}
done();
}
});
it( 'should pass an error to a provided callback if a package name is not available on NPM', function test( done ) {
var dirpath,
cp;
cp = proxyquire( mpath, {
'./package_name.js': function isAvailable( name , clbk ) {
clbk( null, false );
}
});
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
cp( dirpath, {
'name': 'request'
}, onFinish );
function onFinish( error ) {
if ( error ) {
assert.ok( true );
} else {
assert.ok( false );
}
done();
}
});
it( 'should pass any read errors to a provided callback', function test( done ) {
var dirpath,
cp;
cp = proxyquire( mpath, {
'fs': {
'readFile': function read( path, opts, clbk ) {
clbk( new Error() );
}
}
});
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
cp( dirpath, onFinish );
function onFinish( error ) {
if ( error ) {
assert.ok( true );
} else {
assert.ok( false );
}
done();
}
});
it( 'should pass any write errors to a provided callback', function test( done ) {
var dirpath;
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
cp( dirpath, onFinish );
function onFinish( error ) {
if ( error ) {
assert.ok( true );
} else {
assert.ok( false );
}
done();
}
});
it( 'should create a package.json file in a specified directory without requiring a callback', function test( done ) {
var dirpath;
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
mkdirp.sync( dirpath );
cp( dirpath );
setTimeout( onTimeout, 500 );
function onTimeout() {
var bool = fs.existsSync( path.join( dirpath, 'package.json' ) );
assert.isTrue( bool );
done();
}
});
it( 'should create a package.json file using a specified template', function test( done ) {
var dirpath;
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
mkdirp.sync( dirpath );
cp( dirpath, {
'template': 'default'
}, onFinish );
function onFinish( error ) {
var bool;
if ( error ) {
assert.ok( false );
} else {
bool = fs.existsSync( path.join( dirpath, 'package.json' ) );
assert.isTrue( bool );
}
done();
}
});
it( 'should ignore any unrecognized options', function test( done ) {
var dirpath;
dirpath = path.resolve( __dirname, '../build/' + new Date().getTime() );
mkdirp.sync( dirpath );
cp( dirpath, {
'beep': 'boop'
}, onFinish );
function onFinish( error ) {
var bool;
if ( error ) {
assert.ok( false );
} else {
bool = fs.existsSync( path.join( dirpath, 'package.json' ) );
assert.isTrue( bool );
}
done();
}
});
});
|
import fs from 'fs';
import winston from 'winston';
export default function (opt) {
const logs = opt.logs || './logs';
if (!fs.existsSync(logs)) {
fs.mkdirSync(logs);
}
const logger = winston.createLogger({
transports: [
new winston.transports.File({
level: 'info',
filename: `./${logs}/all-logs.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
}),
new winston.transports.Console({
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
}),
],
exitOnError: false,
});
const stream = {
write(message) {
logger.info(message);
},
};
return {
logger,
stream,
};
}
|
'use strict';
var JavascriptUtils = {
// get selected text in the current window
getSelectedText: function () {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (window.document.getSelection) {
txt = window.document.getSelection();
} else if (window.document.selection) {
txt = window.document.selection.createRange().text;
}
return txt;
},
// get selected text and parent element in the current window
getSelectionTextAndContainerElement: function () {
var text = "", containerElement = null;
if (typeof window.getSelection !== "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var node = sel.getRangeAt(0).commonAncestorContainer;
containerElement = node.nodeType === 1 ? node : node.parentNode;
text = sel.toString();
}
} else if (typeof document.selection !== "undefined" &&
document.selection.type !== "Control") {
var textRange = document.selection.createRange();
containerElement = textRange.parentElement();
text = textRange.text;
}
return {
text: text,
containerElement: containerElement
};
},
toggleFullScreen: function (elem) {
// https://developer.mozilla.org/fr/docs/Web/Guide/DOM/Using_full_screen_mode
if (!document.fullscreenElement && // alternative standard method
!document.mozFullScreenElement && !document.webkitFullscreenElement) { // current working methods
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
}
}; |
import React, { Component } from 'react';
import sortList from 'common/sortable';
import { getRandomString } from '../multi-input/part';
import MultiInputList from 'app/common/component/multi-input/list';
export default class List extends MultiInputList {
constructor(props) {
super(props);
}
render() {
const {
dataSourceUi,
listClassName,
sortable,
showCheckbox,
showDeleteBtn,
checkBoxName,
inputName
} = this.context;
let name = '';
if (dataSourceUi.length > 0) {
name = 'list-group';
}
return (
<ul id={this.listId} className={`multi-list sortable-list ${name} ${listClassName}`}>
{
dataSourceUi.map((item, i) => {
return (
<li className="list-group-item" id={item.itemId} key={i} data-seq={item.seq}>
{sortable && <i className="es-icon es-icon-yidong mrl color-gray inline-block vertical-middle"></i>}
<img className="avatar-sm avatar-sm-square mrm" src={item.avatar} />
<span className="label-name text-overflow inline-block vertical-middle">{item.nickname}</span>
<label className={showCheckbox ? '' : 'hidden'}><input type="checkbox" name={checkBoxName + item.id} checked={item.isVisible} onChange={event => this.context.onChecked(event)} value={item.itemId} />显示</label>
<a className={showDeleteBtn ? 'pull-right link-gray mtm' : 'hidden'} onClick={event => this.context.removeItem(event)} data-item-id={item.itemId}>
<i className="es-icon es-icon-close01 text-12"></i>
</a>
<input type="hidden" name={inputName} value={item.id} />
</li>
)
})
}
</ul>
)
}
};
List.contextTypes = {
...MultiInputList.contextTypes,
showCheckbox: React.PropTypes.bool,
showDeleteBtn: React.PropTypes.bool,
checkBoxName: React.PropTypes.string,
onChecked: React.PropTypes.func,
}; |
var mongoose = require('mongoose');
var Blog = mongoose.Schema({
imageUrl: String,
title: String,
permalink: String,
isActive: {type: Boolean, default: false},
author: String,
tags: Array,
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
preview: String,
content: String,
comments: [{author: String, content: String, createdAt: Date}]
});
Blog.methods.toVM = function(){
var _this = this;
return {
title: _this.title,
author: _this.author,
imageUrl: _this.imageUrl,
permalink: _this.permalink,
preview: _this.preview,
content: _this.content,
tags: _this.tags,
createdAt: _this.createdAt,
updateAt: _this.updateAt,
comments: _this.comments
};
};
Blog.statics.get = function (query, limit, callback) {
this.find(query).sort({'createdAt': -1}).limit(limit || 10).exec(function(err, data) {
if (!err) return callback(data);
});
};
module.exports = mongoose.model('blogs', Blog); |
window.FacilityFilter = function () {
};
/**
* 指定したフィルター条件に一致する施設情報のGeoJsonを生成する
*
* @param {[type]} conditions [description]
* @param {[type]} nurseryFacilities [description]
* @return {[type]} [description]
*/
FacilityFilter.prototype.getFilteredFeaturesGeoJson = function (conditions, nurseryFacilities)
{
// 絞り込んだ条件に一致する施設を格納するgeoJsonを準備
var newGeoJson = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features":[]
};
// console.log("getFilteredFeaturesGeoJson");
// 認可保育園の検索元データを取得
var ninkaFeatures = [];
_features = nurseryFacilities.features.filter(function (item,idx) {
var type = item.properties['種別'] ? item.properties['種別'] : item.properties['Type'];
if(type == "認可保育所") return true;
});
Array.prototype.push.apply(ninkaFeatures, _features);
// 認可外保育園の検索元データを取得
var ninkagaiFeatures = [];
_features = nurseryFacilities.features.filter(function (item,idx) {
var type = item.properties['種別'] ? item.properties['種別'] : item.properties['Type'];
if(type == "認可外保育所") return true;
});
Array.prototype.push.apply(ninkagaiFeatures, _features);
// 幼稚園の検索元データを取得
var youchienFeatures = [];
_features = nurseryFacilities.features.filter(function (item,idx) {
var type = item.properties['種別'] ? item.properties['種別'] : item.properties['Type'];
if(type == "幼稚園") return true;
});
Array.prototype.push.apply(youchienFeatures, _features);
// ----------------------------------------------------------------------
// 認可保育所向けフィルター
// ----------------------------------------------------------------------
// 認可保育所:開園時間
// console.log("[before]ninkaFeatures length:", ninkaFeatures.length);
if(conditions['ninkaOpenTime']) {
filterfunc = function (item, idx) {
f = function (item,idx) {
// var _time = conditions['ninkaOpenTime'] + ":00";
var _time = conditions['ninkaOpenTime'];
var open = item.properties['開園時間'] ? item.properties['開園時間'] : item.properties['Open'];
if(open == _time) {
return true;
}
};
return f(item,idx);
};
ninkaFeatures = ninkaFeatures.filter(filterfunc);
}
// 認可保育所:終園時間
if(conditions['ninkaCloseTime']) {
filterfunc = function (item, idx) {
f = function (item,idx) {
switch(conditions['ninkaCloseTime']) {
case "18":
checkAry = ["18:00","18:30","18:45","18:50","18:55","19:00","19:15","19:30","20:00","21:30"];
break;
case "19":
checkAry = ["19:00","19:15","19:30","20:00","21:30"];
break;
case "20":
checkAry = ["20:00","21:30"];
break;
case "21":
checkAry = ["21:30"];
break;
}
var close = item.properties['終園時間'] ? item.properties['終園時間'] : item.properties['Close'];
if($.inArray(close, checkAry) >= 0) {
return true;
}
};
return f(item,idx);
};
ninkaFeatures = ninkaFeatures.filter(filterfunc);
}
// 認可保育所:一時
if(conditions['ninkaIchijiHoiku']) {
filterfunc = function (item,idx) {
var temp = item.properties['一時'] ? item.properties['一時'] : item.properties['Temp'];
if(temp === 'Y') {
return true;
}
};
ninkaFeatures = ninkaFeatures.filter(filterfunc);
}
// 認可保育所:夜間
if(conditions['ninkaYakan']) {
filterfunc = function (item,idx) {
var night = item.properties['夜間'] ? item.properties['夜間'] : item.properties['Night'];
if(night === 'Y') {
return true;
}
};
ninkaFeatures = ninkaFeatures.filter(filterfunc);
}
// 認可保育所:休日
if(conditions['ninkaKyujitu']) {
filterfunc = function (item,idx) {
var holiday = item.properties['休日'] ? item.properties['休日'] : item.properties['Holiday'];
if(holiday === 'Y') {
return true;
}
};
ninkaFeatures = ninkaFeatures.filter(filterfunc);
}
if(conditions['ninkaVacancy']) {
filterfunc = function (item,idx) {
var vacancy = item.properties['Vacancy'] ? item.properties['Vacancy'] : item.properties['Vacancy'];
if(vacancy === 'Y') {
return true;
}
};
ninkaFeatures = ninkaFeatures.filter(filterfunc);
}
// console.log("[after]ninkaFeatures length:", ninkaFeatures.length);
// ----------------------------------------------------------------------
// 認可外保育所向けフィルター
// ----------------------------------------------------------------------
// 認可外:開園時間
// console.log("[before]ninkagaiFeatures length:", ninkagaiFeatures.length);
if(conditions['ninkagaiOpenTime']) {
filterfunc = function (item, idx) {
f = function (item,idx) {
var _time = conditions['ninkagaiOpenTime'];
var open = item.properties['開園時間'] ? item.properties['開園時間'] : item.properties['Open'];
if(open == _time) {
return true;
}
};
return f(item,idx);
};
ninkagaiFeatures = ninkagaiFeatures.filter(filterfunc);
}
// 認可外:終園時間
if(conditions['ninkagaiCloseTime']) {
filterfunc = function (item, idx) {
f = function (item,idx) {
checkAry = [];
switch(conditions['ninkagaiCloseTime']) {
case "18":
checkAry = ["18:00","19:00","19:30","19:45","20:00","20:30","22:00","23:00","3:00"];
break;
case "19":
checkAry = ["19:00","19:30","19:45","20:00","20:30","22:00","23:00","3:00"];
break;
case "20":
checkAry = ["20:00","20:30","22:00","23:00","3:00"];
break;
case "22":
checkAry = ["22:00","23:00","3:00"];
break;
case "27":
checkAry = ["3:00"];
break;
}
var h24 = item.properties['H24'] ? item.properties['H24'] : item.properties['H24'];
var close = item.properties['終園時間'] ? item.properties['終園時間'] : item.properties['Close'];
if(h24 === 'Y' || $.inArray(close, checkAry) >= 0) {
return true;
}
};
return f(item,idx);
};
ninkagaiFeatures = ninkagaiFeatures.filter(filterfunc);
}
// 認可保育所:24時間
if(conditions['ninkagai24H']) {
filterfunc = function (item,idx) {
var h24 = item.properties['H24'] ? item.properties['H24'] : item.properties['H24'];
if(h24 === 'Y') {
return true;
}
};
ninkagaiFeatures = ninkagaiFeatures.filter(filterfunc);
}
// 認可保育所:証明あり
if(conditions['ninkagaiShomei']) {
filterfunc = function (item,idx) {
var proof = item.properties['証明'] ? item.properties['証明'] : item.properties['Proof'];
if(proof === 'Y') {
return true;
}
};
ninkagaiFeatures = ninkagaiFeatures.filter(filterfunc);
}
// console.log("[after]ninkagaiFeatures length:", ninkagaiFeatures.length);
// ----------------------------------------------------------------------
// 幼稚園向けフィルター
// ----------------------------------------------------------------------
// まだ用意しない
// 戻り値の作成
var features = [];
Array.prototype.push.apply(features, ninkaFeatures);
Array.prototype.push.apply(features, ninkagaiFeatures);
Array.prototype.push.apply(features, youchienFeatures);
// console.log("getFilteredFeaturesGeoJson: return value: ", features.length);
newGeoJson.features = features;
return newGeoJson;
};
|
const dests = {
'' : '000',
'M' : '001',
'D' : '010',
'MD' : '011',
'A' : '100',
'AM' : '101',
'AD' : '110',
'AMD': '111'
};
const comps = {
'0' : '0101010',
'1' : '0111111',
'-1' : '0111010',
'D' : '0001100',
'A' : '0110000',
'!D' : '0001101',
'!A' : '0110001',
'-D' : '0001111',
'-A' : '0110011',
'D+1': '0011111',
'A+1': '0110111',
'D-1': '0001110',
'A-1': '0110010',
'D+A': '0000010',
'D-A': '0010011',
'A-D': '0000111',
'D&A': '0000000',
'D|A': '0010101',
'M' : '1110000',
'!M' : '1110001',
'-M' : '1110011',
'M+1': '1110111',
'M-1': '1110010',
'D+M': '1000010',
'D-M': '1010011',
'M-D': '1000111',
'D&M': '1000000',
'D|M': '1010101'
};
const jumps = {
'' : '000',
'JGT': '001',
'JEQ': '010',
'JGE': '011',
'JLT': '100',
'JNE': '101',
'JLE': '110',
'JMP': '111'
};
export const translateDest = mnemonic => dests[mnemonic];
export const translateComp = mnemonic => comps[mnemonic];
export const translateJump = mnemonic => jumps[mnemonic];
|
module.exports = function() {
class ClassA {
constructor() {
this.__ks_init();
this.__ks_cons(arguments);
}
__ks_init() {
}
__ks_cons_0() {
try {
foo();
}
catch(error) {
throw error;
}
}
__ks_cons(args) {
if(args.length === 0) {
ClassA.prototype.__ks_cons_0.apply(this);
}
else {
throw new SyntaxError("Wrong number of arguments");
}
}
}
}; |
// @flow
jest.mock('fs');
import { fileJournaler } from '../src/journalers';
import fs from 'fs';
describe('fileJournaler', () => {
it('should allow setting file path for journaler', async () => {
const setCollectionName = fileJournaler('/dev/null');
const configured = setCollectionName('coll');
await configured({ rec: 'This record is cool!' });
expect(fs.__mockedFile[0]).toHaveProperty('path', '/dev/null');
});
it('should append records to the given file', async () => {
const setCollectionName = fileJournaler('/dev/null');
const configured = setCollectionName('coll');
const record = { rec: 'This record is cool!' };
const success = await configured(record);
expect(success).toBe(true);
expect(fs.__mockedFile[0]).toHaveProperty('data', JSON.stringify(record));
});
it('should warn if failed to write but return false', async () => {
global.console = { warn: jest.fn() };
const setCollectionName = fileJournaler('fail');
const configured = setCollectionName('coll');
const record = { rec: 'This record is cool!' };
const success = await configured(record);
expect(success).toBe(false);
expect(console.warn).toBeCalledWith('Could not write to file due to error', fs.__mockedError);
});
it('should warn if failed to parse record but return false', async () => {
const error = new Error();
global.JSON = {stringify: jest.fn(() => {throw error})};
global.console = { warn: jest.fn() };
const setCollectionName = fileJournaler('fail');
const configured = setCollectionName('coll');
const record = { rec: 'This record is cool!' };
const success = await configured(record);
expect(success).toBe(false);
expect(console.warn).toBeCalledWith('Could not write to file due to error', error);
});
afterEach(() => {
jest.clearAllMocks();
});
}); |
var view;
view = new Thorax.LayoutView({
setView: function(view) {
view.on('all', function(eventName) {
return $('body').append(this.name + ': ' + eventName + '<br>');
});
Thorax.LayoutView.prototype.setView.call(this, view);
return $('body').append('<hr>');
},
showViewA: function() {
return this.setView(new Thorax.View({
name: 'A',
template: Handlebars.compile("A")
}));
},
showViewB: function() {
return this.setView(new Thorax.View({
name: "B",
template: Handlebars.compile("B")
}));
},
template: Handlebars.compile("{{layout-element}}\n{{#button \"showViewA\" class=\"btn\"}}Set View A{{/button}}\n{{#button \"showViewB\" class=\"btn\"}}Set View B{{/button}}")
});
view.appendTo('body');
|
version https://git-lfs.github.com/spec/v1
oid sha256:307070caee667b8cb3792501f2212a95350c9fcb14da17483f44eeb8b7786cf9
size 631748
|
'use strict';
angular.module('accessibleTodoListApp')
.controller('MainCtrl', function ($scope) {
$scope.todos = ['Item 1','Item 2','Item 3'];
});
|
/**
* @fileoverview Editor class - Application Subclass for Model/Scene Editor
* @author Tony Parisi / http://www.tonyparisi.com
*/
goog.provide('Vizi.Editor');
Vizi.Editor = function(param) {
// Chain to superclass
Vizi.Viewer.call(this, param);
this.showSelectionBoxes = true;
this.showNormals = true;
this.normalDecoration = null;
this.planeDecoration = null;
this.planeDecoration2 = null;
this.selectedObject = null;
}
goog.inherits(Vizi.Editor, Vizi.Viewer);
Vizi.Editor.prototype.selectObject = function(object, event) {
if (this.showSelectionBoxes) {
this.highlightObject(object);
}
else {
this.highlightObject(null);
}
if (this.showNormals) {
this.showNormal(object, event);
}
this.selectedObject = object;
}
Vizi.Editor.prototype.onMouseMove = function(object, event) {
if (this.selectedObject) {
this.showNormal(object, event);
}
}
Vizi.Editor.prototype.showNormal = function(object, event) {
console.log("showNormal: ", event);
if (object === null || event && event.normal && this.showNormals) {
if (this.highlightedObject) {
this.highlightedObject._parent.removeComponent(this.normalDecoration);
this.highlightedObject._parent.removeComponent(this.planeDecoration);
this.highlightedObject._parent.removeComponent(this.planeDecoration2);
}
if (object) {
var bbox = Vizi.SceneUtils.computeBoundingBox(object);
var width = bbox.max.x - bbox.min.x,
height = bbox.max.y - bbox.min.y,
depth = bbox.max.z - bbox.min.z;
// The normal
var normalLength = Math.max(width, Math.max(height, depth));
var hitpoint = event.point.clone();
var hitnormal = event.normal.clone();
var vec = hitpoint.clone().add(hitnormal.multiplyScalar(normalLength));
this.normalDecoration = Vizi.Helpers.VectorDecoration({
start : hitpoint,
end : vec,
color : 0xaa0000
});
this.highlightedObject._parent.addComponent(this.normalDecoration);
// The plane
var planeSize = Math.max(width, Math.max(height, depth));
this.planeDecoration2 = Vizi.Helpers.PlaneDecoration({
normal: event.normal,
position:event.point,
size:planeSize});
this.highlightedObject._parent.addComponent(this.planeDecoration2);
}
}
}
Vizi.Editor.prototype.highlightObject = function(object) {
if (object === null) {
this.showNormal(object, null);
}
Vizi.Viewer.prototype.highlightObject.call(this, object);
}
Vizi.Editor.prototype.setSelectionBoxesOn = function(on)
{
this.showSelectionBoxes = !this.showSelectionBoxes;
this.highlightObject(null);
}
Vizi.Editor.prototype.setNormalsOn = function(on)
{
this.showNormals = !this.showNormals;
this.showNormal(null, null);
}
Vizi.Editor.DRAG_PLANE_SIZE = 10;
|
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
import { typedDependencies } from './dependenciesTyped.generated'
import { createRightLogShift } from '../../factoriesNumber.js'
export const rightLogShiftDependencies = {
typedDependencies,
createRightLogShift
}
|
require('./connect');
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
// 定义模式loginSchema
const loginSchema = new Schema({
account : String,
password : String
}, {
versionKey: false
});
// 定义模式registrySchema
const registrySchema = new Schema({
account : String,
password : String,
sex : Boolean,
birthday : Date,
tel : String,
email : String
}, {
versionKey: false
});
const Models = {
// 定义模型loginModel,数据库存的是logins
loginModel : mongoose.model("login", loginSchema),
// 定义模型registryModel,数据库存的是registrys
registryModel : mongoose.model("registry", registrySchema)
}
module.exports = Models;
/*mongoose.Schema({
username: {// 真实姓名
type: String,
required: true
},
password: { // 密码
type: String,
required: true
}
});*/
|
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('ArrayBuffer', function(assert){
var b;
assert.same(ArrayBuffer, Object(ArrayBuffer), 'is object');
NATIVE && assert.arity(ArrayBuffer, 1);
NATIVE && assert.name(ArrayBuffer, 'ArrayBuffer');
NATIVE && assert.looksNative(ArrayBuffer);
b = new ArrayBuffer(123);
assert.same(b.byteLength, 123, 'length');
if (NATIVE) {
assert.throws(function(){
new ArrayBuffer(-1);
}, RangeError, 'negative length');
assert.throws(function(){
new ArrayBuffer();
}, RangeError, 'missed length');
assert.throws(function(){
new ArrayBuffer(Number.MAX_SAFE_INTEGER + 1);
}, RangeError, 'absurd length');
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('ArrayBuffer.isView', function(assert){
var isView, i$, x$, ref$, len$, y$;
isView = ArrayBuffer.isView;
assert.isFunction(isView);
assert.arity(isView, 1);
assert.name(isView, 'isView');
assert.looksNative(isView);
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
if (global[x$]) {
assert.same(isView(new global[x$]([1])), true, x$ + " - true");
}
}
assert.same(isView(new DataView(new ArrayBuffer(1))), true, "DataView - true");
assert.same(isView(new ArrayBuffer(1)), false, "ArrayBuffer - false");
for (i$ = 0, len$ = (ref$ = [void 8, null, false, true, 0, 1, '', 'qwe', {}, [], fn$]).length; i$ < len$; ++i$) {
y$ = ref$[i$];
assert.same(isView(y$), false, y$ + " - false");
}
function fn$(){}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('ArrayBuffer#slice', function(assert){
var array, buffer;
assert.isFunction(ArrayBuffer.prototype.slice);
assert.arity(ArrayBuffer.prototype.slice, 2);
assert.name(ArrayBuffer.prototype.slice, 'slice');
assert.looksNative(ArrayBuffer.prototype.slice);
array = new Uint8Array([1, 2, 3, 4, 5]);
buffer = array.buffer;
assert.ok(buffer instanceof ArrayBuffer, 'correct buffer');
assert.ok(buffer.slice() !== buffer, 'returns new buffer');
assert.ok(buffer.slice() instanceof ArrayBuffer, 'correct instance');
assert.arrayEqual(new Uint8Array(buffer.slice()), array);
assert.arrayEqual(new Uint8Array(buffer.slice(1, 3)), [2, 3]);
assert.arrayEqual(new Uint8Array(buffer.slice(1, void 8)), [2, 3, 4, 5]);
assert.arrayEqual(new Uint8Array(buffer.slice(1, -1)), [2, 3, 4]);
assert.arrayEqual(new Uint8Array(buffer.slice(-2, -1)), [4]);
assert.arrayEqual(new Uint8Array(buffer.slice(-2, -3)), []);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, $name, ref$, $bytes;
module = QUnit.module, test = QUnit.test;
module('ES6');
if (DESCRIPTORS) {
for ($name in ref$ = {
Float32Array: 4,
Float64Array: 8,
Int8Array: 1,
Int16Array: 2,
Int32Array: 4,
Uint8Array: 1,
Uint16Array: 2,
Uint32Array: 4,
Uint8ClampedArray: 1
}) {
$bytes = ref$[$name];
(fn$.call(this, $name, $bytes));
}
}
function fn$(name, bytes){
var this$ = this;
test(name + " constructor", function(assert){
var Typed, a, e, b;
Typed = global[name];
assert.isFunction(Typed);
assert.arity(Typed, 3);
assert.name(Typed, name);
NATIVE && assert.looksNative(Typed);
assert.same(Typed.BYTES_PER_ELEMENT, bytes, name + ".BYTES_PER_ELEMENT");
a = new Typed(4);
assert.same(a.BYTES_PER_ELEMENT, bytes, '#BYTES_PER_ELEMENT');
assert.same(a.byteOffset, 0, name + '#byteOffset, passed number');
assert.same(a.byteLength, 4 * bytes, '#byteLength, passed number');
assert.arrayEqual(a, [0, 0, 0, 0], 'correct values, passed number');
try {
a = new Typed('0x4');
assert.same(a.byteOffset, 0, '#byteOffset, passed string');
assert.same(a.byteLength, 4 * bytes, '#byteLength, passed string');
assert.arrayEqual(a, [0, 0, 0, 0], 'correct values, passed string');
} catch (e$) {
e = e$;
assert.same(e, [0, 0, 0, 0], 'passed string');
}
try {
a = new Typed(true);
assert.same(a.byteOffset, 0, '#byteOffset, passed boolean');
assert.same(a.byteLength, 1 * bytes, '#byteLength, passed boolean');
assert.arrayEqual(a, [0], 'correct values, passed boolean');
} catch (e$) {
e = e$;
assert.same(e, [0], 'passed boolean');
}
assert.throws(function(){
new Typed;
}, TypeError, 'throws without argument');
assert.throws(function(){
new Typed(void 8);
}, TypeError, 'throws on undefined');
assert.throws(function(){
new Typed(1.5);
}, RangeError, 'throws on 1.5');
assert.throws(function(){
new Typed(-1);
}, RangeError, 'throws on -1');
assert.throws(function(){
new Typed(-0);
}, RangeError, 'throws on -0');
assert.throws(function(){
new Typed(NaN);
}, RangeError, 'throws on NaN');
try {
a = new Typed(null);
assert.same(a.byteOffset, 0, '#byteOffset, passed null');
assert.same(a.byteLength, 0, '#byteLength, passed null');
assert.arrayEqual(a, [], 'correct values, passed null');
} catch (e$) {
e = e$;
assert.same(e, [], 'passed null');
}
a = new Typed([1, 2, 3, 4]);
assert.same(a.byteOffset, 0, '#byteOffset, passed array');
assert.same(a.byteLength, 4 * bytes, '#byteLength, passed array');
assert.arrayEqual(a, [1, 2, 3, 4], 'correct values, passed array');
a = new Typed({
0: 1,
1: 2,
2: 3,
3: 4,
length: 4
});
assert.same(a.byteOffset, 0, '#byteOffset, passed array-like');
assert.same(a.byteLength, 4 * bytes, '#byteLength, passed array-like');
assert.arrayEqual(a, [1, 2, 3, 4], 'correct values, passed array-like');
try {
a = new Typed({});
assert.same(a.byteOffset, 0, '#byteOffset, passed empty object (also array-like case)');
assert.same(a.byteLength, 0, '#byteLength, passed empty object (also array-like case)');
assert.arrayEqual(a, [], 'correct values, passed empty object (also array-like case)');
} catch (e$) {
e = e$;
assert.same(e, [], 'passed empty object (also array-like case)');
}
try {
a = new Typed(createIterable([1, 2, 3, 4]));
assert.same(a.byteOffset, 0, '#byteOffset, passed iterable');
assert.same(a.byteLength, 4 * bytes, '#byteLength, passed iterable');
assert.arrayEqual(a, [1, 2, 3, 4], 'correct values, passed iterable');
} catch (e$) {
e = e$;
assert.same(e, [1, 2, 3, 4], 'passed iterable');
}
a = new Typed(new Typed([1, 2, 3, 4]));
assert.same(a.byteOffset, 0, '#byteOffset, passed typed array');
assert.same(a.byteLength, 4 * bytes, '#byteLength, passed typed array');
assert.arrayEqual(a, [1, 2, 3, 4], 'correct values, passed typed array');
b = new Typed([1, 2, 3, 4]);
b[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8] = function(){
return createIterable([4, 3, 2, 1])[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8]();
};
a = new Typed(b);
assert.same(a.byteOffset, 0, '#byteOffset, passed typed array with custom iterator');
assert.same(a.byteLength, 4 * bytes, '#byteLength, passed typed array with custom iterator');
assert.arrayEqual(a, [1, 2, 3, 4], 'correct values, passed typed array with custom iterator');
a = new Typed(new ArrayBuffer(8));
assert.same(a.byteOffset, 0, '#byteOffset, passed buffer');
assert.same(a.byteLength, 8, '#byteLength, passed buffer');
assert.same(a.length, 8 / bytes, 'correct length, passed buffer');
a = new Typed(new ArrayBuffer(16), 8);
assert.same(a.byteOffset, 8, '#byteOffset, passed buffer and byteOffset');
assert.same(a.byteLength, 8, '#byteLength, passed buffer and byteOffset');
assert.same(a.length, 8 / bytes, 'correct length, passed buffer and byteOffset');
a = new Typed(new ArrayBuffer(24), 8, 8 / bytes);
assert.same(a.byteOffset, 8, '#byteOffset, passed buffer, byteOffset and length');
assert.same(a.byteLength, 8, '#byteLength, passed buffer, byteOffset and length');
assert.same(a.length, 8 / bytes, 'correct length, passed buffer, byteOffset and length');
a = new Typed(new ArrayBuffer(8), void 8);
assert.same(a.byteOffset, 0, '#byteOffset, passed buffer and undefined');
assert.same(a.byteLength, 8, '#byteLength, passed buffer and undefined');
assert.same(a.length, 8 / bytes, 'correct length, passed buffer and undefined');
a = new Typed(new ArrayBuffer(16), 8, void 8);
assert.same(a.byteOffset, 8, '#byteOffset, passed buffer, byteOffset and undefined');
assert.same(a.byteLength, 8, '#byteLength, passed buffer, byteOffset and undefined');
assert.same(a.length, 8 / bytes, 'correct length, passed buffer, byteOffset and undefined');
a = new Typed(new ArrayBuffer(8), 8);
assert.same(a.byteOffset, 8, '#byteOffset, passed buffer and byteOffset with buffer length');
assert.same(a.byteLength, 0, '#byteLength, passed buffer and byteOffset with buffer length');
assert.arrayEqual(a, [], 'correct values, passed buffer and byteOffset with buffer length');
if (NATIVE) {
assert.throws(function(){
new Typed(new ArrayBuffer(8), -1);
}, RangeError, 'If offset < 0, throw a RangeError exception');
if (bytes !== 1) {
assert.throws(function(){
new Typed(new ArrayBuffer(8), 3);
}, RangeError, 'If offset modulo elementSize ≠ 0, throw a RangeError exception');
assert.throws(function(){
new Typed(new ArrayBuffer(9));
}, RangeError, 'If bufferByteLength modulo elementSize ≠ 0, throw a RangeError exception');
}
assert.throws(function(){
new Typed(new ArrayBuffer(8), 16);
}, RangeError, 'If newByteLength < 0, throw a RangeError exception');
assert.throws(function(){
new Typed(new ArrayBuffer(24), 8, 24);
}, RangeError, 'If offset+newByteLength > bufferByteLength, throw a RangeError exception');
} else {
assert.throws(function(){
new Typed(new ArrayBuffer(8), -1);
}, 'If offset < 0, throw a RangeError exception');
if (bytes !== 1) {
assert.throws(function(){
new Typed(new ArrayBuffer(8), 3);
}, 'If offset modulo elementSize ≠ 0, throw a RangeError exception');
assert.throws(function(){
new Typed(new ArrayBuffer(9));
}, 'If bufferByteLength modulo elementSize ≠ 0, throw a RangeError exception');
}
assert.throws(function(){
new Typed(new ArrayBuffer(8), 16);
}, 'If newByteLength < 0, throw a RangeError exception');
assert.throws(function(){
new Typed(new ArrayBuffer(24), 8, 24);
}, 'If offset+newByteLength > bufferByteLength, throw a RangeError exception');
}
assert.throws(function(){
Typed(1);
}, TypeError, 'throws without `new`');
});
}
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Float32Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Float64Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Int16Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Int32Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Int8Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Uint16Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Uint32Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Uint8Array conversions', function(assert){
assert.ok(true);
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('Uint8ClampedArray conversions', function(assert){
var source, expected, array, i$, to$, i;
source = [-Infinity, -Number.MAX_VALUE, -1, -Number.MIN_VALUE, -0, 0, Number.MIN_VALUE, 1, 1.1, 1.9, 255, 255.1, 255.9, 256, Number.MAX_VALUE, Infinity, NaN];
expected = [0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0];
assert.arrayEqual(new Uint8ClampedArray(source), expected, 'conversion, constructor <- array');
array = new Uint8ClampedArray(1);
for (i$ = 0, to$ = source.length; i$ < to$; ++i$) {
i = i$;
array[0] = source[i];
assert.same(array[0], expected[i], 'conversion, setter');
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, i$, x$, ref$, len$, y$, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
if (DESCRIPTORS) {
test('DataView', function(assert){
var d;
assert.same(DataView, Object(DataView), 'is object');
NATIVE && assert.arity(DataView, 3);
NATIVE && assert.name(DataView, 'DataView');
NATIVE && assert.looksNative(DataView);
d = new DataView(new ArrayBuffer(8));
d.setUint32(0, 0x12345678);
assert.same(d.getUint32(0), 0x12345678, 'big endian/big endian');
d.setUint32(0, 0x12345678, true);
assert.same(d.getUint32(0, true), 0x12345678, 'little endian/little endian');
d.setUint32(0, 0x12345678, true);
assert.same(d.getUint32(0), 0x78563412, 'little endian/big endian');
d.setUint32(0, 0x12345678);
assert.same(d.getUint32(0, true), 0x78563412, 'big endian/little endian');
assert.throws(function(){
return new DataView({});
}, 'non-ArrayBuffer argument');
assert.throws(function(){
return new DataView('bogus');
}, TypeError, 'non-ArrayBuffer argument');
});
test('DataView accessors', function(assert){
var u, d;
u = new Uint8Array(8);
d = new DataView(u.buffer);
assert.arrayEqual(u, [0, 0, 0, 0, 0, 0, 0, 0]);
d.setUint8(0, 255);
assert.arrayEqual(u, [0xff, 0, 0, 0, 0, 0, 0, 0]);
d.setInt8(1, -1);
assert.arrayEqual(u, [0xff, 0xff, 0, 0, 0, 0, 0, 0]);
d.setUint16(2, 0x1234);
assert.arrayEqual(u, [0xff, 0xff, 0x12, 0x34, 0, 0, 0, 0]);
d.setInt16(4, -1);
assert.arrayEqual(u, [0xff, 0xff, 0x12, 0x34, 0xff, 0xff, 0, 0]);
d.setUint32(1, 0x12345678);
assert.arrayEqual(u, [0xff, 0x12, 0x34, 0x56, 0x78, 0xff, 0, 0]);
d.setInt32(4, -2023406815);
assert.arrayEqual(u, [0xff, 0x12, 0x34, 0x56, 0x87, 0x65, 0x43, 0x21]);
d.setFloat32(2, 1.2e+38);
assert.arrayEqual(u, [0xff, 0x12, 0x7e, 0xb4, 0x8e, 0x52, 0x43, 0x21]);
d.setFloat64(0, -1.2345678e+301);
assert.arrayEqual(u, [0xfe, 0x72, 0x6f, 0x51, 0x5f, 0x61, 0x77, 0xe5]);
u.set([0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87]);
assert.same(d.getUint8(0), 128);
assert.same(d.getInt8(1), -127);
assert.same(d.getUint16(2), 33411);
assert.same(d.getInt16(3), -31868);
assert.same(d.getUint32(4), 2223343239);
assert.same(d.getInt32(2), -2105310075);
assert.same(d.getFloat32(2), -1.932478247535851e-37);
assert.same(d.getFloat64(0), -3.116851295377095e-306);
});
test('DataView endian', function(assert){
var rawbuf, d;
rawbuf = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]).buffer;
d = new DataView(rawbuf);
assert.same(d.byteLength, 8, 'buffer');
assert.same(d.byteOffset, 0, 'buffer');
assert.throws(function(){
return d.getUint8(-2);
});
assert.throws(function(){
return d.getUint8(8);
}, 'bounds for buffer');
assert.throws(function(){
return d.setUint8(-2, 0);
}, 'bounds for buffer');
assert.throws(function(){
return d.setUint8(8, 0);
}, 'bounds for buffer');
d = new DataView(rawbuf, 2);
assert.same(d.byteLength, 6, 'buffer, byteOffset');
assert.same(d.byteOffset, 2, 'buffer, byteOffset');
assert.same(d.getUint8(5), 7, 'buffer, byteOffset');
assert.throws(function(){
return d.getUint8(-2);
}, 'bounds for buffer, byteOffset');
assert.throws(function(){
return d.getUint8(6);
}, 'bounds for buffer, byteOffset');
assert.throws(function(){
return d.setUint8(-2, 0);
}, 'bounds for buffer, byteOffset');
assert.throws(function(){
return d.setUint8(6, 0);
}, 'bounds for buffer, byteOffset');
if (NATIVE) {
d = new DataView(rawbuf, 8);
assert.same(d.byteLength, 0, 'buffer, byteOffset');
}
assert.throws(function(){
return new DataView(rawbuf, -1);
}, 'invalid byteOffset');
assert.throws(function(){
return new DataView(rawbuf, 9);
}, 'invalid byteOffset');
d = new DataView(rawbuf, 2, 4);
assert.same(d.byteLength, 4, 'buffer, byteOffset, length');
assert.same(d.byteOffset, 2, 'buffer, byteOffset, length');
assert.same(d.getUint8(3), 5, 'buffer, byteOffset, length');
assert.throws(function(){
return d.getUint8(-2);
}, 'bounds for buffer, byteOffset, length');
assert.throws(function(){
return d.getUint8(4);
}, 'bounds for buffer, byteOffset, length');
assert.throws(function(){
return d.setUint8(-2, 0);
}, 'bounds for buffer, byteOffset, length');
assert.throws(function(){
return d.setUint8(4, 0);
}, 'bounds for buffer, byteOffset, length');
assert.throws(function(){
return new DataView(rawbuf, 0, 9);
}, 'invalid byteOffset+length');
assert.throws(function(){
return new DataView(rawbuf, 8, 1);
}, 'invalid byteOffset+length');
assert.throws(function(){
return new DataView(rawbuf, 9, -1);
}, 'invalid byteOffset+length');
});
for (i$ = 0, len$ = (ref$ = ['getUint8', 'getInt8', 'getUint16', 'getInt16', 'getUint32', 'getInt32', 'getFloat32', 'getFloat64']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
(fn$.call(this, x$));
}
for (i$ = 0, len$ = (ref$ = ['setUint8', 'setInt8', 'setUint16', 'setInt16', 'setUint32', 'setInt32', 'setFloat32', 'setFloat64']).length; i$ < len$; ++i$) {
y$ = ref$[i$];
(fn1$.call(this, y$));
}
}
function fn$(name){
var this$ = this;
test('DataView#' + name, function(assert){
assert.isFunction(DataView.prototype[name]);
NATIVE && assert.arity(DataView.prototype[name], 1);
assert.name(DataView.prototype[name], name);
assert.looksNative(DataView.prototype[name]);
assert.same(new DataView(new ArrayBuffer(8))[name](0), 0, 'returns element');
});
}
function fn1$(name){
var this$ = this;
test('DataView#' + name, function(assert){
assert.isFunction(DataView.prototype[name]);
NATIVE && assert.arity(DataView.prototype[name], 2);
assert.name(DataView.prototype[name], name);
assert.looksNative(DataView.prototype[name]);
assert.same(new DataView(new ArrayBuffer(8))[name](0, 0), void 8, 'void');
});
}
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.copyWithin', function(assert){
var global, i$, x$, ref$, len$, Typed, a;
global = Function('return this')();
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.copyWithin, x$ + "::copyWithin is function");
assert.arity(Typed.prototype.copyWithin, 2, x$ + "::copyWithin arity is 2");
assert.name(Typed.prototype.copyWithin, 'copyWithin', x$ + "::copyWithin name is 'copyWithin'");
assert.looksNative(Typed.prototype.copyWithin, x$ + "::copyWithin looks native");
assert.strictEqual(a = new Typed(5).copyWithin(0), a, 'return this');
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(0, 3), [4, 5, 3, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(1, 3), [1, 4, 5, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(1, 2), [1, 3, 4, 5, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(2, 2), [1, 2, 3, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(0, 3, 4), [4, 2, 3, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(1, 3, 4), [1, 4, 3, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(1, 2, 4), [1, 3, 4, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(0, -2), [4, 5, 3, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(0, -2, -1), [4, 2, 3, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(-4, -3, -2), [1, 3, 3, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(-4, -3, -1), [1, 3, 4, 4, 5]);
assert.arrayEqual(new Typed([1, 2, 3, 4, 5]).copyWithin(-4, -3), [1, 3, 4, 5, 5]);
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.fill.call([0], 1);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.every', function(assert){
var i$, x$, ref$, len$, Typed, a, ctx, v, k, arr;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.every, x$ + "::every is function");
assert.arity(Typed.prototype.every, 1, x$ + "::every arity is 1");
assert.name(Typed.prototype.every, 'every', x$ + "::every name is 'every'");
assert.looksNative(Typed.prototype.every, x$ + "::every looks native");
(a = new Typed([1])).every(fn$, ctx = {});
assert.ok(new Typed([1, 2, 3]).every(fn1$));
assert.ok(new Typed([1, 2, 3]).every((fn2$)));
assert.ok(!new Typed([1, 2, 3]).every((fn3$)));
assert.ok(!new Typed([1, 2, 3]).every(fn4$));
assert.ok(new Typed([1, 2, 3]).every(fn5$, 1));
v = '';
k = '';
new Typed([1, 2, 3]).every(fn6$);
assert.same(v, '123');
assert.same(k, '012');
assert.ok((arr = new Typed([1, 2, 3])).every(fn7$));
assert.throws(fn8$, "isn't generic");
}
function fn$(val, key, that){
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, a, 'correct link to array in callback');
return assert.same(this, ctx, 'correct callback context');
}
function fn1$(it){
return typeof it === 'number';
}
function fn2$(it){
return it < 4;
}
function fn3$(it){
return it < 3;
}
function fn4$(it){
return typeof it === 'string';
}
function fn5$(){
return +this === 1;
}
function fn6$(a, b){
v += a;
k += b;
return true;
}
function fn7$(){
return arguments[2] === arr;
}
function fn8$(){
Typed.prototype.every.call([0], function(){
return true;
});
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.fill', function(assert){
var i$, x$, ref$, len$, Typed, a;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.fill, x$ + "::fill is function");
assert.arity(Typed.prototype.fill, 1, x$ + "::fill arity is 1");
assert.name(Typed.prototype.fill, 'fill', x$ + "::fill name is 'fill'");
assert.looksNative(Typed.prototype.fill, x$ + "::fill looks native");
assert.strictEqual(a = new Typed(5).fill(5), a, 'return this');
assert.arrayEqual(new Typed(5).fill(5), [5, 5, 5, 5, 5], 'basic');
assert.arrayEqual(new Typed(5).fill(5, 1), [0, 5, 5, 5, 5], 'start index');
assert.arrayEqual(new Typed(5).fill(5, 1, 4), [0, 5, 5, 5, 0], 'end index');
assert.arrayEqual(new Typed(5).fill(5, 6, 1), [0, 0, 0, 0, 0], 'start > end');
assert.arrayEqual(new Typed(5).fill(5, -3, 4), [0, 0, 5, 5, 0], 'negative start index');
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.fill.call([0], 1);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.filter', function(assert){
var i$, x$, ref$, len$, Typed, a, ctx, instance, v, k;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.filter, x$ + "::filter is function");
assert.arity(Typed.prototype.filter, 1, x$ + "::filter arity is 1");
assert.name(Typed.prototype.filter, 'filter', x$ + "::filter name is 'filter'");
assert.looksNative(Typed.prototype.filter, x$ + "::filter looks native");
(a = new Typed([1])).filter(fn$, ctx = {});
instance = new Typed([1, 2, 3, 4, 5, 6, 7, 8, 9]).filter((fn1$));
assert.ok(instance instanceof Typed, 'correct instance');
assert.arrayEqual(instance, [1, 3, 5, 7, 9], 'works');
v = '';
k = '';
new Typed([1, 2, 3]).filter(fn2$);
assert.same(v, '123');
assert.same(k, '012');
assert.throws(fn3$, "isn't generic");
}
function fn$(val, key, that){
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, a, 'correct link to array in callback');
return assert.same(this, ctx, 'correct callback context');
}
function fn1$(it){
return it % 2;
}
function fn2$(a, b){
v += a;
k += b;
}
function fn3$(){
Typed.prototype.filter.call([0], function(){
return true;
});
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.findIndex', function(assert){
var i$, x$, ref$, len$, Typed, a, ctx, v, k;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.findIndex, x$ + "::findIndex is function");
assert.arity(Typed.prototype.findIndex, 1, x$ + "::findIndex arity is 1");
assert.name(Typed.prototype.findIndex, 'findIndex', x$ + "::findIndex name is 'findIndex'");
assert.looksNative(Typed.prototype.findIndex, x$ + "::findIndex looks native");
(a = new Typed([1])).findIndex(fn$, ctx = {});
assert.same(new Typed([1, 2, 3]).findIndex(fn1$), 1);
assert.same(new Typed([1, 2, 3]).findIndex((fn2$)), -1);
v = '';
k = '';
new Typed([1, 2, 3]).findIndex(fn3$);
assert.same(v, '123');
assert.same(k, '012');
assert.throws(fn4$, "isn't generic");
}
function fn$(val, key, that){
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, a, 'correct link to array in callback');
return assert.same(this, ctx, 'correct callback context');
}
function fn1$(it){
return !(it % 2);
}
function fn2$(it){
return it === 4;
}
function fn3$(a, b){
v += a;
k += b;
}
function fn4$(){
Typed.prototype.findIndex.call([0], function(){
return true;
});
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.find', function(assert){
var i$, x$, ref$, len$, Typed, a, ctx, v, k;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.find, x$ + "::find is function");
assert.arity(Typed.prototype.find, 1, x$ + "::find arity is 1");
assert.name(Typed.prototype.find, 'find', x$ + "::find name is 'find'");
assert.looksNative(Typed.prototype.find, x$ + "::find looks native");
(a = new Typed([1])).find(fn$, ctx = {});
assert.same(new Typed([1, 2, 3]).find(fn1$), 2);
assert.same(new Typed([1, 2, 3]).find((fn2$)), void 8);
v = '';
k = '';
new Typed([1, 2, 3]).find(fn3$);
assert.same(v, '123');
assert.same(k, '012');
assert.throws(fn4$, "isn't generic");
}
function fn$(val, key, that){
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, a, 'correct link to array in callback');
return assert.same(this, ctx, 'correct callback context');
}
function fn1$(it){
return !(it % 2);
}
function fn2$(it){
return it === 4;
}
function fn3$(a, b){
v += a;
k += b;
}
function fn4$(){
Typed.prototype.find.call([0], function(){
return true;
});
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.forEach', function(assert){
var i$, x$, ref$, len$, Typed, a, ctx, v, k;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.forEach, x$ + "::forEach is function");
assert.arity(Typed.prototype.forEach, 1, x$ + "::forEach arity is 1");
assert.name(Typed.prototype.forEach, 'forEach', x$ + "::forEach name is 'forEach'");
assert.looksNative(Typed.prototype.forEach, x$ + "::forEach looks native");
assert.same(new Typed([1]).forEach(fn$), void 8, 'void');
(a = new Typed([1])).forEach(fn1$, ctx = {});
v = '';
k = '';
new Typed([1, 2, 3]).forEach(fn2$);
assert.same(v, '123');
assert.same(k, '012');
assert.throws(fn3$, "isn't generic");
}
function fn$(){}
function fn1$(val, key, that){
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, a, 'correct link to array in callback');
return assert.same(this, ctx, 'correct callback context');
}
function fn2$(a, b){
v += a;
k += b;
}
function fn3$(){
Typed.prototype.forEach.call([0], function(){
return true;
});
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArray%.from', function(assert){
var i$, x$, ref$, len$, Typed, inst, O;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.from, x$ + ".from is function");
assert.arity(Typed.from, 1, x$ + ".from arity is 1");
assert.name(Typed.from, 'from', x$ + ".from name is 'from'");
assert.looksNative(Typed.from, x$ + ".from looks native");
inst = Typed.from([1, 2, 3]);
assert.ok(inst instanceof Typed, 'correct instance with array');
assert.arrayEqual(inst, [1, 2, 3], 'correct elements with array');
inst = Typed.from({
0: 1,
1: 2,
2: 3,
length: 3
});
assert.ok(inst instanceof Typed, 'correct instance with array-like');
assert.arrayEqual(inst, [1, 2, 3], 'correct elements with array-like');
inst = Typed.from(createIterable([1, 2, 3]));
assert.ok(inst instanceof Typed, 'correct instance with iterable');
assert.arrayEqual(inst, [1, 2, 3], 'correct elements with iterable');
assert.arrayEqual(Typed.from([1, 2, 3], fn$), [1, 4, 9], 'accept callback');
Typed.from([1], fn1$, O = {});
assert.throws(fn2$, "isn't generic #1");
if (NATIVE) {
assert.throws(fn3$, "isn't generic #2");
assert.ok((fn4$()), 'uses ToLength');
}
}
function fn$(it){
return it * it;
}
function fn1$(a, b){
assert.same(arguments.length, 2, 'correct number of callback arguments');
assert.same(a, 1, 'correct value in callback');
assert.same(b, 0, 'correct index in callback');
return assert.same(this, O, 'correct callback context');
}
function fn2$(){
Typed.from.call(void 8, []);
}
function fn3$(){
Typed.from.call(Array, []);
}
function fn4$(){
try {
return Typed.from({
length: -1,
0: 1
}, function(){
throw 42;
});
} catch (e$) {}
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.indexOf', function(assert){
var i$, x$, ref$, len$, Typed;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.indexOf, x$ + "::indexOf is function");
assert.arity(Typed.prototype.indexOf, 1, x$ + "::indexOf arity is 1");
assert.name(Typed.prototype.indexOf, 'indexOf', x$ + "::indexOf name is 'indexOf'");
assert.looksNative(Typed.prototype.indexOf, x$ + "::indexOf looks native");
assert.same(new Typed([1, 1, 1]).indexOf(1), 0);
assert.same(new Typed([1, 2, 3]).indexOf(1, 1), -1);
assert.same(new Typed([1, 2, 3]).indexOf(2, 1), 1);
assert.same(new Typed([1, 2, 3]).indexOf(2, -1), -1);
assert.same(new Typed([1, 2, 3]).indexOf(2, -2), 1);
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.indexOf.call([1, 2], 1);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, arrays;
module = QUnit.module, test = QUnit.test;
module('ES6');
arrays = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray'];
DESCRIPTORS && test('%TypedArrayPrototype%.keys', function(assert){
var i$, x$, ref$, len$, Typed, iter;
for (i$ = 0, len$ = (ref$ = arrays).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.keys, x$ + "::keys is function");
assert.arity(Typed.prototype.keys, 0, x$ + "::keys arity is 0");
assert.name(Typed.prototype.keys, 'keys', x$ + "::keys name is 'keys'");
assert.looksNative(Typed.prototype.keys, x$ + "::keys looks native");
iter = new Typed([1, 2, 3]).keys();
assert.isIterator(iter);
assert.isIterable(iter);
assert.strictEqual(iter[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.toStringTag : void 8], 'Array Iterator');
assert.deepEqual(iter.next(), {
value: 0,
done: false
}, 'step 1');
assert.deepEqual(iter.next(), {
value: 1,
done: false
}, 'step 2');
assert.deepEqual(iter.next(), {
value: 2,
done: false
}, 'step 3');
assert.deepEqual(iter.next(), {
value: void 8,
done: true
}, 'done');
NATIVE && assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.keys.call([1, 2]);
}
});
DESCRIPTORS && test('%TypedArrayPrototype%.values', function(assert){
var i$, x$, ref$, len$, Typed, iter;
for (i$ = 0, len$ = (ref$ = arrays).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.values, x$ + "::values is function");
assert.arity(Typed.prototype.values, 0, x$ + "::values arity is 0");
assert.name(Typed.prototype.values, 'values', x$ + "::values name is 'values'");
assert.looksNative(Typed.prototype.values, x$ + "::values looks native");
iter = new Typed([1, 2, 3]).values();
assert.isIterator(iter);
assert.isIterable(iter);
assert.strictEqual(iter[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.toStringTag : void 8], 'Array Iterator');
assert.deepEqual(iter.next(), {
value: 1,
done: false
}, 'step 1');
assert.deepEqual(iter.next(), {
value: 2,
done: false
}, 'step 2');
assert.deepEqual(iter.next(), {
value: 3,
done: false
}, 'step 3');
assert.deepEqual(iter.next(), {
value: void 8,
done: true
}, 'done');
NATIVE && assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.values.call([1, 2]);
}
});
DESCRIPTORS && test('%TypedArrayPrototype%.entries', function(assert){
var i$, x$, ref$, len$, Typed, iter;
for (i$ = 0, len$ = (ref$ = arrays).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.entries, x$ + "::entries is function");
assert.arity(Typed.prototype.entries, 0, x$ + "::entries arity is 0");
assert.name(Typed.prototype.entries, 'entries', x$ + "::entries name is 'entries'");
assert.looksNative(Typed.prototype.entries, x$ + "::entries looks native");
iter = new Typed([1, 2, 3]).entries();
assert.isIterator(iter);
assert.isIterable(iter);
assert.strictEqual(iter[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.toStringTag : void 8], 'Array Iterator');
assert.deepEqual(iter.next(), {
value: [0, 1],
done: false
}, 'step 1');
assert.deepEqual(iter.next(), {
value: [1, 2],
done: false
}, 'step 2');
assert.deepEqual(iter.next(), {
value: [2, 3],
done: false
}, 'step 3');
assert.deepEqual(iter.next(), {
value: void 8,
done: true
}, 'done');
NATIVE && assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.entries.call([1, 2]);
}
});
DESCRIPTORS && test('%TypedArrayPrototype%.@@iterator', function(assert){
var i$, x$, ref$, len$, Typed, iter;
for (i$ = 0, len$ = (ref$ = arrays).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isIterable(Typed.prototype, x$ + " is itrable");
assert.arity(Typed.prototype[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8], 0, x$ + "::@@iterator arity is 0");
assert.name(Typed.prototype[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8], 'values', x$ + "::@@iterator name is 'values'");
assert.looksNative(Typed.prototype[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8], x$ + "::@@iterator looks native");
assert.strictEqual(Typed.prototype[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8], Typed.prototype.values);
iter = new Typed([1, 2, 3])[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8]();
assert.isIterator(iter);
assert.isIterable(iter);
assert.strictEqual(iter[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.toStringTag : void 8], 'Array Iterator');
assert.deepEqual(iter.next(), {
value: 1,
done: false
}, 'step 1');
assert.deepEqual(iter.next(), {
value: 2,
done: false
}, 'step 2');
assert.deepEqual(iter.next(), {
value: 3,
done: false
}, 'step 3');
assert.deepEqual(iter.next(), {
value: void 8,
done: true
}, 'done');
NATIVE && assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype[typeof Symbol != 'undefined' && Symbol !== null ? Symbol.iterator : void 8].call([1, 2]);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.join', function(assert){
var i$, x$, ref$, len$, Typed;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.join, x$ + "::join is function");
assert.arity(Typed.prototype.join, 1, x$ + "::join arity is 1");
assert.name(Typed.prototype.join, 'join', x$ + "::join name is 'join'");
assert.looksNative(Typed.prototype.join, x$ + "::join looks native");
assert.same(new Typed([1, 2, 3]).join('|'), '1|2|3', 'works #1');
assert.same(new Typed([1, 2, 3]).join(), '1,2,3', 'works #2');
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.join.call([1, 2, 3]);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.lastIndexOf', function(assert){
var i$, x$, ref$, len$, Typed;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.lastIndexOf, x$ + "::lastIndexOf is function");
assert.arity(Typed.prototype.lastIndexOf, 1, x$ + "::lastIndexOf arity is 1");
assert.name(Typed.prototype.lastIndexOf, 'lastIndexOf', x$ + "::lastIndexOf name is 'lastIndexOf'");
assert.looksNative(Typed.prototype.lastIndexOf, x$ + "::lastIndexOf looks native");
assert.same(new Typed([1, 1, 1]).lastIndexOf(1), 2);
assert.same(new Typed([1, 2, 3]).lastIndexOf(3, 1), -1);
assert.same(new Typed([1, 2, 3]).lastIndexOf(2, 1), 1);
assert.same(new Typed([1, 2, 3]).lastIndexOf(2, -3), -1);
assert.same(new Typed([1, 2, 3]).lastIndexOf(2, -2), 1);
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.lastIndexOf.call([1, 2], 1);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.map', function(assert){
var i$, x$, ref$, len$, Typed, a, ctx, instance, v, k;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.map, x$ + "::map is function");
assert.arity(Typed.prototype.map, 1, x$ + "::map arity is 1");
assert.name(Typed.prototype.map, 'map', x$ + "::map name is 'map'");
assert.looksNative(Typed.prototype.map, x$ + "::map looks native");
(a = new Typed([1])).map(fn$, ctx = {});
instance = new Typed([1, 2, 3, 4, 5]).map((fn1$));
assert.ok(instance instanceof Typed, 'correct instance');
assert.arrayEqual(instance, [2, 4, 6, 8, 10], 'works');
v = '';
k = '';
new Typed([1, 2, 3]).map(fn2$);
assert.same(v, '123');
assert.same(k, '012');
assert.throws(fn3$, "isn't generic");
}
function fn$(val, key, that){
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, a, 'correct link to array in callback');
return assert.same(this, ctx, 'correct callback context');
}
function fn1$(it){
return it * 2;
}
function fn2$(a, b){
v += a;
k += b;
}
function fn3$(){
Typed.prototype.map.call([0], function(){
return true;
});
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArray%.of', function(assert){
var i$, x$, ref$, len$, Typed, inst;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.of, x$ + ".of is function");
assert.arity(Typed.of, 0, x$ + ".of arity is 0");
assert.name(Typed.of, 'of', x$ + ".of name is 'of'");
assert.looksNative(Typed.of, x$ + ".of looks native");
inst = Typed.of();
assert.ok(inst instanceof Typed, 'correct instance with 0 arguments');
assert.arrayEqual(inst, [], 'correct elements with 0 arguments');
inst = Typed.of(1);
assert.ok(inst instanceof Typed, 'correct instance with 1 argument');
assert.arrayEqual(inst, [1], 'correct elements with 1 argument');
inst = Typed.of(1, 2, 3);
assert.ok(inst instanceof Typed, 'correct instance with several arguments');
assert.arrayEqual(inst, [1, 2, 3], 'correct elements with several arguments');
assert.throws(fn$, "isn't generic #1");
NATIVE && assert.throws(fn1$, "isn't generic #2");
}
function fn$(){
Typed.of.call(void 8, 1);
}
function fn1$(){
Typed.of.call(Array, 1);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.reduceRight', function(assert){
var i$, x$, ref$, len$, Typed, a, accumulator, v, k, fn1$ = curry$(function(x$, y$){
return x$ + y$;
}), fn3$ = curry$(function(x$, y$){
return x$ + y$;
});
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.reduceRight, x$ + "::reduceRight is function");
assert.arity(Typed.prototype.reduceRight, 1, x$ + "::reduceRight arity is 1");
assert.name(Typed.prototype.reduceRight, 'reduceRight', x$ + "::reduceRight name is 'reduceRight'");
assert.looksNative(Typed.prototype.reduceRight, x$ + "::reduceRight looks native");
(a = new Typed([1])).reduceRight(fn$, accumulator = {});
assert.same(new Typed([1, 2, 3]).reduceRight(fn1$, 1), 7, 'works with initial accumulator');
(a = new Typed([1, 2])).reduceRight(fn2$);
assert.same(new Typed([1, 2, 3]).reduceRight(fn3$), 6, 'works without initial accumulator');
v = '';
k = '';
new Typed([1, 2, 3]).reduceRight(fn4$, 0);
assert.same(v, '321', 'correct order #1');
assert.same(k, '210', 'correct order #2');
assert.throws(fn5$, "isn't generic");
}
function fn$(memo, val, key, that){
assert.same(arguments.length, 4, 'correct number of callback arguments');
assert.same(memo, accumulator, 'correct callback accumulator');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
return assert.same(that, a, 'correct link to array in callback');
}
function fn2$(memo, val, key, that){
assert.same(memo, 2, 'correct default accumulator');
assert.same(val, 1, 'correct start value without initial accumulator');
return assert.same(key, 0, 'correct start index without initial accumulator');
}
function fn4$(memo, a, b){
v += a;
k += b;
}
function fn5$(){
Typed.prototype.reduceRight.call([0], function(){
return true;
});
}
});
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.reduce', function(assert){
var i$, x$, ref$, len$, Typed, a, accumulator, v, k, fn1$ = curry$(function(x$, y$){
return x$ + y$;
}), fn3$ = curry$(function(x$, y$){
return x$ + y$;
});
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.reduce, x$ + "::reduce is function");
assert.arity(Typed.prototype.reduce, 1, x$ + "::reduce arity is 1");
assert.name(Typed.prototype.reduce, 'reduce', x$ + "::reduce name is 'reduce'");
assert.looksNative(Typed.prototype.reduce, x$ + "::reduce looks native");
(a = new Typed([1])).reduce(fn$, accumulator = {});
assert.same(new Typed([1, 2, 3]).reduce(fn1$, 1), 7, 'works with initial accumulator');
(a = new Typed([1, 2])).reduce(fn2$);
assert.same(new Typed([1, 2, 3]).reduce(fn3$), 6, 'works without initial accumulator');
v = '';
k = '';
new Typed([1, 2, 3]).reduce(fn4$, 0);
assert.same(v, '123', 'correct order #1');
assert.same(k, '012', 'correct order #2');
assert.throws(fn5$, "isn't generic");
}
function fn$(memo, val, key, that){
assert.same(arguments.length, 4, 'correct number of callback arguments');
assert.same(memo, accumulator, 'correct callback accumulator');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
return assert.same(that, a, 'correct link to array in callback');
}
function fn2$(memo, val, key, that){
assert.same(memo, 1, 'correct default accumulator');
assert.same(val, 2, 'correct start value without initial accumulator');
return assert.same(key, 1, 'correct start index without initial accumulator');
}
function fn4$(memo, a, b){
v += a;
k += b;
}
function fn5$(){
Typed.prototype.reduce.call([0], function(){
return true;
});
}
});
function curry$(f, bound){
var context,
_curry = function(args) {
return f.length > 1 ? function(){
var params = args ? args.concat() : [];
context = bound ? context || this : this;
return params.push.apply(params, arguments) <
f.length && arguments.length ?
_curry.call(context, params) : f.apply(context, params);
} : f;
};
return _curry();
}
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.reverse', function(assert){
var i$, x$, ref$, len$, Typed, a;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.reverse, x$ + "::reverse is function");
assert.arity(Typed.prototype.reverse, 0, x$ + "::reverse arity is 0");
assert.name(Typed.prototype.reverse, 'reverse', x$ + "::reverse name is 'reverse'");
assert.looksNative(Typed.prototype.reverse, x$ + "::reverse looks native");
assert.same((a = new Typed([1, 2])).reverse(), a, 'return this');
assert.arrayEqual(new Typed([1, 2, 3, 4]).reverse(), [4, 3, 2, 1], 'works #1');
assert.arrayEqual(new Typed([1, 2, 3]).reverse(), [3, 2, 1], 'works #2');
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.reverse.call([1, 2]);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.set', function(assert){
var i$, x$, ref$, len$, Typed, a, b, y$;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.set, x$ + "::set is function");
NATIVE && assert.arity(Typed.prototype.set, 1, x$ + "::set arity is 1");
assert.name(Typed.prototype.set, 'set', x$ + "::set name is 'subarray'");
assert.looksNative(Typed.prototype.set, x$ + "::set looks native");
assert.same(new Typed(1).set([1]), void 8, 'void');
a = new Typed([1, 2, 3, 4, 5]);
b = new Typed(5);
b.set(a);
assert.arrayEqual(b, [1, 2, 3, 4, 5]);
assert.throws(fn$);
assert.throws(fn1$);
b.set(new Typed([99, 98]), 2);
assert.arrayEqual(b, [1, 2, 99, 98, 5]);
b.set(new Typed([99, 98, 97]), 2);
assert.arrayEqual(b, [1, 2, 99, 98, 97]);
assert.throws(fn2$);
assert.throws(fn3$);
assert.arrayEqual((y$ = new Typed(2), y$.set({
length: 2,
0: 1,
1: 2
}), y$), [1, 2]);
assert.throws(fn4$, "isn't generic");
}
function fn$(){
b.set(a, 1);
}
function fn1$(){
b.set(a, -1);
}
function fn2$(){
b.set(new Typed([99, 98, 97, 96]), 2);
}
function fn3$(){
b.set([101, 102, 103, 104], 4);
}
function fn4$(){
Typed.prototype.set.call([1, 2, 3], [1]);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.slice', function(assert){
var i$, x$, ref$, len$, Typed, arr;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.slice, x$ + "::slice is function");
NATIVE && assert.arity(Typed.prototype.slice, 2, x$ + "::slice arity is 2");
assert.name(Typed.prototype.slice, 'slice', x$ + "::slice name is 'subarray'");
assert.looksNative(Typed.prototype.slice, x$ + "::slice looks native");
arr = new Typed([1, 2, 3, 4, 5]);
assert.ok(arr.slice() !== arr, 'returns new array');
assert.ok(arr.slice() instanceof Typed, 'correct instance');
assert.ok(arr.slice().buffer !== arr.buffer, 'with new buffer');
assert.arrayEqual(arr.slice(), arr);
assert.arrayEqual(arr.slice(1, 3), [2, 3]);
assert.arrayEqual(arr.slice(1, void 8), [2, 3, 4, 5]);
assert.arrayEqual(arr.slice(1, -1), [2, 3, 4]);
assert.arrayEqual(arr.slice(-2, -1), [4]);
assert.arrayEqual(arr.slice(-2, -3), []);
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.slice.call([1, 2, 3], 1);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.some', function(assert){
var i$, x$, ref$, len$, Typed, a, ctx, v, k, arr;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.some, x$ + "::some is function");
assert.arity(Typed.prototype.some, 1, x$ + "::some arity is 1");
assert.name(Typed.prototype.some, 'some', x$ + "::some name is 'some'");
assert.looksNative(Typed.prototype.some, x$ + "::some looks native");
(a = new Typed([1])).some(fn$, ctx = {});
assert.ok(new Typed([1, 2, 3]).some(fn1$));
assert.ok(new Typed([1, 2, 3]).some((fn2$)));
assert.ok(!new Typed([1, 2, 3]).some((fn3$)));
assert.ok(!new Typed([1, 2, 3]).some(fn4$));
v = '';
k = '';
new Typed([1, 2, 3]).some(fn5$);
assert.same(v, '123');
assert.same(k, '012');
assert.ok((arr = new Typed([1, 2, 3])).some(fn6$));
assert.throws(fn7$, "isn't generic");
}
function fn$(val, key, that){
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(val, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, a, 'correct link to array in callback');
return assert.same(this, ctx, 'correct callback context');
}
function fn1$(it){
return typeof it === 'number';
}
function fn2$(it){
return it < 3;
}
function fn3$(it){
return it < 0;
}
function fn4$(it){
return typeof it === 'string';
}
function fn5$(a, b){
v += a;
k += b;
}
function fn6$(){
return arguments[2] === arr;
}
function fn7$(){
Typed.prototype.some.call([0], function(){
return true;
});
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.subarray', function(assert){
var i$, x$, ref$, len$, Typed, a, b;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.subarray, x$ + "::subarray is function");
NATIVE && assert.arity(Typed.prototype.subarray, 2, x$ + "::subarray arity is 2");
assert.name(Typed.prototype.subarray, 'subarray', x$ + "::subarray name is 'subarray'");
assert.looksNative(Typed.prototype.subarray, x$ + "::subarray looks native");
a = new Typed([1, 2, 3, 4, 5]);
b = a.subarray(3);
assert.ok(a !== b, 'creates new array');
assert.ok(b instanceof Typed, "instance " + x$);
assert.same(a.buffer, b.buffer, 'with the same buffer');
assert.arrayEqual(b, [4, 5]);
assert.arrayEqual(a.subarray(1, 3), [2, 3]);
assert.arrayEqual(a.subarray(-3), [3, 4, 5]);
assert.arrayEqual(a.subarray(-3, -1), [3, 4]);
assert.arrayEqual(a.subarray(3, 2), []);
assert.arrayEqual(a.subarray(-2, -3), []);
assert.arrayEqual(a.subarray(4, 1), []);
assert.arrayEqual(a.subarray(-1, -4), []);
assert.arrayEqual(a.subarray(1).subarray(1), [3, 4, 5]);
assert.arrayEqual(a.subarray(1, 4).subarray(1, 2), [3]);
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.subarray.call([1, 2, 3], 1);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.toLocaleString', function(assert){
var i$, x$, ref$, len$, Typed;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.toLocaleString, x$ + "::toLocaleString is function");
assert.arity(Typed.prototype.toLocaleString, 0, x$ + "::toLocaleString arity is 0");
assert.name(Typed.prototype.toLocaleString, 'toLocaleString', x$ + "::toLocaleString name is 'toLocaleString'");
assert.looksNative(Typed.prototype.toLocaleString, x$ + "::toLocaleString looks native");
assert.same(new Typed([1, 2, 3]).toLocaleString(), [1, 2, 3].toLocaleString(), 'works');
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.toLocaleString.call([1, 2, 3]);
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES6');
DESCRIPTORS && test('%TypedArrayPrototype%.toString', function(assert){
var i$, x$, ref$, len$, Typed;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.toString, x$ + "::toString is function");
assert.arity(Typed.prototype.toString, 0, x$ + "::toString arity is 0");
assert.name(Typed.prototype.toString, 'toString', x$ + "::toString name is 'toString'");
assert.looksNative(Typed.prototype.toString, x$ + "::toString looks native");
assert.same(new Typed([1, 2, 3]).toString(), '1,2,3', 'works');
assert.same(Typed.prototype.toString.call([1, 2, 3]), '1,2,3', "generic");
}
});
}).call(this);
// Generated by LiveScript 1.3.1
(function(){
var module, test, this$ = this;
module = QUnit.module, test = QUnit.test;
module('ES7');
DESCRIPTORS && test('%TypedArrayPrototype%.includes', function(assert){
var i$, x$, ref$, len$, Typed;
for (i$ = 0, len$ = (ref$ = ['Float32Array', 'Float64Array', 'Int8Array', 'Int16Array', 'Int32Array', 'Uint8Array', 'Uint16Array', 'Uint32Array', 'Uint8ClampedArray']).length; i$ < len$; ++i$) {
x$ = ref$[i$];
Typed = global[x$];
assert.isFunction(Typed.prototype.includes, x$ + "::includes is function");
assert.arity(Typed.prototype.includes, 1, x$ + "::includes arity is 1");
assert.name(Typed.prototype.includes, 'includes', x$ + "::includes name is 'includes'");
assert.looksNative(Typed.prototype.includes, x$ + "::includes looks native");
assert.same(new Typed([1, 1, 1]).includes(1), true);
assert.same(new Typed([1, 1, 1]).includes(2), false);
assert.same(new Typed([1, 2, 3]).includes(1, 1), false);
assert.same(new Typed([1, 2, 3]).includes(2, 1), true);
assert.same(new Typed([1, 2, 3]).includes(2, -1), false);
assert.same(new Typed([1, 2, 3]).includes(2, -2), true);
assert.throws(fn$, "isn't generic");
}
function fn$(){
Typed.prototype.includes.call([1, 2], 1);
}
});
}).call(this);
|
var mousetrap = require('mousetrap');
var UAParser = require('ua-parser-js');
var $ = require('jquery');
var keybindings = require('./keybindings');
var imageList = require('./imageList.json');
var tagInfo = require('./tagInfo.json');
var overlay = require('./overlay');
var closeness = require('./closeness');
var GoogleMapsLoader = require('google-maps'); // only for common js environments
var filtrate = require('./filtrate');
var querystring = require('./querystring');
var svo = null;
var markerIndex = {};
var useAdjustmentMode = ! (querystring('adjust') || '0').startsWith('0');
var eid = overlay.eid;
function updateFlipButton() {
var tail;
if ($('#marker').is(':visible')) {
tail = "to Modern Image";
} else {
tail = "to Historic Image";
}
$('#flip-button-change').text(tail);
}
var shareButtonLinkTemplates = {
"e-mail": "mailto:?body=URL",
"facebook": "https://www.facebook.com/sharer/sharer.php?u=URL",
"reddit": "https://reddit.com/submit?url=URL",
"twitter": "https://twitter.com/share?url=URL"
};
function updateShareButtons() {
for (var name in shareButtonLinkTemplates) {
var anchor = eid(name);
anchor.href = shareButtonLinkTemplates[name].replace(
"URL", encodeURIComponent(window.location.href));
}
}
function updateImageInfo(image) {
$('#image-info-text')
.text(image.TITLE)
.attr('href', image['CAT Record URL']);
}
var engine = new UAParser().getEngine().name;
function setPanoAndPov(options) {
if (engine === "Gecko") {
svo.pan.setOptions(options);
} else {
svo.pan.setPano(options.pano);
setTimeout(function() {
svo.pan.setPov(options.pov);
}, 200);
}
}
function initialize(google) {
svo = new overlay.SVO();
svo.m_initMap();
var svService = new google.maps.StreetViewService();
var imageCategories = {};
$.each(imageList, function(i, image) {
var pos = {lat: image.lat, lng: image.lng};
var marker = new google.maps.Marker({
position: pos,
map: svo.map,
title: image.TITLE
});
markerIndex[image.imageID] = marker;
imageCategories[image['Tag 1']] = 1;
imageCategories[image['Tag 2']] = 1;
marker.addListener('click', function() {
var giveUpNextTime = false;
var gotPanoramaCallback = function(data, status) {
if (status === google.maps.StreetViewStatus.OK) {
console.log("Got panorama " +
(giveUpNextTime ? "by location" : "by id"));
updateOverlayImageInfo(svo, image);
location.hash = image.imageID;
var options = {
pano: data.location.pano,
pov: {heading: image.heading, pitch: image.pitch}
};
// Changing the location and POV at the same time causes horrible
// display problems!
//svo.pan.setOptions(options);
setPanoAndPov(options);
svo.m_toggleVisible(true);
updateFlipButton();
updateShareButtons();
updateImageInfo(image);
} else {
console.log("Failed a try to get pano data");
if (giveUpNextTime) {
console.error('Street View data not found for this location.');
} else {
giveUpNextTime = true;
svService.getPanorama({
location: pos,
radius: 20,
preference: google.maps.StreetViewPreference.NEAREST},
gotPanoramaCallback);
}
}
};
svService.getPanorama({pano: image.pano}, gotPanoramaCallback);
});
});
delete imageCategories[''];
var startMarker = location.hash.slice(1);
if ((! startMarker) || (markerIndex[startMarker] === undefined)) {
var startMarker = (imageList[
Math.floor(Math.random() * imageList.length)].imageID);
}
var initMarker = markerIndex[startMarker];
// Set the map center, panorama location, etc.
// So maybe don't set those in the initMap??
svo.m_initPanorama();
svo.m_initMarker();
google.maps.event.addListener(svo.pan, 'position_changed', function ()
{
var newPos = svo.pan.getPosition(),
newLatLng = {lat: newPos.lat(), lng: newPos.lng()};
svo.map.setCenter(newPos);
// Add markers to the street view that are within a certain number of
// meters from here
updateImageSpots(
closeness.findPointsWithin(newLatLng, imageList, 100));
// TODO: reuse the list of close points we got earlier
var imageToShow = closeness.findClosePoint(newLatLng, imageList, 10,
location.hash.slice(1));
if (imageToShow === null) {
svo.m_setImage(null, null);
svo.m_toggleVisible(false);
updateFlipButton();
} else {
updateOverlayImageInfo(svo, imageToShow);
svo.streetPt = svo.pan.getPosition();
svo.m_toggleVisible(true);
updateFlipButton();
}
svo.m_updateMarker();
});
google.maps.event.trigger(initMarker, "click");
svo.pan.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(
document.getElementById('wymercopyright'));
$('#nav-filtertags, #nav-searchtab, #nav-about').click(function() {
$('#' + this.id.substring(4)).toggle();
google.maps.event.trigger(svo.map, 'resize');
google.maps.event.trigger(svo.pan, 'resize');
return false;
});
if (useAdjustmentMode) {
var adjOut = $('<div class="wymercontrol wymermapcontrol" id="adjust-out"></div>')
.insertAfter('body')
.css("padding-left", "20px")
.css("width", "150px")
.css("height", "200px");
keybindings.addAdjustmentKeybindings(svo, markerIndex, adjOut);
svo.map.controls[google.maps.ControlPosition.LEFT_TOP].push(
eid('adjust-out'));
}
keybindings.addNormalKeybindings(svo);
$("#flip-button").click(function() {
svo.m_toggleVisible();
updateFlipButton();
});
// Notice if the user types a valid Wymer number in the #hash.
window.onhashchange = function() {
var id = location.hash.slice(1);
if (id && (id in markerIndex)) {
google.maps.event.trigger(
markerIndex[id], "click");
}
};
var markerFilter = filtrate.filtrate(imageList,
['TITLE', 'STERMS',
// 'DATE', // TODO
'area', 'CLASSES',
'imageID',
],
['Tag 1', 'Tag 2']);
var filterChecks = $("div#filtertags").filterCheckBoxes(
Object.keys(imageCategories)
).find('input');
var filterSearch = $("input#title-search");
var filterSearchButton = $("#title-search-submit");
var filterClearButton = $("#title-search-clear");
var searchNav = $("#nav-searchtab");
var filterNav = $("#nav-filtertags");
function callUpdate() {
var search = filterSearch.val();
var selected = filterChecks.filter(':checked')
.map(function() { return this.value; })
.toArray();
searchNav.toggleClass("nav-activated", !!search);
filterNav.toggleClass("nav-activated",
selected.length < filterChecks.length);
filterClearButton.toggle(!!search);
markerFilter.find(
search, selected,
function onMatch(image) {
markerIndex[image.imageID].setMap(svo.map);
},
function onNoMatch(image) {
markerIndex[image.imageID].setMap(null);
});
}
filterChecks.on('change', callUpdate);
filterSearch.on('change', callUpdate);
filterSearchButton.on('keypress click', callUpdate);
filterClearButton.on('keypress click', function() {
filterSearch.val('').trigger('change');
});
filterChecks.first().trigger('change');
}
$.fn.filterCheckBoxes = function(categories, options) {
var opts = $.extend({}, $.fn.filterCheckBoxes.defaults, options);
var contents = $.map(categories, function(cat) {
var input = $('<input type="checkbox" checked>')
.attr('name', opts.name)
.attr('value', cat).wrap('<label>').parent();
var title = opts.tagInfo[cat] ? opts.tagInfo[cat]['title'] : cat;
console.log("'" + cat + "'");
console.log(title);
$('<span class="tagtitle">').text(title).appendTo(input);
if (opts.tagInfo[cat]) {
$('<span class="tagdescription">').text(opts.tagInfo[cat]['description']).appendTo(input);
}
return input.wrap('<p>').parent();
});
this.append(contents);
return this;
};
$.fn.filterCheckBoxes.defaults = {
name: 'filtertags',
tagInfo: tagInfo
};
var currentImageSpots = [];
function updateImageSpots(imageRecs) {
// obliterate the old ones, disconnecting so we can GC them
currentImageSpots.forEach(function(marker) {
marker.setMap(null);
google.maps.event.clearInstanceListeners(marker);
});
currentImageSpots.splice(0, currentImageSpots.length);
// make new ones for our new location
imageRecs.forEach(function(record) {
var image = record.point;
var marker = new google.maps.Marker({
position: {lat: image.lat, lng: image.lng},
map: svo.pan
});
marker.addListener('click', function() {
google.maps.event.trigger(markerIndex[image.imageID], 'click');
});
currentImageSpots.push(marker);
});
}
function updateOverlayImageInfo(svo, image) {
svo.imageID = image.imageID;
// TODO: does this work?
svo.streetPt = new google.maps.LatLng(image.lat, image.lng);
svo.sheading = image.heading;
svo.imageDistance = image.image_distance;
svo.realImageHeight = image.height;
svo.realImageWidth = image.width;
svo.spitch = image.pitch;
svo.m_calcImagePoint()
svo.m_setImage(image.image_url, image['CAT Record URL']);
}
module.exports = { 'initialize': initialize };
|
/* jshint node: true */
"use strict";
var Backbone = require("backbone");
var app = require("application");
var $ = require("jquery");
var BaseModels = require("models");
var Models = app.module('Users.Models');
Models.UserModel = BaseModels.BaseModel.extend({
// TODO: Define actual methods/properties, like url. In the meantime, sync
// is overridden to wait a second and then respond with whatever properties
// the model already had. If any attributes are set and create is called, an
// ID will be set.
sync: function (method, model, options) {
console.log('Simulating sync for UserModel, method is:' + method);
var deferred = $.Deferred();
var response = _.extend({}, model.attributes);
if (!_.isEmpty(response) && method == 'create')
response.id = 'deadbeef';
_.delay(function () {
deferred.resolve(response);
}, 1000);
return deferred.promise();
}
});
module.exports = Models;
|
require("./40.js");
require("./81.js");
require("./163.js");
require("./325.js");
module.exports = 326; |
imgurModule = require('./');
console.message = console.log;
imgur.search(['cats and dogs'], console); |
/**
* PreloadJS
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2011 gskinner.com, inc.
*
* Distributed under the terms of the MIT license.
* http://www.opensource.org/licenses/mit-license.html
*
* This notice shall be included in all copies or substantial portions of the Software.
**/(function(){var c=this.createjs=this.createjs||{},c=c.PreloadJS=c.PreloadJS||{};c.version="NEXT";c.buildDate="Fri, 18 Jan 2013 22:50:18 GMT"})();this.createjs=this.createjs||{};
(function(){var c=function(){this.initialize()},a=c.prototype;c.initialize=function(d){d.addEventListener=a.addEventListener;d.removeEventListener=a.removeEventListener;d.removeAllEventListeners=a.removeAllEventListeners;d.hasEventListener=a.hasEventListener;d.dispatchEvent=a.dispatchEvent};a._listeners=null;a.initialize=function(){};a.addEventListener=function(a,b){var g=this._listeners;if(!g)g=this._listeners={};var f=g[a];f?this.removeEventListener(a,b):f=g[a]=[];f.push(b);return b};a.removeEventListener=
function(a,b){var g=this._listeners;if(g){var f=g[a];if(f)for(var e=0,c=f.length;e<c;e++)if(f[e]==b){c==1?delete g[a]:f.splice(e,1);break}}};a.removeAllEventListeners=function(a){a?this._listeners&&delete this._listeners[a]:this._listeners=null};a.dispatchEvent=function(a,b){var g=false,f=this._listeners;if(a&&f){typeof a=="string"&&(a={type:a});a.target=b||this;f=f[a.type];if(!f)return g;for(var f=f.slice(),e=0,c=f.length;e<c;e++){var h=f[e];h instanceof Function?g=g||h.apply(null,[a]):h.handleEvent&&
(g=g||h.handleEvent(a))}}return!!g};a.hasEventListener=function(a){var b=this._listeners;return!(!b||!b[a])};a.toString=function(){return"[EventDispatcher]"};createjs.EventDispatcher=c})();this.createjs=this.createjs||{};
(function(){var c=function(){this.init()};c.prototype={};var a=c.prototype;c.FILE_PATTERN=/(\w+:\/{2})?((?:\w+\.){2}\w+)?(\/?[\S]+\/|\/)?([\w\-%\.]+)(?:\.)(\w+)?(\?\S+)?/i;a.loaded=false;a.canceled=false;a.progress=0;a._item=null;a.onProgress=null;a.onLoadStart=null;a.onComplete=null;a.onError=null;a.addEventListener=null;a.removeEventListener=null;a.removeAllEventListeners=null;a.dispatchEvent=null;a.hasEventListener=null;a._listeners=null;createjs.EventDispatcher.initialize(a);a.getItem=function(){return this._item};
a.init=function(){};a.load=function(){};a.close=function(){};a._sendLoadStart=function(){this._isCanceled()||(this.onLoadStart&&this.onLoadStart({target:this}),this.dispatchEvent("loadStart"))};a._sendProgress=function(a){if(!this._isCanceled()){var b;if(a instanceof Number)this.progress=a,b={loaded:this.progress,total:1};else if(b=a,this.progress=a.loaded/a.total,isNaN(this.progress)||this.progress==Infinity)this.progress=0;b.target=this;b.type="progress";this.onProgress&&this.onProgress(b);this.dispatchEvent(b)}};
a._sendComplete=function(){this._isCanceled()||(this.onComplete&&this.onComplete({target:this}),this.dispatchEvent("complete"))};a._sendError=function(a){if(!this._isCanceled())a==null&&(a={}),a.target=this,a.type="error",this.onError&&this.onError(a),this.dispatchEvent(a)};a._isCanceled=function(){return window.createjs==null||this.canceled?true:false};a._parseURI=function(a){return!a?null:a.match(c.FILE_PATTERN)};a.toString=function(){return"[PreloadJS AbstractLoader]"};createjs.AbstractLoader=
c})();this.createjs=this.createjs||{};
(function(){var c=function(b){this.init(b)},a=c.prototype=new createjs.AbstractLoader;c.LOAD_TIMEOUT=8E3;c.BINARY="binary";c.CSS="css";c.IMAGE="image";c.JAVASCRIPT="javascript";c.JSON="json";c.SOUND="sound";c.SVG="svg";c.TEXT="text";c.XML="xml";a.useXHR=true;a.stopOnError=false;a.maintainScriptOrder=true;a.next=null;a.onFileLoad=null;a.onFileProgress=null;a._typeCallbacks=null;a._extensionCallbacks=null;a._loadStartWasDispatched=false;a._maxConnections=1;a._currentlyLoadingScript=null;a._currentLoads=
null;a._loadQueue=null;a._loadQueueBackup=null;a._loadItemsById=null;a._loadItemsBySrc=null;a._loadedResults=null;a._loadedRawResults=null;a._numItems=0;a._numItemsLoaded=0;a._scriptOrder=null;a._loadedScripts=null;a.init=function(b){this._numItems=this._numItemsLoaded=0;this._loadStartWasDispatched=this._paused=false;this._currentLoads=[];this._loadQueue=[];this._loadQueueBackup=[];this._scriptOrder=[];this._loadedScripts=[];this._loadItemsById={};this._loadItemsBySrc={};this._loadedResults={};this._loadedRawResults=
{};this._typeCallbacks={};this._extensionCallbacks={};this.setUseXHR(b)};a.setUseXHR=function(b){return this.useXHR=b!=false&&window.XMLHttpRequest!=null};a.removeAll=function(){this.remove()};a.remove=function(b){var a=null;b&&!(b instanceof Array)?a=[b]:b&&(a=b);b=false;if(a){for(;a.length;){for(var d=a.pop(),e=this.getResult(d),c=this._loadQueue.length-1;c>=0;c--)if(h=this._loadQueue[c].getItem(),h.id==d||h.src==d){this._loadQueue.splice(c,1)[0].cancel();break}for(c=this._loadQueueBackup.length-
1;c>=0;c--)if(h=this._loadQueueBackup[c].getItem(),h.id==d||h.src==d){this._loadQueueBackup.splice(c,1)[0].cancel();break}if(e)delete this._loadItemsById[e.id],delete this._loadItemsBySrc[e.src],this._disposeItem(e);else for(var c=this._currentLoads.length-1;c>=0;c--){var h=this._currentLoads[c].getItem();if(h.id==d||h.src==d){this._currentLoads.splice(c,1)[0].cancel();b=true;break}}}b&&this._loadNext()}else{this.close();for(d in this._loadItemsById)this._disposeItem(this._loadItemsById[d]);this.initialize(this.useXHR)}};
a.reset=function(){this.close();for(var b in this._loadItemsById)this._disposeItem(this._loadItemsById[b]);b=[];for(i=0,l=this._loadQueueBackup.length;i<l;i++)b.push(this._loadQueueBackup[i].getItem());this.loadManifest(b,false)};c.isBinary=function(b){switch(b){case createjs.LoadQueue.IMAGE:case createjs.LoadQueue.BINARY:return true;default:return false}};a.installPlugin=function(b){if(!(b==null||b.getPreloadHandlers==null)){b=b.getPreloadHandlers();if(b.types!=null)for(var a=0,d=b.types.length;a<
d;a++)this._typeCallbacks[b.types[a]]=b.callback;if(b.extensions!=null)for(a=0,d=b.extensions.length;a<d;a++)this._extensionCallbacks[b.extensions[a]]=b.callback}};a.setMaxConnections=function(b){this._maxConnections=b;this._paused||this._loadNext()};a.loadFile=function(b,a){b==null?this._sendError({text:"PRELOAD_NO_FILE"}):(this._addItem(b),a!==false&&this.setPaused(false))};a.loadManifest=function(b,a){var d;if(b instanceof Array){if(b.length==0){this._sendError({text:"PRELOAD_MANIFEST_EMPTY"});
return}d=b}else{if(b==null){this._sendError({text:"PRELOAD_MANIFEST_NULL"});return}d=[b]}for(var c=0,j=d.length;c<j;c++)this._addItem(d[c],false);a!==false&&this.setPaused(false)};a.load=function(){this.setPaused(false)};a.getItem=function(b){return this._loadItemsById[b]||this._loadItemsBySrc[b]};a.getResult=function(b,a){var d=this._loadItemsById[b]||this._loadItemsBySrc[b];if(d==null)return null;d=d.id;return a&&this._loadedRawResults[d]?this._loadedRawResults[d]:this._loadedResults[d]};a.setPaused=
function(b){(this._paused=b)||this._loadNext()};a.close=function(){for(;this._currentLoads.length;)this._currentLoads.pop().cancel();this._scriptOrder.length=0;this._loadedScripts.length=0;this.loadStartWasDispatched=false};a._addItem=function(b){b=this._createLoadItem(b);if(b!=null){var a=this._createLoader(b);a!=null&&(this._loadQueue.push(a),this._loadQueueBackup.push(a),this._numItems++,this._updateProgress(),this.maintainScriptOrder&&b.type==createjs.LoadQueue.JAVASCRIPT&&a instanceof createjs.XHRLoader&&
(this._scriptOrder.push(b),this._loadedScripts.push(null)))}};a._createLoadItem=function(b){var a;switch(typeof b){case "string":a={src:b};break;case "object":a=window.HTMLAudioElement&&b instanceof HTMLAudioElement?{tag:b,src:a.tag.src,type:createjs.LoadQueue.SOUND}:b}a.result=null;b=this._parseURI(a.src);if(b!=null)a.ext=b[5];if(a.type==null)a.type=this._getTypeByExtension(a.ext);if(a.tag==null)a.tag=this._createTag(a.type);if(a.id==null||a.id=="")a.id=a.src;if(b=this._typeCallbacks[a.type]||this._extensionCallbacks[a.ext]){b=
b(a.src,a.type,a.id,a.data);if(b===false)return null;else if(b!==true){if(b.src!=null)a.src=b.src;if(b.id!=null)a.id=b.id;if(b.tag!=null&&b.tag.load instanceof Function)a.tag=b.tag;if(b.completeHandler!=null)a.completeHandler=b.completeHandler}if(b.type)a.type=b.type;b=this._parseURI(a.src);if(b!=null)a.ext=b[5]}this._loadItemsById[a.id]=a;return this._loadItemsBySrc[a.src]=a};a._createLoader=function(a){var d=this.useXHR;switch(a.type){case createjs.LoadQueue.JSON:case createjs.LoadQueue.XML:case createjs.LoadQueue.TEXT:d=
true;break;case createjs.LoadQueue.SOUND:d=false}return d?new createjs.XHRLoader(a):new createjs.TagLoader(a)};a._loadNext=function(){if(!this._paused){if(!this._loadStartWasDispatched)this._sendLoadStart(),this._loadStartWasDispatched=true;if(this._numItems==this._numItemsLoaded)this.loaded=true,this._sendComplete(),this.next&&this.next.load&&this.next.load();for(var a=0,d=this._loadQueue.length;a<d;a++){if(this._currentLoads.length>=this._maxConnections)break;var c=this._loadQueue[a];if(this.maintainScriptOrder&&
c instanceof createjs.TagLoader&&c.getItem().type==createjs.LoadQueue.JAVASCRIPT){if(this._currentlyLoadingScript)continue;this._currentlyLoadingScript=true}this._loadQueue.splice(a,1);this._loadItem(c);a--;d--}}};a._loadItem=function(a){a.addEventListener("progress",createjs.proxy(this._handleProgress,this));a.addEventListener("complete",createjs.proxy(this._handleFileComplete,this));a.addEventListener("error",createjs.proxy(this._handleFileError,this));this._currentLoads.push(a);a.load()};a._handleFileError=
function(a){var d=a.target;this._numItemsLoaded++;this._updateProgress();a={item:d.getItem()};this._sendError(a);this.stopOnError||(this._removeLoadItem(d),this._loadNext())};a._handleFileComplete=function(a){var a=a.target,d=a.getItem();this._loadedResults[d.id]=a.getResult();a instanceof createjs.XHRLoader&&(this._loadedRawResults[d.id]=a.getResult(true));this._removeLoadItem(a);if(this.maintainScriptOrder&&d.type==createjs.LoadQueue.JAVASCRIPT)if(a instanceof createjs.TagLoader)this._currentlyLoadingScript=
false;else{this._loadedScripts[this._scriptOrder.indexOf(d)]=d;this._checkScriptLoadOrder(a);return}this._processFinishedLoad(d)};a._processFinishedLoad=function(a){this._numItemsLoaded++;this._updateProgress();this._sendFileComplete(a);this._loadNext()};a._checkScriptLoadOrder=function(){for(var a=this._loadedScripts.length,d=0;d<a;d++){var c=this._loadedScripts[d];if(c===null)break;c!==true&&(this._processFinishedLoad(c),this._loadedScripts[d]=true,d--,a--)}};a._removeLoadItem=function(a){for(var d=
this._currentLoads.length,c=0;c<d;c++)if(this._currentLoads[c]==a){this._currentLoads.splice(c,1);break}};a._handleProgress=function(a){a=a.target;this._sendFileProgress(a.getItem(),a.progress);this._updateProgress()};a._updateProgress=function(){var a=this._numItemsLoaded/this._numItems,d=this._numItems-this._numItemsLoaded;if(d>0){for(var c=0,e=0,j=this._currentLoads.length;e<j;e++)c+=this._currentLoads[e].progress;a+=c/d*(d/this._numItems)}this._sendProgress(a)};a._disposeItem=function(a){delete this._loadedResults[a.id];
delete this._loadedRawResults[a.id];delete this._loadItemsById[a.id];delete this._loadItemsBySrc[a.src]};a._createTag=function(a){switch(a){case createjs.LoadQueue.IMAGE:return document.createElement("img");case createjs.LoadQueue.SOUND:return a=document.createElement("audio"),a.autoplay=false,a;case createjs.LoadQueue.JAVASCRIPT:return a=document.createElement("script"),a.type="text/javascript",a;case createjs.LoadQueue.CSS:return a=this.useXHR?document.createElement("style"):document.createElement("link"),
a.rel="stylesheet",a.type="text/css",a;case createjs.LoadQueue.SVG:return this.useXHR?a=document.createElement("svg"):(a=document.createElement("object"),a.type="image/svg+xml"),a}return null};a._getTypeByExtension=function(a){switch(a){case "jpeg":case "jpg":case "gif":case "png":case "webp":case "bmp":return createjs.LoadQueue.IMAGE;case "ogg":case "mp3":case "wav":return createjs.LoadQueue.SOUND;case "json":return createjs.LoadQueue.JSON;case "xml":return createjs.LoadQueue.XML;case "css":return createjs.LoadQueue.CSS;
case "js":return createjs.LoadQueue.JAVASCRIPT;case "svg":return createjs.LoadQueue.SVG;default:return createjs.LoadQueue.TEXT}};a._sendFileProgress=function(a,d){if(this._isCanceled())this._cleanUp();else{var c={target:this,type:"fileprogress",progress:d,loaded:d,total:1,item:a};this.onFileProgress&&this.onFileProgress(c);this.dispatchEvent(c)}};a._sendFileComplete=function(a){if(!this._isCanceled()){var d={target:this,type:"fileload",item:a,result:this._loadedResults[a.id],rawResult:this._loadedRawResults[a.id]};
a.completeHandler&&a.completeHandler(d);this.onFileLoad&&this.onFileLoad(d);this.dispatchEvent(d)}};a.toString=function(){return"[PreloadJS LoadQueue]"};createjs.proxy=function(a,d){return function(){return a.apply(d,arguments)}};createjs.LoadQueue=c;if(!createjs.proxy)createjs.proxy=function(a,d){var c=Array.prototype.slice.call(arguments,2);return function(){return a.apply(d,Array.prototype.slice.call(arguments,0).concat(c))}};var d=function(){};d.init=function(){var a=navigator.userAgent;d.isFirefox=
a.indexOf("Firefox")>-1;d.isOpera=window.opera!=null;d.isChrome=a.indexOf("Chrome")>-1;d.isIOS=a.indexOf("iPod")>-1||a.indexOf("iPhone")>-1||a.indexOf("iPad")>-1};d.init();createjs.LoadQueue.BrowserDetect=d;if(!Array.prototype.indexOf)Array.prototype.indexOf=function(a){if(this==null)throw new TypeError;var d=Object(this),c=d.length>>>0;if(c===0)return-1;var e=0;arguments.length>1&&(e=Number(arguments[1]),e!=e?e=0:e!=0&&e!=Infinity&&e!=-Infinity&&(e=(e>0||-1)*Math.floor(Math.abs(e))));if(e>=c)return-1;
for(e=e>=0?e:Math.max(c-Math.abs(e),0);e<c;e++)if(e in d&&d[e]===a)return e;return-1}})();this.createjs=this.createjs||{};
(function(){var c=function(a){this.init(a)},a=c.prototype=new createjs.AbstractLoader;a._loadTimeout=null;a._tagCompleteProxy=null;a._isAudio=false;a._tag=null;a.init=function(a){this._item=a;this._tag=a.tag;this._isAudio=window.HTMLAudioElement&&a.tag instanceof HTMLAudioElement;this._tagCompleteProxy=createjs.proxy(this._handleLoad,this)};a.getResult=function(){return this._tag};a.cancel=function(){this.canceled=true;this._clean();this.getItem()};a.load=function(){var a=this._item,b=this._tag;clearTimeout(this._loadTimeout);
this._loadTimeout=setTimeout(createjs.proxy(this._handleTimeout,this),createjs.LoadQueue.LOAD_TIMEOUT);if(this._isAudio)b.src=null,b.preload="auto";b.onerror=createjs.proxy(this._handleError,this);this._isAudio?(b.onstalled=createjs.proxy(this._handleStalled,this),b.addEventListener("canplaythrough",this._tagCompleteProxy,false)):(b.onload=createjs.proxy(this._handleLoad,this),b.onreadystatechange=createjs.proxy(this._handleReadyStateChange,this));switch(a.type){case createjs.LoadQueue.CSS:b.href=
a.src;break;case createjs.LoadQueue.SVG:b.data=a.src;break;default:b.src=a.src}if(a.type==createjs.LoadQueue.SVG||a.type==createjs.LoadQueue.JAVASCRIPT||a.type==createjs.LoadQueue.CSS)(document.body||document.getElementsByTagName("body")[0]).appendChild(b);b.load!=null&&b.load()};a._handleTimeout=function(){this._clean();this._sendError({reason:"PRELOAD_TIMEOUT"})};a._handleStalled=function(){};a._handleError=function(){this._clean();this._sendError()};a._handleReadyStateChange=function(){clearTimeout(this._loadTimeout);
this.getItem().tag.readyState=="loaded"&&this._handleLoad()};a._handleLoad=function(){if(!this._isCanceled()){var a=this.getItem(),b=a.tag;if(!(this.loaded||this.isAudio&&b.readyState!==4))this.loaded=true,a.type==createjs.LoadQueue.SVG&&(document.body||document.getElementsByTagName("body")[0]).removeChild(b),this._clean(),this._sendComplete()}};a._clean=function(){clearTimeout(this._loadTimeout);var a=this.getItem().tag;a.onload=null;a.removeEventListener&&a.removeEventListener("canplaythrough",
this._tagCompleteProxy,false);a.onstalled=null;a.onprogress=null;a.onerror=null;a.parentNode&&a.parentNode.removeChild(a)};a.toString=function(){return"[PreloadJS TagLoader]"};createjs.TagLoader=c})();this.createjs=this.createjs||{};
(function(){var c=function(a){this.init(a)},a=c.prototype=new createjs.AbstractLoader;a._request=null;a._loadTimeout=null;a._xhrLevel=1;a._response=null;a._rawResponse=null;a.init=function(a){this._item=a;this._createXHR(a)};a.getResult=function(a){return a&&this._rawResponse?this._rawResponse:this._response};a.cancel=function(){this.canceled=true;this._clean();this._request.abort()};a.load=function(){if(this._request==null)this._handleError();else{this._request.onloadstart=createjs.proxy(this._handleLoadStart,
this);this._request.onprogress=createjs.proxy(this._handleProgress,this);this._request.onabort=createjs.proxy(this._handleAbort,this);this._request.onerror=createjs.proxy(this._handleError,this);this._request.ontimeout=createjs.proxy(this._handleTimeout,this);if(this._xhrLevel==1)this._loadTimeout=setTimeout(createjs.proxy(this._handleTimeout,this),createjs.LoadQueue.LOAD_TIMEOUT);this._request.onload=createjs.proxy(this._handleLoad,this);this._request.onreadystatechange=this._handleReadyStateChange(this);
try{this._request.send()}catch(a){this._sendError({source:a})}}};a._handleProgress=function(a){a.loaded>0&&a.total==0||this._sendProgress({loaded:a.loaded,total:a.total})};a._handleLoadStart=function(){clearTimeout(this._loadTimeout);this._sendLoadStart()};a._handleAbort=function(){this._clean();this._sendError()};a._handleError=function(){this._clean();this._sendError()};a._handleReadyStateChange=function(){this._request.readyState==4&&this._handleLoad()};a._handleLoad=function(){if(!this.loaded)this.loaded=
true,this._checkError()?(this._response=this._getResponse(),this._clean(),this._generateTag()&&this._sendComplete()):this._handleError()};a._handleTimeout=function(){this._clean();this._sendError()};a._checkError=function(){switch(parseInt(this._request.status)){case 404:case 0:return false}return true};a._getResponse=function(){if(this._response!=null)return this._response;if(this._request.response!=null)return this._request.response;try{if(this._request.responseText!=null)return this._request.responseText}catch(a){}try{if(this._request.responseXML!=
null)return this._request.responseXML}catch(b){}return null};a._createXHR=function(a){var b=document.createElement("a");b.href=a.src;var c=document.createElement("a");c.href=location.href;var b=b.hostname!=""&&(b.port!=c.port||b.protocol!=c.protocol||b.hostname!=c.hostname),f;if(b&&window.XDomainRequest)f=new XDomainRequest;else if(window.XMLHttpRequest)f=new XMLHttpRequest;else try{f=new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){try{f=new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(j){try{f=new ActiveXObject("Msxml2.XMLHTTP")}catch(h){return false}}}a.type==
createjs.LoadQueue.TEXT&&f.overrideMimeType&&f.overrideMimeType("text/plain; charset=x-user-defined");this._xhrLevel=typeof f.responseType==="string"?2:1;f.open("GET",a.src,true);b&&f instanceof XMLHttpRequest&&this._xhrLevel==1&&f.setRequestHeader("Origin",location.origin);if(createjs.LoadQueue.isBinary(a.type))f.responseType="arraybuffer";this._request=f;return true};a._clean=function(){clearTimeout(this._loadTimeout);var a=this._request;a.onloadstart=null;a.onprogress=null;a.onabort=null;a.onerror=
null;a.onload=null;a.ontimeout=null;a.onloadend=null;a.onreadystatechange=null};a._generateTag=function(){var a=this._item.tag;switch(this._item.type){case createjs.LoadQueue.IMAGE:return a.onload=createjs.proxy(this._handleTagReady,this),a.src=this._item.src,this._rawResponse=this._response,this._response=a,false;case createjs.LoadQueue.JAVASCRIPT:a=document.createElement("script");this._rawResponse=a.text=this._response;this._response=a;break;case createjs.LoadQueue.CSS:document.getElementsByTagName("head")[0].appendChild(a);
if(a.styleSheet)a.styleSheet.cssText=this._response;else{var b=document.createTextNode(this._response);a.appendChild(b)}this._rawResponse=this._response;this._response=a;break;case createjs.LoadQueue.XML:this._response=b=this._parseXML(this._response,"text/xml");break;case createjs.LoadQueue.SVG:b=this._parseXML(this._response,"image/svg+xml");this._rawResponse=this._response;a.appendChild(b.documentElement);this._response=a;break;case createjs.LoadQueue.JSON:try{eval("json="+this._response)}catch(c){break}this._rawResponse=
this._response;this._response={}}return true};a._parseXML=function(a,b){var c;window.DOMParser?c=(new DOMParser).parseFromString(a,b):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async=false,c.loadXML(a));return c};a._handleTagReady=function(){this._sendComplete()};a.toString=function(){return"[PreloadJS XHRLoader]"};createjs.XHRLoader=c})();
|
Morpho.log = console.log; |
import React from 'react'
import PropTypes from 'prop-types'
import EntryListItemContainer from './entry-list-item.container'
import RoundSelectorContainer from './round-selector.container'
const EntryList = ({entries, pars}) => (
<div>
<h2>出場選手一覧</h2>
<div className='row mb-2'>
<div className='col-auto mr-auto'/>
<div className='col-auto'>
<RoundSelectorContainer/>
</div>
</div>
{entries.map(e =>
<EntryListItemContainer key={`EntryList-${e.id}`}
pars={pars}
{...e} />
)}
</div>
)
EntryList.propTypes = {
entries: PropTypes.array.isRequired,
pars: PropTypes.array.isRequired,
}
export default EntryList
|
import GlobalNotification from './GlobalNotification'
export default GlobalNotification
|
import React from 'react';
const th = (props) => {
const { children } = props;
return (
<th>{ children }</th>
);
};
export default th;
|
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (props, defaultProps) {
var keys = (0, _keys2.default)(defaultProps);
var target = {};
for (var _iterator = (0, _keys2.default)(props), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var key = _ref;
if (keys.indexOf(key) === -1) {
target[key] = props[key];
}
}
return target;
}; |
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* @jest-environment ./CircusHandleTestEventEnvironment.js
*/
beforeEach(() => {});
test('test name here', () => {
expect(true).toBe(true);
});
test('second test name here', () => {
expect(true).toBe(true);
});
|
/**
* Error handlers
*/
var log = require('./logging');
var serverConfig = require('./config');
var noStack = [ 402, 404 ];
var shortStack = [ 401, 403, 407, 408 ];
var errct = 0;
function defaultRequestHandler(req, res, next) {
var err = new Error(req.path + ' not found');
err.status = 404;
next(err);
}
function clippedStack(stack, lines) {
if (!lines) lines=1;
var clipped = stack.split && stack.split("\n").splice(0,lines);
return clipped.join("\n");
}
function logErrors(err, req, res, next) {
++errct;
if (err.status) {
if (noStack.indexOf(err.status)>-1) {
log.error(err.status + ' ' + clippedStack(err.stack));
} else if (shortStack.indexOf(err.status)>-1) {
log.error(err.status + ' ' + clippedStack(err.stack, 3));
} else {
log.error(err.status + ' ERROR #' + errct);
log.error(err.stack);
}
} else {
log.error('UNHANDLED ERROR #'+errct);
log.error(err.stack);
}
next(err);
}
function apiErrorResponse(err, req, res, next) {
if (req.xhr ||
req.path===serverConfig.apiRoute
|| req.path.indexOf(serverConfig.apiRoute + '/')===1) {
var errorMsg = err.status ?
{
error : (err.message||'ERROR')
+ '(code:'+err.status + ', #' + errct + ')',
code : err.status
}
:
{
error : 'An unhandled server error has occurred. (' + errct + ')',
code : 500
};
var msg = JSON.stringify(errorMsg);
res.status(errorMsg.code)
.type('json')
.send(msg);
} else {
next(err);
}
}
function errorResponse(err, req, res, next) {
var ecode = err.status || 500;
var emsg = err.message ? err.message
: err.status ? 'An unknown error has occurred.'
: 'An unhandled server exception has occurred.';
res.status(ecode)
.send(emsg + ' (' + errct + ')');
}
module.exports = function(app) {
log.debug('Initializing server error handlers...')
app.all('*', defaultRequestHandler);
app.use(logErrors);
app.use(apiErrorResponse);
app.use(errorResponse);
};
|
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import Form from './Form';
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
<h1>Prevent Transition</h1>
<ul>
<li><Link to="/">Form</Link></li>
<li><Link to="/contact">Contact</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<hr/>
<Route exact path='/' component={Form}/>
<Route path='/contact' render={() => (<h2>Contact</h2>)}/>
<Route path='/about' render={() => (<h2>About</h2>)}/>
</div>
</BrowserRouter>
);
}
}
export default App;
|
version https://git-lfs.github.com/spec/v1
oid sha256:b28811be69917ab2deb0fdeadfd8d3eb4dc5bc4487869e2a2cdb49719ec69405
size 15238
|
var searchData=
[
['int_5ftype_5fbytearr_5flength',['INT_TYPE_BYTEARR_LENGTH',['../BinsonObject_8h.html#a0bd44a13d360dbe7ce51b58d84e86b18a8726ee486aa7c3d73cc39a58b6f9c14c',1,'BinsonObject.h']]],
['int_5ftype_5fnormal',['INT_TYPE_NORMAL',['../BinsonObject_8h.html#a0bd44a13d360dbe7ce51b58d84e86b18a4d0075b3204a6c57c9a2c292f8ddb307',1,'BinsonObject.h']]],
['int_5ftype_5fstring_5flength',['INT_TYPE_STRING_LENGTH',['../BinsonObject_8h.html#a0bd44a13d360dbe7ce51b58d84e86b18a75182953aa9c35ae64f29f240ff6ad24',1,'BinsonObject.h']]],
['integervalue',['integerValue',['../structBinsonField.html#a88bc4483faecd28e1671135d2eb911b8',1,'BinsonField']]],
['intvaluetype',['IntValueType',['../BinsonObject_8h.html#a0bd44a13d360dbe7ce51b58d84e86b18',1,'BinsonObject.h']]]
];
|
'use strict';
const paris = require('./paris');
module.exports = {
start: () => {
paris.start();
},
paris
};
|
annoCtrl.controller('BooksCtrl', ['$scope', '$routeParams', '$modal', '$timeout', 'UserService', 'SerializeService', function($scope, $routeParams, $modal, $timeout, UserService, SerializeService) {
// Save user data after login
var uid = $routeParams.uid
UserService.getUser(uid).then(function(user) {
$scope.user = user
$scope.$emit('page:change', 'books', (user.name || '我') + '的书架')
// fetch books
SerializeService.fetchAllBooks(user.id).then(function(books) {
$scope.books = books
$scope.tipVisible = !user.is_self && _.isEmpty(books)
})
$scope.searchBook = function() {
var modalInstance = $modal.open({
templateUrl: 'modalSearchBook.html',
controller: 'SearchBookCtrl',
resolve: {
'user': function() {
return user
}
}
}).opened.then(function() {
$timeout(function() {
// not that way angular
var firstInput = $('.modal-dialog input[type="text"]')
if (firstInput.length) {
firstInput[0].focus()
}
}, 50)
})
}
})
}]).controller('SearchBookCtrl', ['$scope', '$modalInstance', '$location', '$http', 'BookService', 'user', function($scope, $modalInstance, $location, $http, BookService, user) {
$scope.searchBook = function(query) {
if (!query.match(/^\d*$/)) { // search by keyword
$http.get('/api/v2/book/search', {
params: {
q: query
}
}).success(function(res) {
$scope.books = res.books
if (res.books.length) {
$scope.selectedIndex = 0
$scope.selectedBook = res.books[0]
}
})
} else { // search by subject id
BookService.get(query).then(function(book) {
$scope.selectedIndex = 0
$scope.selectedBook = book
$scope.books = [book]
})
}
$scope.has_searched = true
}
$scope.selectBook = function($index, book) {
$scope.selectedIndex = $index
$scope.selectedBook = book
}
$scope.ok = function (bid) {
$location.path('/' + user.uid + '/book/' + bid +'/new')
$modalInstance.close()
}
$scope.cancel = function () {
$modalInstance.dismiss('cancel')
}
}]) |
/*!
* parse-github-short-urls <https://github.com/tunnckoCore/parse-github-short-urls>
*
* Copyright (c) 2015-2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var test = require('assertit')
var parseGithubShortUrls = require('./index')
test('parse-github-short-urls:', function (done) {
parseGithubShortUrls()
done()
})
|
//Define global namespace
var mw_app = mw_app || {};
mw_app.validation = (function() {
//Define regular expressions object
var regexpressions = {
text: /^[a-zA-Z ]{2,30}$/,
email: /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
tel: /^(?:[-(). +]*[0-9]){11,}[-\s\.()+]{0,}[-\s\./0-9]*$/,
url: /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/,
};
//Find next button, all inputs and successful inputs
var _cacheDom = function() {
this.details = $('.details');
this.detailsNext = $('.next-details');
this.inputElements = this.details.find('input');
this.hasSuccess = this.details.find('.form-control-success');
};
//Apply validation to every detail input element in dom
var validate = function() {
_cacheDom.call(this);
for (var i = 0; i < this.inputElements.length; i++) {
_applyRegExByType(this.inputElements[i]);
}
};
//Comparing the dom input type with the key from regexpressions - to apply the correct regex
var _applyRegExByType = function(currentInputElement) {
for (var regExType in regexpressions) {
var regex = regexpressions[regExType];
if (currentInputElement.type == regExType) {
_setInputFieldRegexType(regex, currentInputElement);
}
}
};
//After any user input, apply the regex to the chosen element
var _setInputFieldRegexType = function(regex, currentInputElement) {
$(currentInputElement).on('input', function(e) {
var test = regex.test($(currentInputElement).val());
_setValidationClasses(currentInputElement, test);
});
};
//Enable the next button when all fields have passed validation
var _validateNextButton = function() {
_cacheDom();
if (this.hasSuccess.length == this.details.length) {
this.detailsNext
.prop("disabled", null)
.css("border-color", "green");
} else {
this.detailsNext
.prop("disabled", true)
.css("border-color", "red");
}
};
//Sets visual tick or cross beside input for success/failure of regex test
var _setValidationClasses = function(currentInputElement, test) {
_removeExistingClasses(currentInputElement);
if (test) {
$(currentInputElement)
.addClass('form-control-success')
.parents(':eq(1)').addClass('has-success');
} else {
$(currentInputElement)
.addClass('form-control-danger')
.parents(':eq(1)').addClass('has-danger');
}
_validateNextButton();
};
//Clear input element of any left-over classes from the last round of validation
var _removeExistingClasses = function(currentInputElement) {
$(currentInputElement).removeClass('form-control-danger form-control-success');
$(currentInputElement).parents(':eq(1)').removeClass('has-success has-danger');
};
//Clears validation classes and resets next button
var resetValidation = function(currentInputElement) {
_removeExistingClasses(currentInputElement);
_validateNextButton();
};
//Make validate and resetValidation methods public
return {
validate: validate,
resetValidation: resetValidation
};
})();
|
import React from 'react';
import { mount } from 'enzyme';
import Filetree from '../../app/components/Filetree';
import { getUsername } from '../../app/actions/filetree-actions';
const dispatchGetUsername = () => getUsername();
describe('Filetree component', () => {
it('calls getUsername from dispatchGetUsername from componentDidMount', () => {
const mockGetUsername = jest.fn(dispatchGetUsername);
mount(<Filetree dispatchGetUsername={mockGetUsername} />);
expect(mockGetUsername).toHaveBeenCalled();
});
});
|
// All code points in the `Tamil` script as per Unicode v6.1.0:
[
0xB82,
0xB83,
0xB85,
0xB86,
0xB87,
0xB88,
0xB89,
0xB8A,
0xB8E,
0xB8F,
0xB90,
0xB92,
0xB93,
0xB94,
0xB95,
0xB99,
0xB9A,
0xB9C,
0xB9E,
0xB9F,
0xBA3,
0xBA4,
0xBA8,
0xBA9,
0xBAA,
0xBAE,
0xBAF,
0xBB0,
0xBB1,
0xBB2,
0xBB3,
0xBB4,
0xBB5,
0xBB6,
0xBB7,
0xBB8,
0xBB9,
0xBBE,
0xBBF,
0xBC0,
0xBC1,
0xBC2,
0xBC6,
0xBC7,
0xBC8,
0xBCA,
0xBCB,
0xBCC,
0xBCD,
0xBD0,
0xBD7,
0xBE6,
0xBE7,
0xBE8,
0xBE9,
0xBEA,
0xBEB,
0xBEC,
0xBED,
0xBEE,
0xBEF,
0xBF0,
0xBF1,
0xBF2,
0xBF3,
0xBF4,
0xBF5,
0xBF6,
0xBF7,
0xBF8,
0xBF9,
0xBFA
]; |
/**
* Mixins for metrics
* @function metricsMix
* @param {function} Class
* @returns {function} Class
*/
'use strict'
/** @lends metricsMix */
function metricsMix(Class) {
/**
* @class MetricsMix
*/
class MetricsMix extends Class {
constructor() {
super(...arguments)
this.metrics = {
controllerAttachCounts: {},
controllerDetachCounts: {},
invocationKeepCounts: {},
invocationKeepStartCounts: {},
invocationKeepStopCounts: {},
}
}
addControllerAttachCountMetrics(controllerName, amount = 1) {
return this.addMetrics('controllerAttachCounts', controllerName, amount)
}
addControllerDetachCountMetrics(controllerName, amount = 1) {
return this.addMetrics('controllerDetachCounts', controllerName, amount)
}
addInvocationKeepCountMetrics(controllerName, amount = 1) {
return this.addMetrics('invocationKeepCounts', controllerName, amount)
}
addKeepStartCountMetrics(controllerName, amount = 1) {
return this.addMetrics(
'invocationKeepStartCounts',
controllerName,
amount,
)
}
addKeepStopCountMetrics(controllerName, amount = 1) {
return this.addMetrics('invocationKeepStopCounts', controllerName, amount)
}
addMetrics(namespace, key, amount = 1) {
if (!this.metrics[namespace]) {
throw new Error(`[MetricsMix] Unknown namespace: ${namespace}`)
}
this.metrics[namespace][key] =
(this.metrics[namespace][key] || 0) + amount
}
}
return MetricsMix
}
module.exports = metricsMix
|
import { combineReducers } from 'redux';
import Specs from './reducer_specs';
import Editorials from './reducer_editorials';
const rootReducer = combineReducers({
specs: Specs,
editorials: Editorials
});
export default rootReducer;
|
const helpers = require('../helpers');
const execSync = require('child_process').execSync;
// const REPO_NAME_RE = /Push URL: https:\/\/github\.com\/.*\/(.*)\.git/;
const REPO_NAME_RE = /Push URL: (?:https:\/\/|git@)github\.com(?:\/|:).*\/(.*)\.git/;
function getWebpackConfigModule() {
if (helpers.hasProcessFlag('github-dev')) {
return require('../webpack.dev.js');
} else if (helpers.hasProcessFlag('github-prod')) {
return require('../webpack.prod.js');
} else {
throw new Error('Invalid compile option.');
}
}
function getRepoName(remoteName) {
remoteName = remoteName || 'origin';
var stdout = execSync('git remote show ' + remoteName),
match = REPO_NAME_RE.exec(stdout);
console.log(match);
if (!match) {
throw new Error('Could not find a repository on remote ' + remoteName);
} else {
return match[1];
}
}
function stripTrailing(str, char) {
if (str[0] === char) {
str = str.substr(1);
}
if(str.substr(-1) === char) {
str = str.substr(0, str.length - 1);
}
return str;
}
/**
* Given a string remove trailing slashes and adds 1 slash at the end of the string.
*
* Example:
* safeUrl('/value/')
* // 'value/'
*
* @param url
* @returns {string}
*/
function safeUrl(url) {
const stripped = stripTrailing(url || '', '/');
return stripped ? stripped + '/' : ''
}
exports.getWebpackConfigModule = getWebpackConfigModule;
exports.getRepoName = getRepoName;
exports.safeUrl = safeUrl;
|
var gameState = {
create: function() {
this.physics.startSystem(Phaser.Physics.ARCADE);
this.background = game.add.tileSprite(0,0, this.game.world.width, this.game.world.height, 'space');
this.background.autoScroll(-60, -20);
this.setupPlayer();
this.player;
this.enemy;
this.enemyTwo;
this.catTrail;
this.setupButtons();
this.setupLazers();
this.setupEnemies();
this.setupExplosions();
this.fontStyle;
this.score = 0;
this.lives = 9;
this.scoreString = '';
this.scoreText;
this.PlayerAlive = true;
this.endTime = 0;
this.music;
this.ouch;
this.boom;
this.ding;
this.pew;
this.wee
this.fireRate = 1000;
this.nextFire = 0;
this.alive = true;
game.time.events.loop(Phaser.Timer.SECOND * 2, this.spawnEnemy, this);
game.physics.startSystem(Phaser.Physics.ARCADE);
game.time.advancedTiming = true;
this.instructions = this.add.text( game.world.centerX, game.world.centerY,
'Use mouse to Move, Press Spacebar to Fire\n' + 'Good Luck, you have 9 lives and 30 seconds',
{ font: "30px Arial", fill: "#ff0044", align: "center" });
this.instructions.anchor.setTo(0.5, 0.5);
this.instExpire = this.time.now + 9000;
this.fontStyle = { font: "40px Arial", fill: "#FFCC00", stroke: "#333", strokeThickness: 3, align: "center" };
this.scoreText = this.game.add.text(60,10,"Score : "+this.score,this.fontStyle);
this.livesText = this.game.add.text(game.world.width - 200, 10,"Lives : "+this.lives,this.fontStyle);
this.endTime = game.time.now + (1000 * 30 );
this.music = this.add.audio('game_audio');
this.music.play('', 0, 0.3, true);
this.ouch = this.add.audio('hurt_audio');
this.boom = this.add.audio('explosion_audio');
this.ding = this.add.audio('select_audio');
this.pew = this.add.audio('pew_audio');
this.wee = this.add.audio('wee_audio');
},
update: function() {
// If the PLAYER is > 8px away from the pointer then let's move to it
if (this.physics.arcade.distanceToPointer(this.player, this.game.input.activePointer) > 8)
{
// Make the object seek to the active pointer (mouse or touch).
this.physics.arcade.moveToPointer(this.player, 400);
this.player.rotation = this.game.physics.arcade.angleToPointer(this.player);
}
else
{
this.player.body.velocity.set(0);
}
var style = { font: '34px Arial', align: 'center'};
var timeLeft = this.endTime - game.time.now;
if (timeLeft >= 0) {
// show time remaining in seconds (divide by 1000)
game.debug.text(Math.ceil(timeLeft / 1000) + " seconds left!", 500, 100, "#00ff00");
}
else {
game.debug.text("Ran out of time!", 500, 100, "#ff0000");
game.state.start('GameOver');
}
if(this.PlayerAlive && this.fireButton.isDown) {
this.fireLazers();
this.pew.play();
}
game.physics.arcade.overlap( this.lazers, this.enemies, this.lazerHitsEnemy, null, this);
this.game.physics.arcade.collide(this.enemies, this.player, this.enemyHitPlayer,null, this);
this.game.physics.arcade.collide(this.enemies, this.lazers, this.lazerHitsEnemy,null, this);
if (this.instructions.exists && this.time.now > this.instExpire) {
this.instructions.destroy();
}
},
lazerHitsEnemy : function(lazer, enemy) {
if(this.enemies.getIndex(enemy) > -1)
this.enemies.remove(enemy);
this.boom.play();
enemy.kill();
lazer.kill();
this.score += 10;
this.scoreText.setText("Score : "+this.score);
// And create an explosion
var explosion = this.explosions.getFirstExists(false);
explosion.reset(enemy.body.x, enemy.body.y);
explosion.play('boom', 30, false, true);
},
enemyHitPlayer : function(player, enemy){
if(this.enemies.getIndex(enemy) > -1)
this.enemies.remove(enemy);
enemy.kill();
this.ouch.play();
this.lives -= 1;
this.livesText.setText("Lives : "+this.lives);
var explosion = this.explosions.getFirstExists(false);
explosion.reset(player.body.x, player.body.y);
explosion.reset(enemy.body.x, enemy.body.y);
explosion.play('boom', 30, false, true);
game.physics.arcade.overlap(this.player, this.enemies, this.enemyHitPlayer, null, this);
if(this.lives < 0)
this.game.state.start('GameOver');
},
fireLazers : function() {
if( this.lazerTime == null )
this.lazerTime = this.game.time.now;
if ( this.game.time.now > this.lazerTime )
{
var lazer = this.lazers.getFirstExists(false);
lazer.reset( this.player.x, this.player.y);
this.player.angle = this.player.angle;
lazer.body.velocity.y = Math.cos( this.player.angle * (Math.PI/180) ) * (-400);
lazer.body.velocity.x = Math.sin( this.player.angle * (Math.PI/180) ) * 400;
this.lazerTime = this.game.time.now + 300;
lazer.rotation = true;
if (this.tracking)
{
this.rotation = Math.atan2(this.body.velocity.y, this.body.velocity.x);
}
if (this.scaleSpeed > 0)
{
this.scale.x += this.scaleSpeed;
this.scale.y += this.scaleSpeed;
}
}
},
addToScore: function (score) {
this.score += score;
this.scoreText.text = this.score;
},
spawnEnemy: function() {
var enemy = this.enemies.getFirstExists(false);
var MIN_ENEMY_SPACING = 200;
var MAX_ENEMY_SPACING = 1000;
var ENEMY_SPEED = 200;
if (enemy) {
enemy.reset(game.rnd.integerInRange(0, game.width), -20);
enemy.body.velocity.x = game.rnd.integerInRange(-300, 300);
enemy.body.velocity.y = ENEMY_SPEED;
enemy.body.drag.x = 100;
this.wee.play('', 0, 0.3 );
enemy.update = function(){
enemy.angle = 20 - game.math.radToDeg(Math.atan2(enemy.body.velocity.x, enemy.body.velocity.y));
// Kill enemies once they go off screen
if (enemy.y > game.height + 200) {
enemy.kill();
}
}
}
},
setupExplosions: function() {
this.explosions = game.add.group();
this.explosions.physicsBodyType = Phaser.Physics.ARCADE;
this.explosions.createMultiple(30, 'lazerBall');
this.explosions.forEach( function(explosion ) {
explosion.anchor.x = 0.5;
explosion.anchor.y = 0.5;
explosion.animations.add('boom');
}, this );
},
setupButtons: function() {
this.cursors = game.input.keyboard.createCursorKeys();
this.fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
},
setupLazers: function() {
this.lazers = this.game.add.group();
this.lazers.enableBody = true;
this.lazers.physicsBodyType = Phaser.Physics.ARCADE;
this.lazers.createMultiple(30, 'lazers');
this.lazers.setAll('anchor.x', 0.5);
this.lazers.setAll('anchor.y', 0.5);
this.lazers.setAll('outOfBoundsKill', true);
this.lazers.setAll('checkWorldBounds', true);
this.lazers.tracking = false;
this.lazers.scaleSpeed = 20;
},
setupEnemies: function() {
this.enemies = game.add.group();
this.enemies.enableBody = true;
this.enemies.physicsBodyType = Phaser.Physics.ARCADE;
this.enemies.scale.setTo(1.6);
this.enemies.createMultiple(30, 'enemy');
this.enemies.setAll('anchor.x', 0.5);
this.enemies.setAll('anchor.y', 0.5);
this.enemies.setAll('outOfBoundsKill', true);
this.enemies.setAll('checkWorldBounds', true);
this.enemies.callAll('animations.add', 'animations', 'fly10', [0,1,2,3,4,5,6,7,8,8,8, 9, 11,12,13,14,15,16,17,18,18,18,19, 20, 21], 4, true);
this.enemies.callAll('play', null, 'fly10');
this.enemyDelay = 200;
},
//////////PLAYER!!!!///////
setupPlayer: function() {
this.player = game.add.sprite(game.world.centerX, game.world.centerY, 'player');
this.player.anchor.set(0.5);
this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
this.player.body.allowRotation = false;
this.PlayerAlive = true;
this.catTrail = game.add.emitter(this.player.x, this.player.y + 50, 40);
this.catTrail = game.add.emitter(this.player.x - 50, this.player.y + 23, 400);
this.player.addChild(this.catTrail);
this.catTrail.start(false, 2000, 100);
this.catTrail.y = 0;
this.catTrail.x = 0;
this.catTrail.width =10;
this.catTrail.makeParticles('sparklebutt');
this.catTrail.setXSpeed(20, -20);
this.catTrail.setYSpeed(100, 90);
this.catTrail.setRotation(0,0);
this.catTrail.setScale(0.15, 0.8, 0.15, 0.8, 2000, Phaser.Easing.Quintic.Out);
},
};
|
/* eslint-disable no-tabs */
import Command from '@ckeditor/ckeditor5-core/src/command';
import { getSelectedMathModelWidget } from './utils';
export default class MathCommand extends Command {
execute( equation, display, outputType, forceOutputType ) {
const model = this.editor.model;
const selection = model.document.selection;
const selectedElement = selection.getSelectedElement();
model.change( writer => {
if ( selectedElement && ( selectedElement.is( 'mathtex' ) || selectedElement.is( 'mathtex-display' ) ) ) {
// Update selected element
const typeAttr = selectedElement.getAttribute( 'type' );
const existingEquation = selectedElement.getAttribute( 'equation' );
// Only update the element if the equation has changed
if ( existingEquation !== equation ) {
// Use already set type if found and is not forced
const type = forceOutputType ? outputType : typeAttr || outputType;
if ( equation ) {
const mathtex = writer.createElement( display ? 'mathtex-display' : 'mathtex', { equation, type } );
model.insertContent( mathtex );
writer.setSelection( mathtex, 'after' );
} else {
writer.remove( selectedElement );
}
}
} else {
// Create new model element
const mathtex = writer.createElement( display ? 'mathtex-display' : 'mathtex', { equation, type: outputType } );
model.insertContent( mathtex );
writer.setSelection( mathtex, 'after' );
}
} );
}
refresh() {
const model = this.editor.model;
const selection = model.document.selection;
const isAllowed = model.schema.checkChild( selection.focus.parent, 'mathtex' ) ||
model.schema.checkChild( selection.focus.parent, 'mathtex-display' );
this.isEnabled = isAllowed;
const selectedEquation = getSelectedMathModelWidget( selection );
if ( selectedEquation ) {
this.value = selectedEquation.getAttribute( 'equation' );
this.display = selectedEquation.is( 'mathtex-display ' ) ? true : false;
} else {
this.value = null;
this.display = null;
}
}
}
|
var watch = require('watch');
var exec = require('child_process').exec;
watch.createMonitor('', function (monitor) {
monitor.files['.js'] // Stat object for my zshrc.
monitor.on("created", function (f, stat) {
// Handle new files
})
monitor.on("changed", function (f, curr, prev) {
// Handle file changes
console.log(f);
//function puts(error, stdout, stderr) { sys.puts(stdout) }
//exec("r.js.cmd -o build.js");
})
monitor.on("removed", function (f, stat) {
// Handle removed files
})
}) |
var MessageFolderNewFormView = Backbone.View.extend({
events: {
"click button": "createFolder",
},
initialize: function() {
this.folderCollection = this.options.collection;
},
createFolder: function(){
//Only insert if text is written
var val = $(this.el).find("#folderName-input").val().trim();
var collection = this.folderCollection;
if(val.length){
var folder = new MessageFolder({name: val});
folder.save(null,{success: function(){
collection.add(folder);
}});
}
//TODO aqui estoy this.options.collection..destroy();
},
render: function() {
$(this.el).html(template.messagesView.newFolder());
return this;
}
}); |
"use strict";
var generateMetaData = function generateMetaData (rng, speedTendency, generosityTendency, difficulty) {
var difficultyFactor = Math.max(1, Math.pow(difficulty, 1 / 3)),
speed = rng() * speedTendency,
generosity = rng() * generosityTendency,
sum = speed + generosity,
ratio = 1 / sum;
// normalizing and apply difficult factor
return {
speed: speed * ratio * difficultyFactor,
generosity: generosity * ratio * difficultyFactor,
difficulty: difficultyFactor
};
};
module.exports = {
get: function (rng, tendencies, difficulty) {
difficulty += tendencies.difficulty;
return generateMetaData(rng.random, tendencies.speed, tendencies.generosity, difficulty);
}
};
|
var zlib = require('zlib');
var fs = require('fs');
var stream = require('stream');
var util = require('util');
var path = require('path');
var Pend = require('pend');
var findit = require('findit');
var mime = require('mime');
var url = require('url');
var BufferList = require('bl');
var crypto = require('crypto');
module.exports = createGzipStaticMiddleware;
function createGzipStaticMiddleware(options, cb) {
options = options || {};
var dir = options.dir || "public";
var ignoreFile = options.ignoreFile || defaultIgnoreFile;
var aliases = options.aliases || [['/', '/index.html']];
var cache = {};
var pend = new Pend();
var walker = findit(dir);
walker.on('error', function(err) {
walker.stop();
cb(err);
});
walker.on('file', function(file, stat) {
if (ignoreFile(file)) return;
var relName = '/' + path.relative(dir, file);
var bl = new BufferList();
var inStream = fs.createReadStream(file);
inStream.on('error', function(err) {
if (err.code === 'EISDIR') {
delete cache[relName];
return;
} else {
throw err;
}
});
var cacheObj;
cache[relName] = cacheObj = {
bl: bl,
mime: mime.lookup(relName),
mtime: stat.mtime,
hash: null,
};
pend.go(function(cb) {
inStream.pipe(zlib.createGzip()).pipe(bl);
bl.once('finish', cb);
});
pend.go(function(cb) {
var hashBl = new BufferList();
inStream.pipe(crypto.createHash('sha1')).pipe(hashBl);
hashBl.once('finish', function() {
cacheObj.hash = hashBl.toString('base64');
cb();
});
});
});
walker.on('end', function() {
pend.wait(function(err) {
if (err) return cb(err);
aliases.forEach(function(alias) {
cache[alias[0]] = cache[alias[1]];
});
cb(null, middleware);
});
function middleware(req, resp, next) {
var parsedUrl = url.parse(req.url);
var c = cache[parsedUrl.pathname];
if (!c) return next();
if (req.headers['if-none-match'] === c.hash) {
resp.statusCode = 304;
resp.end();
return;
}
var ifModifiedSince = new Date(req.headers['if-modified-since']);
if (!isNaN(ifModifiedSince) && c.mtime <= ifModifiedSince) {
resp.statusCode = 304;
resp.end();
return;
}
var bl = c.bl;
resp.setHeader('Content-Type', c.mime);
resp.setHeader('ETag', c.hash);
if (req.headers['accept-encoding'] == null) {
bl.duplicate().pipe(zlib.createGunzip()).pipe(resp);
} else {
resp.setHeader('Content-Encoding', 'gzip');
bl.duplicate().pipe(resp);
}
}
});
}
function defaultIgnoreFile(file) {
var basename = path.basename(file);
return /^\./.test(basename) || /~$/.test(basename);
}
|
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ModernizrWebpackPlugin = require('modernizr-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: "[name].[contenthash].css",
disable: process.env.NODE_ENV === "development"
});
const insertIndex = new HtmlWebpackPlugin({
template: path.join(__dirname, '../app/index.html'),
title: 'New app',
inject: true,
favicon: 'favicon.ico',
hash: true,
filename: 'index.html'
});
module.exports = {
entry: [
path.join(__dirname, "../app/index.jsx"),
],
output: {
path: path.join(__dirname, '../../dist/'),
filename: 'index.js',
},
module: {
rules: [{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}, {
loader: "postcss-loader"
}],
// use style-loader in development
fallback: "style-loader"
})
},
{
test: /\.css$/,
loaders: ["style-loader", "postcss-loader"]
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/,
query: {
plugin: [
"add-module-exports"
],
presets: ['es2015', 'react', 'stage-3']
}
},
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/,
options: {
plugins: [
'transform-class-properties',
"add-module-exports"
],
presets: ['es2015', 'react', 'stage-3']
},
},
{
test: /\.json?$/,
loader: 'json-loader'
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff"
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader?name=/fonts/[name].[ext]"
},
{
test: /\.(gif|png|jpe?g|svg)$/i,
loaders: [
'file-loader',
{
loader: 'image-webpack-loader',
query: {
mozjpeg: {
progressive: true,
},
gifsicle: {
interlaced: false,
},
optipng: {
optimizationLevel: 4,
},
pngquant: {
quality: '75-90',
speed: 3,
},
},
}
]
}
]
},
stats: {
colors: true
},
devtool: 'source-map',
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new ModernizrWebpackPlugin(),
new CopyWebpackPlugin([{
from: 'src/public'
}]),
extractSass,
insertIndex
]
}; |
/**
*
* MD5 (Message-Digest Algorithm)
* http://www.webtoolkit.info/
*
**/
var MD5 = function (string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function AddUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x,y,z) { return (x & y) | ((~x) & z); }
function G(x,y,z) { return (x & z) | (y & (~z)); }
function H(x,y,z) { return (x ^ y ^ z); }
function I(x,y,z) { return (y ^ (x | (~z))); }
function FF(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function GG(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function HH(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function II(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray=Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
};
function WordToHex(lValue) {
var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
}
return WordToHexValue;
};
function Utf8Encode(string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var x=Array();
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
return temp.toLowerCase();
}
|
module.exports = require('./setTransform'); |
// flow-typed signature: 28ab3537d8400cf87e81ee4edbd75ee5
// flow-typed version: c6154227d1/styled-components_v3.x.x/flow_>=v0.75.x <=v0.103.x
// @flow
type $npm$styledComponents$Interpolation = (<C: {}>(executionContext: C) => string) | string | number;
type $npm$styledComponents$NameGenerator = (hash: number) => string;
type $npm$styledComponents$TaggedTemplateLiteral<R> = {| (Array<string>, $npm$styledComponents$Interpolation): R |};
// ---- FUNCTIONAL COMPONENT DEFINITIONS ----
type $npm$styledComponents$ReactComponentFunctional<Props, DefaultProps = *> =
& { defaultProps: DefaultProps }
& $npm$styledComponents$ReactComponentFunctionalUndefinedDefaultProps<Props>
type $npm$styledComponents$ReactComponentFunctionalUndefinedDefaultProps<Props> =
React$StatelessFunctionalComponent<Props>
// ---- CLASS COMPONENT DEFINITIONS ----
class $npm$styledComponents$ReactComponent<Props, DefaultProps> extends React$Component<Props> {
static defaultProps: DefaultProps
}
type $npm$styledComponents$ReactComponentClass<Props, DefaultProps = *> = Class<$npm$styledComponents$ReactComponent<Props, DefaultProps>>
type $npm$styledComponents$ReactComponentClassUndefinedDefaultProps<Props> = Class<React$Component<Props, *>>
// ---- COMPONENT FUNCTIONS INPUT (UNION) & OUTPUT (INTERSECTION) ----
type $npm$styledComponents$ReactComponentUnion<Props> =
$npm$styledComponents$ReactComponentUnionWithDefaultProps<Props, *>
type $npm$styledComponents$ReactComponentUnionWithDefaultProps<Props, DefaultProps> =
| $npm$styledComponents$ReactComponentFunctional<Props, DefaultProps>
| $npm$styledComponents$ReactComponentFunctionalUndefinedDefaultProps<Props>
| $npm$styledComponents$ReactComponentClass<Props, DefaultProps>
| $npm$styledComponents$ReactComponentClassUndefinedDefaultProps<Props>
type $npm$styledComponents$ReactComponentIntersection<Props, DefaultProps = *> =
& $npm$styledComponents$ReactComponentFunctional<Props, DefaultProps>
& $npm$styledComponents$ReactComponentClass<Props, DefaultProps>;
// ---- WITHCOMPONENT ----
type $npm$styledComponents$ReactComponentStyledWithComponent<ComponentList> = <
Props, DefaultProps,
Input:
| ComponentList
| $npm$styledComponents$ReactComponentStyled<Props, DefaultProps>
| $npm$styledComponents$ReactComponentUnionWithDefaultProps<Props, DefaultProps>
>(Input) => $npm$styledComponents$ReactComponentStyled<Props, DefaultProps>
// ---- STATIC PROPERTIES ----
type $npm$styledComponents$ReactComponentStyledStaticProps<Props, ComponentList> = {|
attrs: <AdditionalProps: {}>(AdditionalProps) => $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteral<Props & AdditionalProps, ComponentList>,
extend: $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteral<Props, ComponentList>,
|}
type $npm$styledComponents$ReactComponentStyledStaticPropsWithComponent<Props, ComponentList> = {|
withComponent: $npm$styledComponents$ReactComponentStyledWithComponent<ComponentList>,
attrs: <AdditionalProps: {}>(AdditionalProps) => $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<Props & AdditionalProps, ComponentList>,
extend: $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<Props, ComponentList>,
|}
// ---- STYLED FUNCTION ----
// Error: styled(CustomComponent).withComponent('a')
// Ok: styled('div').withComponent('a')
type $npm$styledComponents$Call<ComponentListKeys> =
& (ComponentListKeys => $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<{}, ComponentListKeys>)
& (<Props>($npm$styledComponents$ReactComponentUnion<Props>) => $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteral<Props, ComponentListKeys>)
// ---- STYLED COMPONENT ----
type $npm$styledComponents$ReactComponentStyled<Props, ComponentList, DefaultProps = *> =
& $npm$styledComponents$ReactComponentStyledStaticPropsWithComponent<Props, ComponentList>
& $npm$styledComponents$ReactComponentIntersection<Props, DefaultProps>
// ---- TAGGED TEMPLATE LITERAL ----
type $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteral<Props, ComponentList> =
& $npm$styledComponents$ReactComponentStyledStaticProps<Props, ComponentList>
& $npm$styledComponents$TaggedTemplateLiteral<$npm$styledComponents$ReactComponentStyled<Props, ComponentList>>
type $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<Props, ComponentList> =
& $npm$styledComponents$ReactComponentStyledStaticPropsWithComponent<Props, ComponentList>
& $npm$styledComponents$TaggedTemplateLiteral<$npm$styledComponents$ReactComponentStyled<Props, ComponentList>>
// ---- WITHTHEME ----
type $npm$styledComponents$WithThemeReactComponentClass = <
InputProps: { theme: $npm$styledComponents$Theme },
InputDefaultProps: {},
OutputProps: $Diff<InputProps, { theme: $npm$styledComponents$Theme }>,
OutputDefaultProps: InputDefaultProps & { theme: $npm$styledComponents$Theme },
>($npm$styledComponents$ReactComponentClass<InputProps, InputDefaultProps>) => $npm$styledComponents$ReactComponentClass<OutputProps, OutputDefaultProps>
type $npm$styledComponents$WithThemeReactComponentClassUndefinedDefaultProps = <
InputProps: { theme: $npm$styledComponents$Theme },
OutputProps: $Diff<InputProps, { theme: $npm$styledComponents$Theme }>,
>($npm$styledComponents$ReactComponentClassUndefinedDefaultProps<InputProps>) => $npm$styledComponents$ReactComponentClass<OutputProps, { theme: $npm$styledComponents$Theme }>
type $npm$styledComponents$WithThemeReactComponentFunctional = <
InputProps: { theme: $npm$styledComponents$Theme },
InputDefaultProps: {},
OutputProps: $Diff<InputProps, { theme: $npm$styledComponents$Theme }>,
OutputDefaultProps: InputDefaultProps & { theme: $npm$styledComponents$Theme },
>($npm$styledComponents$ReactComponentFunctional<InputProps, InputDefaultProps>) => $npm$styledComponents$ReactComponentFunctional<OutputProps, OutputDefaultProps>
type $npm$styledComponents$WithThemeReactComponentFunctionalUndefinedDefaultProps = <
InputProps: { theme: $npm$styledComponents$Theme },
OutputProps: $Diff<InputProps, { theme: $npm$styledComponents$Theme }>
>($npm$styledComponents$ReactComponentFunctionalUndefinedDefaultProps<InputProps>) => $npm$styledComponents$ReactComponentFunctional<OutputProps, { theme: $npm$styledComponents$Theme }>
type $npm$styledComponents$WithTheme =
& $npm$styledComponents$WithThemeReactComponentClass
& $npm$styledComponents$WithThemeReactComponentClassUndefinedDefaultProps
& $npm$styledComponents$WithThemeReactComponentFunctional
& $npm$styledComponents$WithThemeReactComponentFunctionalUndefinedDefaultProps
// ---- MISC ----
type $npm$styledComponents$Theme = $ReadOnly<{[key: string]: mixed}>;
type $npm$styledComponents$ThemeProviderProps = {
theme: $npm$styledComponents$Theme | ((outerTheme: $npm$styledComponents$Theme) => void)
};
class Npm$StyledComponents$ThemeProvider extends React$Component<$npm$styledComponents$ThemeProviderProps> {}
class Npm$StyledComponents$StyleSheetManager extends React$Component<{ sheet: mixed }> {}
class Npm$StyledComponents$ServerStyleSheet {
instance: StyleSheet
collectStyles: (children: any) => React$Node
getStyleTags: () => string
getStyleElement: () => React$Node
interleaveWithNodeStream: (readableStream: stream$Readable) => stream$Readable
}
type $npm$styledComponents$StyledComponentsComponentListKeys =
$Subtype<$Keys<$npm$styledComponents$StyledComponentsComponentList>>
type $npm$styledComponents$StyledComponentsComponentListValue =
$npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<{}, $npm$styledComponents$StyledComponentsComponentListKeys>
// ---- COMPONENT LIST ----
type $npm$styledComponents$StyledComponentsComponentList = {|
a: $npm$styledComponents$StyledComponentsComponentListValue,
abbr: $npm$styledComponents$StyledComponentsComponentListValue,
address: $npm$styledComponents$StyledComponentsComponentListValue,
area: $npm$styledComponents$StyledComponentsComponentListValue,
article: $npm$styledComponents$StyledComponentsComponentListValue,
aside: $npm$styledComponents$StyledComponentsComponentListValue,
audio: $npm$styledComponents$StyledComponentsComponentListValue,
b: $npm$styledComponents$StyledComponentsComponentListValue,
base: $npm$styledComponents$StyledComponentsComponentListValue,
bdi: $npm$styledComponents$StyledComponentsComponentListValue,
bdo: $npm$styledComponents$StyledComponentsComponentListValue,
big: $npm$styledComponents$StyledComponentsComponentListValue,
blockquote: $npm$styledComponents$StyledComponentsComponentListValue,
body: $npm$styledComponents$StyledComponentsComponentListValue,
br: $npm$styledComponents$StyledComponentsComponentListValue,
button: $npm$styledComponents$StyledComponentsComponentListValue,
canvas: $npm$styledComponents$StyledComponentsComponentListValue,
caption: $npm$styledComponents$StyledComponentsComponentListValue,
cite: $npm$styledComponents$StyledComponentsComponentListValue,
code: $npm$styledComponents$StyledComponentsComponentListValue,
col: $npm$styledComponents$StyledComponentsComponentListValue,
colgroup: $npm$styledComponents$StyledComponentsComponentListValue,
data: $npm$styledComponents$StyledComponentsComponentListValue,
datalist: $npm$styledComponents$StyledComponentsComponentListValue,
dd: $npm$styledComponents$StyledComponentsComponentListValue,
del: $npm$styledComponents$StyledComponentsComponentListValue,
details: $npm$styledComponents$StyledComponentsComponentListValue,
dfn: $npm$styledComponents$StyledComponentsComponentListValue,
dialog: $npm$styledComponents$StyledComponentsComponentListValue,
div: $npm$styledComponents$StyledComponentsComponentListValue,
dl: $npm$styledComponents$StyledComponentsComponentListValue,
dt: $npm$styledComponents$StyledComponentsComponentListValue,
em: $npm$styledComponents$StyledComponentsComponentListValue,
embed: $npm$styledComponents$StyledComponentsComponentListValue,
fieldset: $npm$styledComponents$StyledComponentsComponentListValue,
figcaption: $npm$styledComponents$StyledComponentsComponentListValue,
figure: $npm$styledComponents$StyledComponentsComponentListValue,
footer: $npm$styledComponents$StyledComponentsComponentListValue,
form: $npm$styledComponents$StyledComponentsComponentListValue,
h1: $npm$styledComponents$StyledComponentsComponentListValue,
h2: $npm$styledComponents$StyledComponentsComponentListValue,
h3: $npm$styledComponents$StyledComponentsComponentListValue,
h4: $npm$styledComponents$StyledComponentsComponentListValue,
h5: $npm$styledComponents$StyledComponentsComponentListValue,
h6: $npm$styledComponents$StyledComponentsComponentListValue,
head: $npm$styledComponents$StyledComponentsComponentListValue,
header: $npm$styledComponents$StyledComponentsComponentListValue,
hgroup: $npm$styledComponents$StyledComponentsComponentListValue,
hr: $npm$styledComponents$StyledComponentsComponentListValue,
html: $npm$styledComponents$StyledComponentsComponentListValue,
i: $npm$styledComponents$StyledComponentsComponentListValue,
iframe: $npm$styledComponents$StyledComponentsComponentListValue,
img: $npm$styledComponents$StyledComponentsComponentListValue,
input: $npm$styledComponents$StyledComponentsComponentListValue,
ins: $npm$styledComponents$StyledComponentsComponentListValue,
kbd: $npm$styledComponents$StyledComponentsComponentListValue,
keygen: $npm$styledComponents$StyledComponentsComponentListValue,
label: $npm$styledComponents$StyledComponentsComponentListValue,
legend: $npm$styledComponents$StyledComponentsComponentListValue,
li: $npm$styledComponents$StyledComponentsComponentListValue,
link: $npm$styledComponents$StyledComponentsComponentListValue,
main: $npm$styledComponents$StyledComponentsComponentListValue,
map: $npm$styledComponents$StyledComponentsComponentListValue,
mark: $npm$styledComponents$StyledComponentsComponentListValue,
menu: $npm$styledComponents$StyledComponentsComponentListValue,
menuitem: $npm$styledComponents$StyledComponentsComponentListValue,
meta: $npm$styledComponents$StyledComponentsComponentListValue,
meter: $npm$styledComponents$StyledComponentsComponentListValue,
nav: $npm$styledComponents$StyledComponentsComponentListValue,
noscript: $npm$styledComponents$StyledComponentsComponentListValue,
object: $npm$styledComponents$StyledComponentsComponentListValue,
ol: $npm$styledComponents$StyledComponentsComponentListValue,
optgroup: $npm$styledComponents$StyledComponentsComponentListValue,
option: $npm$styledComponents$StyledComponentsComponentListValue,
output: $npm$styledComponents$StyledComponentsComponentListValue,
p: $npm$styledComponents$StyledComponentsComponentListValue,
param: $npm$styledComponents$StyledComponentsComponentListValue,
picture: $npm$styledComponents$StyledComponentsComponentListValue,
pre: $npm$styledComponents$StyledComponentsComponentListValue,
progress: $npm$styledComponents$StyledComponentsComponentListValue,
q: $npm$styledComponents$StyledComponentsComponentListValue,
rp: $npm$styledComponents$StyledComponentsComponentListValue,
rt: $npm$styledComponents$StyledComponentsComponentListValue,
ruby: $npm$styledComponents$StyledComponentsComponentListValue,
s: $npm$styledComponents$StyledComponentsComponentListValue,
samp: $npm$styledComponents$StyledComponentsComponentListValue,
script: $npm$styledComponents$StyledComponentsComponentListValue,
section: $npm$styledComponents$StyledComponentsComponentListValue,
select: $npm$styledComponents$StyledComponentsComponentListValue,
small: $npm$styledComponents$StyledComponentsComponentListValue,
source: $npm$styledComponents$StyledComponentsComponentListValue,
span: $npm$styledComponents$StyledComponentsComponentListValue,
strong: $npm$styledComponents$StyledComponentsComponentListValue,
style: $npm$styledComponents$StyledComponentsComponentListValue,
sub: $npm$styledComponents$StyledComponentsComponentListValue,
summary: $npm$styledComponents$StyledComponentsComponentListValue,
sup: $npm$styledComponents$StyledComponentsComponentListValue,
table: $npm$styledComponents$StyledComponentsComponentListValue,
tbody: $npm$styledComponents$StyledComponentsComponentListValue,
td: $npm$styledComponents$StyledComponentsComponentListValue,
textarea: $npm$styledComponents$StyledComponentsComponentListValue,
tfoot: $npm$styledComponents$StyledComponentsComponentListValue,
th: $npm$styledComponents$StyledComponentsComponentListValue,
thead: $npm$styledComponents$StyledComponentsComponentListValue,
time: $npm$styledComponents$StyledComponentsComponentListValue,
title: $npm$styledComponents$StyledComponentsComponentListValue,
tr: $npm$styledComponents$StyledComponentsComponentListValue,
track: $npm$styledComponents$StyledComponentsComponentListValue,
u: $npm$styledComponents$StyledComponentsComponentListValue,
ul: $npm$styledComponents$StyledComponentsComponentListValue,
var: $npm$styledComponents$StyledComponentsComponentListValue,
video: $npm$styledComponents$StyledComponentsComponentListValue,
wbr: $npm$styledComponents$StyledComponentsComponentListValue,
// SVG
circle: $npm$styledComponents$StyledComponentsComponentListValue,
clipPath: $npm$styledComponents$StyledComponentsComponentListValue,
defs: $npm$styledComponents$StyledComponentsComponentListValue,
ellipse: $npm$styledComponents$StyledComponentsComponentListValue,
g: $npm$styledComponents$StyledComponentsComponentListValue,
image: $npm$styledComponents$StyledComponentsComponentListValue,
line: $npm$styledComponents$StyledComponentsComponentListValue,
linearGradient: $npm$styledComponents$StyledComponentsComponentListValue,
mask: $npm$styledComponents$StyledComponentsComponentListValue,
path: $npm$styledComponents$StyledComponentsComponentListValue,
pattern: $npm$styledComponents$StyledComponentsComponentListValue,
polygon: $npm$styledComponents$StyledComponentsComponentListValue,
polyline: $npm$styledComponents$StyledComponentsComponentListValue,
radialGradient: $npm$styledComponents$StyledComponentsComponentListValue,
rect: $npm$styledComponents$StyledComponentsComponentListValue,
stop: $npm$styledComponents$StyledComponentsComponentListValue,
svg: $npm$styledComponents$StyledComponentsComponentListValue,
text: $npm$styledComponents$StyledComponentsComponentListValue,
tspan: $npm$styledComponents$StyledComponentsComponentListValue,
|}
type $npm$styledComponents$StyledComponentsNativeComponentListKeys =
$Subtype<$Keys<$npm$styledComponents$StyledComponentsNativeComponentList>>
type $npm$styledComponents$StyledComponentsNativeComponentListValue =
$npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<{}, $npm$styledComponents$StyledComponentsNativeComponentListKeys>
type $npm$styledComponents$StyledComponentsNativeComponentList = {|
ActivityIndicator: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ActivityIndicatorIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ART: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Button: $npm$styledComponents$StyledComponentsNativeComponentListValue,
DatePickerIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
DrawerLayoutAndroid: $npm$styledComponents$StyledComponentsNativeComponentListValue,
FlatList: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Image: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ImageBackground: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ImageEditor: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ImageStore: $npm$styledComponents$StyledComponentsNativeComponentListValue,
KeyboardAvoidingView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ListView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
MapView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Modal: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Navigator: $npm$styledComponents$StyledComponentsNativeComponentListValue,
NavigatorIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Picker: $npm$styledComponents$StyledComponentsNativeComponentListValue,
PickerIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ProgressBarAndroid: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ProgressViewIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
RecyclerViewBackedScrollView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
RefreshControl: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SafeAreaView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ScrollView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SectionList: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SegmentedControlIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Slider: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SliderIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SnapshotViewIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
StatusBar: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SwipeableListView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Switch: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SwitchAndroid: $npm$styledComponents$StyledComponentsNativeComponentListValue,
SwitchIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
TabBarIOS: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Text: $npm$styledComponents$StyledComponentsNativeComponentListValue,
TextInput: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ToastAndroid: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ToolbarAndroid: $npm$styledComponents$StyledComponentsNativeComponentListValue,
Touchable: $npm$styledComponents$StyledComponentsNativeComponentListValue,
TouchableHighlight: $npm$styledComponents$StyledComponentsNativeComponentListValue,
TouchableNativeFeedback: $npm$styledComponents$StyledComponentsNativeComponentListValue,
TouchableOpacity: $npm$styledComponents$StyledComponentsNativeComponentListValue,
TouchableWithoutFeedback: $npm$styledComponents$StyledComponentsNativeComponentListValue,
View: $npm$styledComponents$StyledComponentsNativeComponentListValue,
ViewPagerAndroid: $npm$styledComponents$StyledComponentsNativeComponentListValue,
VirtualizedList: $npm$styledComponents$StyledComponentsNativeComponentListValue,
WebView: $npm$styledComponents$StyledComponentsNativeComponentListValue,
|}
declare module 'styled-components' {
declare export type Interpolation = $npm$styledComponents$Interpolation;
declare export type NameGenerator = $npm$styledComponents$NameGenerator;
declare export type Theme = $npm$styledComponents$Theme;
declare export type ThemeProviderProps = $npm$styledComponents$ThemeProviderProps;
declare export type TaggedTemplateLiteral<R> = $npm$styledComponents$TaggedTemplateLiteral<R>;
declare export type ComponentListKeys = $npm$styledComponents$StyledComponentsComponentListKeys;
declare export type ReactComponentFunctional<Props: {}, DefaultProps: ?{} = *> = $npm$styledComponents$ReactComponentFunctional<Props, DefaultProps>;
declare export type ReactComponentFunctionalUndefinedDefaultProps<Props: {}> = $npm$styledComponents$ReactComponentFunctionalUndefinedDefaultProps<Props>;
declare export type ReactComponentClass<Props: {}, DefaultProps: ?{} = *> = $npm$styledComponents$ReactComponentClass<Props, DefaultProps>;
declare export type ReactComponentClassUndefinedDefaultProps<Props: {}> = $npm$styledComponents$ReactComponentClassUndefinedDefaultProps<Props>;
declare export type ReactComponentUnion<Props> = $npm$styledComponents$ReactComponentUnion<Props>;
declare export type ReactComponentIntersection<Props> = $npm$styledComponents$ReactComponentIntersection<Props>;
declare export type ReactComponentStyledStaticProps<Props> = $npm$styledComponents$ReactComponentStyledStaticPropsWithComponent<Props, ComponentListKeys>;
declare export type ReactComponentStyled<Props> = $npm$styledComponents$ReactComponentStyled<Props, ComponentListKeys>;
declare export type ReactComponentStyledTaggedTemplateLiteral<Props> = $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<Props, ComponentListKeys>;
declare export var css: TaggedTemplateLiteral<Array<Interpolation>>;
declare export var injectGlobal: TaggedTemplateLiteral<void>;
declare export var keyframes: TaggedTemplateLiteral<string>;
declare export var withTheme: $npm$styledComponents$WithTheme;
declare export var ServerStyleSheet: typeof Npm$StyledComponents$ServerStyleSheet;
declare export var StyleSheetManager: typeof Npm$StyledComponents$StyleSheetManager;
declare export var ThemeProvider: typeof Npm$StyledComponents$ThemeProvider;
declare export default {
css: TaggedTemplateLiteral<Array<Interpolation>>,
...$npm$styledComponents$StyledComponentsComponentList,
...$npm$styledComponents$StyledComponentsNativeComponentList,
} & {
[[call]]: $npm$styledComponents$Call<ComponentListKeys>
}
}
declare module 'styled-components/native' {
declare export type Interpolation = $npm$styledComponents$Interpolation;
declare export type NameGenerator = $npm$styledComponents$NameGenerator;
declare export type Theme = $npm$styledComponents$Theme;
declare export type ThemeProviderProps = $npm$styledComponents$ThemeProviderProps;
declare export type TaggedTemplateLiteral<R> = $npm$styledComponents$TaggedTemplateLiteral<R>;
declare export type NativeComponentListKeys = $npm$styledComponents$StyledComponentsNativeComponentListKeys;
declare export type ReactComponentFunctional<Props: {}, DefaultProps: ?{} = *> = $npm$styledComponents$ReactComponentFunctional<Props, DefaultProps>;
declare export type ReactComponentFunctionalUndefinedDefaultProps<Props: {}> = $npm$styledComponents$ReactComponentFunctionalUndefinedDefaultProps<Props>;
declare export type ReactComponentClass<Props: {}, DefaultProps: ?{} = *> = $npm$styledComponents$ReactComponentClass<Props, DefaultProps>;
declare export type ReactComponentClassUndefinedDefaultProps<Props: {}> = $npm$styledComponents$ReactComponentClassUndefinedDefaultProps<Props>;
declare export type ReactComponentUnion<Props> = $npm$styledComponents$ReactComponentUnion<Props>;
declare export type ReactComponentIntersection<Props> = $npm$styledComponents$ReactComponentIntersection<Props>;
declare export type ReactComponentStyledStaticProps<Props> = $npm$styledComponents$ReactComponentStyledStaticPropsWithComponent<Props, NativeComponentListKeys>;
declare export type ReactComponentStyled<Props> = $npm$styledComponents$ReactComponentStyled<Props, NativeComponentListKeys>;
declare export type ReactComponentStyledTaggedTemplateLiteral<Props> = $npm$styledComponents$ReactComponentStyledTaggedTemplateLiteralWithComponent<Props, NativeComponentListKeys>;
declare export var keyframes: TaggedTemplateLiteral<string>;
declare export var withTheme: $npm$styledComponents$WithTheme;
declare export var ThemeProvider: typeof Npm$StyledComponents$ThemeProvider;
declare export default {
css: TaggedTemplateLiteral<Array<Interpolation>>,
...$npm$styledComponents$StyledComponentsNativeComponentList,
} & {
[[call]]: $npm$styledComponents$Call<NativeComponentListKeys>
}
}
|
/************************************************************************
*
* Contains enumerators for Settings
*
************************************************************************/
define(['ko'],
function (ko) {
//check Esoft.Common.Settings.EnumSettingTypes.MandatoryLevel !!! if anything changes here change also in Esoft.Common.Settings.EnumSettingTypes.MandatoryLevel!
var settingEnums = function () {
var self = this;
self.mandatoryLevel = [
{
name: 'Ignore - sme biti prazno',
id: 0
}, {
name: 'Warning - ZAŽELJENO, opozorilo če ni',
id: 1
}, {
name: 'Error - OBVEZNO, napaka če manjka',
id: 2
},
{
name: 'Hidden - skrij okno za vnos',
id: 3
}
];
return self;
};
return settingEnums;
/*
self.mandatoryLevel = [
{
name: 'Ignore',
id: 0
}, {
name: 'Warning',
id: 1
}, {
name: 'Error',
id: 2
}
];
self.settingEnums = ko.observable(new settingEnums());
*/
}); |
/* */
"format amd";
//! moment.js locale configuration
//! locale : Persian [fa]
//! author : Ebrahim Byagowi : https://github.com/ebraminio
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(["../moment"], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var symbolMap = {
'1': '۱',
'2': '۲',
'3': '۳',
'4': '۴',
'5': '۵',
'6': '۶',
'7': '۷',
'8': '۸',
'9': '۹',
'0': '۰'
}, numberMap = {
'۱': '1',
'۲': '2',
'۳': '3',
'۴': '4',
'۵': '5',
'۶': '6',
'۷': '7',
'۸': '8',
'۹': '9',
'۰': '0'
};
var fa = moment.defineLocale('fa', {
months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'),
weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'),
weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd, D MMMM YYYY HH:mm'
},
meridiemParse: /قبل از ظهر|بعد از ظهر/,
isPM: function (input) {
return /بعد از ظهر/.test(input);
},
meridiem : function (hour, minute, isLower) {
if (hour < 12) {
return 'قبل از ظهر';
} else {
return 'بعد از ظهر';
}
},
calendar : {
sameDay : '[امروز ساعت] LT',
nextDay : '[فردا ساعت] LT',
nextWeek : 'dddd [ساعت] LT',
lastDay : '[دیروز ساعت] LT',
lastWeek : 'dddd [پیش] [ساعت] LT',
sameElse : 'L'
},
relativeTime : {
future : 'در %s',
past : '%s پیش',
s : 'چندین ثانیه',
m : 'یک دقیقه',
mm : '%d دقیقه',
h : 'یک ساعت',
hh : '%d ساعت',
d : 'یک روز',
dd : '%d روز',
M : 'یک ماه',
MM : '%d ماه',
y : 'یک سال',
yy : '%d سال'
},
preparse: function (string) {
return string.replace(/[۰-۹]/g, function (match) {
return numberMap[match];
}).replace(/،/g, ',');
},
postformat: function (string) {
return string.replace(/\d/g, function (match) {
return symbolMap[match];
}).replace(/,/g, '،');
},
ordinalParse: /\d{1,2}م/,
ordinal : '%dم',
week : {
dow : 6, // Saturday is the first day of the week.
doy : 12 // The week that contains Jan 1st is the first week of the year.
}
});
return fa;
})); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.selfSign = selfSign;
exports.default = signCertificate;
var _opensslWrapper = require('openssl-wrapper');
var _opensslWrapper2 = _interopRequireDefault(_opensslWrapper);
var _lodash = require('lodash');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Self sign a CA certificate
*
* @param {string|boolean} opts.password pass in a string of password if the
* private key should be encrypted.
* (Use DES3 as default)
* @param {string} opts.key specifies the file to read the
* private key from
* @param {string} opts.req filename of the certficate request
* @param {number} opts.out filename of the certificate
* @param {number} opts.days set expiration date for the cert
* @return {Promise}
*/
function selfSign() {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref$password = _ref.password;
let password = _ref$password === undefined ? false : _ref$password;
var _ref$key = _ref.key;
let key = _ref$key === undefined ? 'untitled.key' : _ref$key;
var _ref$req = _ref.req;
let req = _ref$req === undefined ? 'untitled.csr' : _ref$req;
var _ref$out = _ref.out;
let out = _ref$out === undefined ? 'untitled.crt' : _ref$out;
var _ref$days = _ref.days;
let days = _ref$days === undefined ? 365 : _ref$days;
let wasEncrypted = (0, _lodash.isString)(password);
let opts = {
// `-signkey`
signkey: key,
// `-req`
req: true,
// `-sha256`,
sha256: true,
// `-in=<req>`
in: req,
// `-out=<out>`
out,
// `-days <days>`
days
};
// Add provided password
if (wasEncrypted) {
// `-passin=pass:<secret>`
opts.passin = `pass:${ password }`;
}
return _opensslWrapper2.default.qExec('x509', opts).then(function (buffer) {
return buffer;
}, function (err) {
if (err.match(/^Signature ok/)) {
return Promise.resolve(err);
} else {
return Promise.reject(err);
}
});
}
/**
* Sign a certificate
*
* @param {string|boolean} opts.password pass in a string of password if the
* private key should be encrypted.
* (Use DES3 as default)
* @param {string} opts.CACert filename of the CA cert
* @param {string} opts.CAkey filename of the CA's PK
* @param {string} opts.req filename of the certficate request
* @param {number} opts.out filename of the certificate
* @param {number} opts.days set expiration date for the cert
* @return {Promise}
*/
function signCertificate() {
var _ref2 = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref2$password = _ref2.password;
let password = _ref2$password === undefined ? false : _ref2$password;
var _ref2$CAcert = _ref2.CAcert;
let CAcert = _ref2$CAcert === undefined ? 'ca.crt' : _ref2$CAcert;
var _ref2$CAkey = _ref2.CAkey;
let CAkey = _ref2$CAkey === undefined ? 'ca.key' : _ref2$CAkey;
var _ref2$req = _ref2.req;
let req = _ref2$req === undefined ? 'untitled.csr' : _ref2$req;
var _ref2$out = _ref2.out;
let out = _ref2$out === undefined ? 'untitled.crt' : _ref2$out;
var _ref2$days = _ref2.days;
let days = _ref2$days === undefined ? 365 : _ref2$days;
var _ref2$extfile = _ref2.extfile;
let extfile = _ref2$extfile === undefined ? false : _ref2$extfile;
let wasEncrypted = (0, _lodash.isString)(password);
let hasExtraFile = (0, _lodash.isString)(extfile);
let opts = {
// `-req`
req: true,
// `-sha256`,
sha256: true,
// `-in=<req>`
in: req,
// `-CA=<CACert>`
CA: CAcert,
// `-CAkey=<CAkey>`
CAkey: CAkey,
// `-CAcreateserial`
CAcreateserial: true,
// `-out=<out>`
out,
// `-days <days>`
days
};
// Add provided password
if (wasEncrypted) {
// `-passin=pass:<secret>`
opts.passin = `pass:${ password }`;
}
// Supply an extra file for configuration
if (hasExtraFile) {
opts.extfile = extfile;
}
return _opensslWrapper2.default.qExec('x509', opts).then(function (buffer) {
return buffer;
}, function (err) {
if (err.match(/^Signature ok/)) {
return Promise.resolve(err);
} else {
return Promise.reject(err);
}
});
} |
import datastore from '@google-cloud/datastore';
import GCPConfig from '../../../config/settings';
import getEntityByIndexedValue from './getEntitiesByIndexedValue';
const datastoreClient = datastore({
projectId: GCPConfig.project_id,
keyFilename: GCPConfig.datastore.gcpDatastoreOwnerServiceKeyPath,
});
export default async function cloneEntity(entityObject) {
const newKind = `${entityObject.kind}-clones`;
let response = null;
const dsKey = null;
const entity = [];
const nameValues = Object.entries(entityObject);
nameValues.forEach((pair) => {
const name = pair[0];
const value = pair[1];
const tempObj = {};
if (pair[0] !== '_id' && pair[0] !== 'lastUpdated') {
tempObj.excludeFromIndexes = true;
}
tempObj.name = name;
tempObj.value = value;
entity.push(tempObj);
});
try {
const key = datastoreClient.key([newKind, dsKey]);
const data = entity;
const newEntity = {
key,
data,
};
response = await datastoreClient.save(newEntity).then(() => datastoreClient.get(key));
} catch (err) {
const errorPage = await getEntityByIndexedValue('Pages', 'slug', 'error-cloning-entity');
return console.log('errorPage', errorPage);
}
return response;
}
|
'use strict'
const Joi = require('joi')
const Fs = require('fs')
const Path = require('path')
const Readline = require('readline')
const randomElement = function (array) {
const randomIndex = Math.floor(Math.random() * array.length)
return array[randomIndex]
}
const NameManager = function (firstNameList, lastNameList) {
const load = function (file) {
return new Promise(function (resolve, reject) {
const names = []
const nameStream = Readline.createInterface({
input: Fs.createReadStream(file)
})
nameStream.on('line', function (name) {
names.push(name)
})
nameStream.on('close', function () {
resolve(names)
})
})
}
this.lastNames = load(lastNameList)
this.firstNames = load(firstNameList)
}
NameManager.prototype.getLastName = function () {
return this.lastNames.then(randomElement)
}
NameManager.prototype.getFirstName = function () {
return this.firstNames.then(randomElement)
}
NameManager.prototype.getNames = function (count) {
count = count || 1
const names = []
for (let i = 0; i < count; i++) {
const name = Promise.all([
this.getFirstName(),
this.getLastName()
]).then(function (result) {
return result[0] + ' ' + result[1]
})
names.push(name)
}
return Promise.all(names)
}
exports.plugin = {
name: 'RandomNames',
version: '1.0.0',
register: (server, options) => {
const nameManager = new NameManager(
Path.join(__dirname, '..', '..', 'data', 'first_names.txt'),
Path.join(__dirname, '..', '..', 'data', 'last_names.txt')
)
const replyAccordingToAccept = ({ headers: { accept } }, h, response) => {
if (accept && (accept.indexOf('application/json') > -1)) {
return response
} else {
return h.response(response.join('\n')).type('text/plain')
}
}
server.route({
method: 'GET',
path: '/{number?}',
handler: async (request, h) => {
const names = await nameManager.getNames(request.params.number)
return replyAccordingToAccept(request, h, names)
},
options: {
tags: ['api'],
validate: {
params: Joi.object({
number: Joi.number().optional().min(1).max(100)
})
}
}
})
server.route({
method: 'GET',
path: '/first/{number?}',
handler: async (request, h) => {
const names = []
for (let i = 0; i < request.params.number; i++) {
names.push(nameManager.getFirstName())
}
const response = await Promise.all(names)
return replyAccordingToAccept(request, h, response)
},
options: {
tags: ['api'],
validate: {
params: Joi.object({
number: Joi.number().optional().min(1).max(100).default(1)
})
}
}
})
server.route({
method: 'GET',
path: '/last/{number?}',
handler: async (request, h) => {
const names = []
for (let i = 0; i < request.params.number; i++) {
names.push(nameManager.getLastName())
}
const response = await Promise.all(names)
return replyAccordingToAccept(request, h, response)
},
options: {
tags: ['api'],
validate: {
params: Joi.object({
number: Joi.number().optional().min(1).max(100).default(1)
})
}
}
})
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.