code
stringlengths
2
1.05M
import React, { PropTypes } from 'react'; import { render } from 'react-dom'; import { Container, Row, Col } from 'reactstrap'; import Footer from './Shared/Footer'; class Index extends React.Component { render() { return ( <div> <Container> <Row> <Col> <h1>404: Not Found</h1> <p>You seem to be lost, buddy.</p> </Col> </Row> </Container> <Footer/> </div> ); } } export default Index;
import { connect } from 'react-redux' import { toggleTodo } from '../../../api/actions/todo' import TodoList from '../../components/TodoComponents/List' const getVisibleTodos = (todos, filter) => { switch (filter) { case 'SHOW_ALL': return todos case 'SHOW_COMPLETED': return todos.filter(t => t.completed) case 'SHOW_ACTIVE': return todos.filter(t => !t.completed) default: throw new Error('Unknown filter: ' + filter) } } const mapStateToProps = (state) => ({ todos: getVisibleTodos(state.todos, state.visibilityFilter) }) const mapDispatchToProps = ({ onTodoClick: toggleTodo }) const VisibleTodoList = connect( mapStateToProps, mapDispatchToProps )(TodoList) export default VisibleTodoList
'use strict'; module.exports = angular.module('modules', [ require('./home').name, require('./customer').name, require('./pages').name // Used for static content pages like "About", "Privacy Policy", "404", etc. ]) .controller('MainCtrl', require('./MainController'));
export const $ = window.jQuery export function activePage (query = '') { return $('.ui-page-active ' + query) }
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('healthcare-service-available-time', 'Unit | Model | HealthcareService_AvailableTime', { needs: [ 'model:meta', 'model:narrative', 'model:resource', 'model:extension' ] }); test('it exists', function(assert) { const model = this.subject(); assert.ok(!!model); });
var res = require('./res'), req = http('./req'); module.export = { Res: Res, Req: Req };
'use strict'; function getEndpoint(origin, destination) { var url = "http://localhost:8090/api/directions/transit"; return url.concat("?") .concat("origin=").concat(origin) .concat("&") .concat("destination=").concat(destination); } angular.module('myApp.trip', ['ngRoute', 'uiGmapgoogle-maps']) .config(['$routeProvider', 'uiGmapGoogleMapApiProvider', function ($routeProvider, uiGmapGoogleMapApiProvider) { $routeProvider.when('/trip', { templateUrl: 'trip/trip.html', controller: 'TripController' }); uiGmapGoogleMapApiProvider.configure({ key: 'AIzaSyBgoA-rLWenr8clGOAAkrLoa1iEjwDse4c', v: '3.17', libraries: 'weather,geometry,visualization' }); }]) .controller('TripController', ["$scope", "$http", function ($scope, $http) { $scope.map = { center: { latitude: 10.486364, longitude: -66.874879 }, zoom: 13 }; $scope.getTrip = function (trip) { var endpoint = getEndpoint(trip.origin, trip.destination); $http.get(endpoint).success(function (data) { $scope.trip.steps = data.steps; //console.log("Steps", data.steps); var arrayLength = data.steps.length; $scope.map.polylines = []; for (var i = 0; i < arrayLength; i++) { $scope.map.polylines[i] = { path: data.steps[i].polyline, stroke: { color: '#6060FB', weight: 4 }, editable: true, draggable: false, geodesic: false, visible: true }; } }); //console.log("Origin", $scope.trip); } } ]);
'use strict'; angular.module('myCart', []).config(function () { });
import CombatDetection from './CombatDetection' export default class BoardState { constructor () { this.units = [] } addUnit (unit) { this.units.push(unit) } getUnits () { return this.units } advanceUnits () { this.units.forEach((u) => u.advance()) } killCombattingUnits () { const combatDetection = new CombatDetection(this.units) combatDetection.getCombats().forEach(participants => { participants.forEach(unit => unit.kill()) }) } removeDeadUnits () { this.units = this.units.filter(unit => { return unit.isAlive() }) } }
import assert from "assert"; import generateCombGuid from "../src/index"; describe("Array", () => { describe("generateCombGuid()", () => { it("should return a 36 char string", () => { let val = generateCombGuid(); assert.equal(val.length, 36); }); it("should have 5 segments split on -", () => { let val = generateCombGuid(); assert.equal(val.split("-").length, 5); }); // this does in fact address both previous tests it("should be RFC4122 formatted uuid", () => { let val = generateCombGuid(); // per SO; https://stackoverflow.com/questions/7905929/how-to-test-valid-uuid-guid/29742838 // format from source here; https://github.com/chriso/validator.js/blob/master/src/lib/isUUID.js const isValidGuidFormat = ch => ch.match( /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i ) !== null; assert.equal(isValidGuidFormat(val), true); }); it("should not create a duplicate after 50,000 runs", () => { let arr = []; for (let i = 0; i < 50000; i++) { arr.push(generateCombGuid()); } let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index); assert.equal(findDuplicates(arr), false); }).timeout(45000); }); });
module.exports = function(str) { if (str.charCodeAt(0) === 46 /* . */ && str.indexOf('/', 1) === -1) { return true; } var last = str.lastIndexOf('/'); return last !== -1 ? str.charCodeAt(last + 1) === 46 /* . */ : false; };
/** * @author Kevin Boogaard <{@link http://www.kevinboogaard.com/}> * @author Alex Antonides <{@link http://www.alex-antonides.com/}> * @license {@link https://github.com/kevinboogaard/Sports_World-Ball_Pit/blob/master/LICENSE} * @ignore */ var ADCore = ADCore || {}; var scene = scene || {}; /** * @namespace {String} Event * @memberof ADCore * @typedef {(String)} Event */ scene.Event = scene.Event || {}; /** * @event ON_SCENE_SWITCH * @memberof ADCore.Event */ scene.Event.ON_SCENE_SWITCH = "on_scene_switch"; ADCore.Sceneloader = (function () { /** * Loader of the scenes. * * @class Sceneloader * @constructor */ function Sceneloader() { /** * Load is made when calling the 'Initialize' method of the class. * @property {Scene} current - Current loaded scene. * @public * @default Null */ this.current = null; } var p = Sceneloader.prototype; /** * Load a scene in the game. * * @method Load * @memberof Sceneloader * @public * @param {Scene} scene - Scene to be loaded. * @param {Object} args - Arguments given to the scene. */ p.Load = function(constructor, args) { args = args || []; if (typeof constructor === "undefined") throw new Error("Scene doesn't exist: " + constructor); if (typeof constructor === "string") constructor = scene[constructor]; this.current = new constructor(...args); ADCore.phaser.add.existing(this.current); }; /** * Disposes the current scene in the game and loads a new scene. * * @method Switch * @memberof Sceneloader * @public * @param {Scene} scene - New scene to be loaded. * @param {Object} args - Arguments given to the scene. */ p.Switch = function(scene, args) { this.DisposeCurrent(); this.Load(scene, args); }; /** * Disposes the current scene in the game. * * @method DisposeCurrent * @memberof Sceneloader * @public */ p.DisposeCurrent = function(){ this.current.Dispose(); this.current.pendingDestroy = true; this.current = null; }; return Sceneloader; }());
// Run tasks with newer files only // // grunt-newer: <https://github.com/tschaub/grunt-newer> 'use strict'; module.exports = { // "grunt-newer" works fine without options. // If you need special configuration, insert it here. };
import React from 'react'; import { Route, Switch } from 'react-router-dom'; import { Provider } from 'react-redux'; import { ConnectedRouter } from 'react-router-redux'; import store, { history } from './store'; import ProtectedRoute from './components/protected-route'; import App from './components/app'; import AccountPage from './components/account/page'; import EventPage from './components/events/event-page'; import EditEventPage from './components/events/edit-event-page'; import CreateEventPage from './components/events/create-event-page'; import EventsPage from './components/events/events-page'; import HomePage from './components/home'; import PeoplePage from './components/people-page'; import ProfilePage from './components/profile-page'; import EditProfilePage from './components/edit-profile-page'; // TODO: code-split routes: /events/create const router = ( <Provider store={store}> <ConnectedRouter history={history}> <App> <Route exact path="/" component={HomePage} /> <Switch> <Route exact path="/events" component={EventsPage} /> <ProtectedRoute exact path="/events/create" component={CreateEventPage} /> <Route exact path="/events/:eventId" component={EventPage} /> <Route exact path="/events/:eventId/edit" component={EditEventPage} /> </Switch> <Switch> <ProtectedRoute exact path="/people" component={PeoplePage} /> <ProtectedRoute exact path="/people/:userId" component={ProfilePage} /> <ProtectedRoute exact path="/people/:userId/edit" component={EditProfilePage} /> </Switch> <Route exact path="/login" component={AccountPage} /> <Route exact path="/register" component={AccountPage} /> </App> </ConnectedRouter> </Provider> ); export default router;
#!/usr/bin/env node var fs = require('fs'); var YAML = require('yamljs'); var program = require('commander'); var meta = require('./lib/meta'); program .version(meta.VERSION) .usage('[options] -f <swagger file> -o <output>') .option('-f, --file [file]', 'Path to swagger file', 'swagger.yaml') .option('-o, --output [output]', 'Path to output file', 'lib/api/festivalsApi.js') .parse(process.argv); var CodeGen = require('swagger-js-codegen').CodeGen; YAML.load(program.file, function (swaggerDocs) { if (swaggerDocs === null) { throw new Error('Invalid file path: ' + program.file); } if (!program.output) { throw new Error('Invalid output path: ' + program.output); } var nodejsSourceCode = CodeGen.getCustomCode( { className: 'FestivalsApi', swagger: swaggerDocs, template: { class: fs.readFileSync('templates/node-class.mustache', 'utf-8'), method: fs.readFileSync('templates/method.mustache', 'utf-8'), request: fs.readFileSync('templates/node-request.mustache', 'utf-8') } } ); fs.writeFile(program.output, nodejsSourceCode, function (err) { if (err) { throw err; } console.log('ok'); }); });
// Normal function add(n1, n2) { return n1 + n2; } add(1, 2) // 3 // Curried function add(n1) { return function(n2) { return n1 + n2; } } add(1)(2) // 3
// Placeholders var encryptionPattern = new RegExp(":geheim:([A-Za-z0-9+/=]*):([A-Za-z0-9+/=]*):([A-Za-z0-9+/=]*):", "g"); // Run eval() in different scope, provide non blocking error handling. function methodExec(code, input, key) { try { eval("var method = " + code); return method(input, key); } catch(error) { console.error("Error in encryption/decryption method:", error); return "Error in encryption/decryption method"; } } var encryptFunction = function(input, el) { // Reset Regexp counter and parse input var methodid = el.methodid; var keyid = el.keyid; // Process if (settings.keys.find(k => k.id == keyid && k.methodid == methodid)) { var methodCode = settings.methods.find(m => m.id == methodid).encrypt; var encryptkey = settings.keys.find(k => k.id == keyid && k.methodid == methodid).encryptkey; var outputData = methodExec(methodCode, input, encryptkey); return ":geheim:" + methodid + ":" + keyid + ":" + outputData + ":"; } else { return input; } } var decryptFunction = function(input, el) { // Reset Regexp counter and parse input encryptionPattern.lastIndex = -1; var exec = encryptionPattern.exec(input); var methodid = exec[1]; var keyid = exec[2]; var data = exec[3]; // Store methodid and keyid with element if (el) { el.methodid = methodid; el.keyid = keyid; } // Process if (settings.keys.find(k => k.id == keyid && k.methodid == methodid)) { var methodCode = settings.methods.find(m => m.id == methodid).decrypt; var decryptkey = settings.keys.find(k => k.id == keyid && k.methodid == methodid).decryptkey; var outputData = methodExec(methodCode, data, decryptkey); return {processed: true, data: outputData}; } else { return {processed: false, data: input}; } } // New Getter and Setter functions var defineGetterValue = function() { if (this.getAttribute("geheim")) { return encryptFunction(this.originalValue, this); } else { return this.originalValue; } } var defineGetterEncryptedValue = function() { this.clearTextValue = this.originalValue; if (this.getAttribute("geheim")) { return encryptFunction(this.originalValue, this); } else { return this.originalValue; } } var defineSetterValue = function(val) { if (!this.getAttribute("geheim")) { if (val.substr(0, 8) == ":geheim:") { this.setAttribute("geheim", true); var clearText = decryptFunction(val, this); if (clearText.processed == true) { val = clearText.data; } else { this.setAttribute("geheimUnknown", true); } } } this.originalValue = val; } // Link functions Object.defineProperty(HTMLTextAreaElement.prototype, "originalValue", { get: HTMLTextAreaElement.prototype.__lookupGetter__("value"), set: HTMLTextAreaElement.prototype.__lookupSetter__("value") }); Object.defineProperty(HTMLTextAreaElement.prototype, "encryptedValue", { get: defineGetterEncryptedValue }); Object.defineProperty(HTMLTextAreaElement.prototype, "value", { get: defineGetterValue, set: defineSetterValue }); Object.defineProperty(HTMLInputElement.prototype, "originalValue", { get: HTMLInputElement.prototype.__lookupGetter__("value"), set: HTMLInputElement.prototype.__lookupSetter__("value") }); Object.defineProperty(HTMLInputElement.prototype, "encryptedValue", { get: defineGetterEncryptedValue }); Object.defineProperty(HTMLInputElement.prototype, "value", { get: defineGetterValue, set: defineSetterValue }); // Force all fields to reset their value so they use the new Getter and Setter var processElements = function() { // Prepare Textarea and Input by triggering a value change [].forEach.call(document.querySelectorAll("textarea, input[type=text], input:not([type])"), function(el) { el.value = el.originalValue; }); // Replace all encrypted text values var textNodes = document.createTreeWalker(document, NodeFilter.SHOW_TEXT, null, false); for (var node; node = textNodes.nextNode();) { if (encryptionPattern.test(node.wholeText)) { if (!node.parentNode.matches("textarea, input[type=text], input:not([type])")) { // Highlight that this text was originally encrypted node.parentNode.setAttribute("geheimText", true); // Show clear text node.nodeValue = node.nodeValue.replace(encryptionPattern, function(match) { var clearText = decryptFunction(match); if (clearText.processed == false) { // Unknown encryption method or key. node.parentNode.setAttribute("geheimTextUnknown", true); } return clearText.data; }); } } } } // Process all elements on page load window.addEventListener("load", processElements); // Process all elements on page changes window.addEventListener("load", function() { new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.addedNodes.length > 0) { processElements(); }; }); }).observe(document.body, { childList: true, subtree: true }); }); // Bind click event to toggle encryption status window.addEventListener("dblclick", function(event) { var el = event.target; toggleGeheimStatus(el); }); window.addEventListener("click", function(event) { var el = event.target; if (event.offsetY < 20 && (el.clientWidth - event.offsetX) < 20) { toggleGeheimStatus(el); } }); function toggleGeheimStatus(el) { if (el.matches("textarea, input[type=text], input:not([type])")) { if (el.getAttribute("geheim")) { el.removeAttribute("geheim"); } else { geheimPopup(el, { // Trim settings to only send non trivial information keys: settings.keys.map(function(k){return {id:k.id, name:k.name, methodid:k.methodid}}), methods: settings.methods.map(function(m){return {id:m.id, name:m.name}}) }); } el.value = el.originalValue; } } // Process form submit events window.addEventListener("submit", function(event) { [].forEach.call(event.target.querySelectorAll("textarea, input[type=text], input:not([type])"), function(el) { el.value = el.encryptedValue; }); window.setTimeout(function() { [].forEach.call(event.target.querySelectorAll("textarea, input[type=text], input:not([type])"), function(el) { el.value = el.clearTextValue; }); }, 0); }, true);
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('service:page-title-list', function(hooks) { setupTest(hooks); test('the list has no tokens by default', function (assert) { assert.equal(this.owner.lookup('service:page-title-list').tokens.length, 0); }); test('calling `push` adds a token to the end of the list', function (assert) { let list = this.owner.lookup('service:page-title-list'); list.push({ id: 1}); assert.equal(list.tokens.length, 1); }); test('tokens have next and previous tokens', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1 }; let second = { id: 2 }; let third = { id: 3 }; list.push(first); list.push(second); list.push(third); assert.equal(list.tokens.length, 3); assert.equal(first.previous, null); assert.equal(first.next, second); assert.equal(second.previous, first); assert.equal(second.next, third); assert.equal(third.previous, second); assert.equal(third.next, null); }); test('removing a token closes the hole in the list', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1 }; let second = { id: 2 }; let third = { id: 3 }; list.push(first); list.push(second); list.push(third); list.remove(2); assert.equal(list.tokens.length, 2); assert.equal(first.previous, null); assert.equal(first.next, third); assert.equal(second.previous, null); assert.equal(second.next, null); assert.equal(third.previous, first); assert.equal(third.next, null); }); test('the separator property is inherited by the previous token', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1, separator: 'a' }; let second = { id: 2 }; list.push(first); list.push(second); assert.equal(first.separator, 'a'); assert.equal(second.separator, 'a'); }); test('the separator property is not inherited if explicitly set', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1, separator: 'a' }; let second = { id: 2, separator: 'b' }; list.push(first); list.push(second); assert.equal(first.separator, 'a'); assert.equal(second.separator, 'b'); }); test('the prepend property is inherited by the previous token', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1, prepend: true }; let second = { id: 2 }; list.push(first); list.push(second); assert.ok(first.prepend); assert.ok(second.prepend); }); test('the prepend property is not inherited if explicitly set', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1, prepend: true }; let second = { id: 2, prepend: false }; list.push(first); list.push(second); assert.ok(first.prepend); assert.ok(!second.prepend); }); test('if the replace attribute is set, all previous tokens are hidden', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1 }; let second = { id: 2 }; let third = { id: 3, replace: true }; list.push(first); list.push(second); list.push(third); let tokens = list.get('sortedTokens'); assert.equal(tokens.length, 1); assert.equal(tokens[0].id, 3); }); test('any additional tokens added after replace are not hidden', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1 }; let second = { id: 2, replace: true }; let third = { id: 3 }; list.push(first); list.push(second); list.push(third); let tokens = list.get('sortedTokens'); assert.equal(tokens.length, 2); assert.equal(tokens[0].id, 3); assert.equal(tokens[1].id, 2); }); test('removing a token with replace: true will set all previous tokens to be visible', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1 }; let second = { id: 2, replace: true }; let third = { id: 3 }; list.push(first); list.push(second); list.push(third); list.remove(2); let tokens = list.get('sortedTokens'); assert.equal(tokens.length, 2); assert.equal(tokens[0].id, 3); assert.equal(tokens[1].id, 1); }); test('removing a token with replace: true will only set previous tokens up to the last replace: true to visible', function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1 }; let second = { id: 2, replace: true }; let third = { id: 3, replace: true }; list.push(first); list.push(second); list.push(third); list.remove(3); let tokens = list.get('sortedTokens'); assert.equal(tokens.length, 1); assert.equal(tokens[0].id, 2); }); test("null tokens aren't displayed as a string", function (assert) { let list = this.owner.lookup('service:page-title-list'); let first = { id: 1, title: '1' }; let second = { id: 2, title: null }; let third = { id: 3, title: '3' }; list.push(first); list.push(second); list.push(third); assert.equal(list.toString(), '3 | 1'); }); test("initial page-title defaults", function (assert) { let list = this.owner.lookup('service:page-title-list'); assert.equal(list._defaultConfig.separator, ' | '); assert.equal(list._defaultConfig.prepend, true); assert.equal(list._defaultConfig.replace, null); }); test("can change defaults from config", function (assert) { this.owner.register("config:environment", { pageTitle: { separator: ' & ', prepend: false, replace: true } }); let list = this.owner.lookup('service:page-title-list'); assert.equal(list._defaultConfig.separator, ' & '); assert.equal(list._defaultConfig.prepend, false); assert.equal(list._defaultConfig.replace, true); }); test("undefined config entries do not change defaults", function (assert) { this.owner.register("config:environment", { pageTitle: { separator: undefined, prepend: null, replace: undefined } }); let list = this.owner.lookup('service:page-title-list'); assert.equal(list._defaultConfig.separator, ' | '); assert.equal(list._defaultConfig.prepend, true); assert.equal(list._defaultConfig.replace, null); }); });
/** * derived-classes-1 created on 6/30/16 10:10 AM. * * @description [To be completed] * @author Florian Popa <florian@webgenerals.com> */ class Point { constructor(a, b) { this.a = a; this.b = b; console.log('Point: ', this.a, this.b); } } class ColorPoint extends Point { static testMe() { } haveFun() { console.log('ColorPoint: ', this.a, this.b); } } const ColorPoint1 = new ColorPoint(); ColorPoint1.haveFun();
'use strict'; // see http://eslint.org/docs/rules/#stylistic-issues module.exports = { // Enforce spacing inside array brackets 'array-bracket-spacing': [2, 'never'], // Disallow or enforce spaces inside of single line blocks 'block-spacing': [2, 'always'], // Enforce one true brace style 'brace-style': [2, 'stroustrup', { allowSingleLine: true }], // Require camel case names 'camelcase': [2, { properties: 'always' }], // Disallow or enforce trailing commas 'comma-dangle': 2, // Enforce spacing before and after comma 'comma-spacing': [2, { before: false, after: true }], // Enforce consistent comma style 'comma-style': [2, 'last'], // Require or disallow padding inside computed properties 'computed-property-spacing': [2, 'never'], // Enforces consistent naming when capturing the current execution context 'consistent-this': [2, 'self'], // Enforce newline at the end of file, with no multiple empty lines 'eol-last': 2, // Disallow spacing between function identifiers and their invocations 'func-call-spacing': [2, 'never'], // Require function names to match the name of the variable or property to // which they are assigned 'func-name-matching': 2, // Don't require function expressions to have a name 'func-names': 0, // Enforces use of function declarations or expressions 'func-style': [2, 'expression'], // Blacklist certain identifiers to prevent them being used 'id-blacklist': 0, // This option enforces minimum and maximum identifier lengths (variable // names, property names etc.) 'id-length': [2, { exceptions: ['x', 'y', 'z', 'a', 'e', 'i', 'j', 'k', 'v', '_'], min: 2, properties: 'always' }], // Require identifiers to match the provided regular expression 'id-match': 0, // Enforce consistent indentation 'indent': [2, 2, { CallExpression: { arguments: 1 }, SwitchCase: 1 }], // Specify whether double or single quotes should be used in JSX attributes 'jsx-quotes': [2, 'prefer-double'], // Enforces spacing between keys and values in object literal properties 'key-spacing': [2, { beforeColon: false, afterColon: true }], // Enforce spacing before and after keywords 'keyword-spacing': 2, // Enforce position of line comments 'line-comment-position': 2, // Disallow mixed 'LF' and 'CRLF' as linebreaks 'linebreak-style': [2, 'unix'], // Enforces empty lines around comments 'lines-around-comment': [2, { allowArrayStart: true, allowBlockStart: true, allowObjectStart: true, beforeBlockComment: true, beforeLineComment: true }], // Require newlines around directives 'lines-around-directive': [2, { before: 'never', after: 'always' }], // Specify the maximum depth that blocks can be nested 'max-depth': [2, 4], // Specify the maximum length of a line in your program 'max-len': [2, 80, 4, { ignoreStrings: true, ignoreRegExpLiterals: true, ignoreTemplateLiterals: true, ignoreUrls: true }], // Enforce a maximum file length 'max-lines': [2, { max: 300, skipBlankLines: true, skipComments: true }], // Specify the maximum depth callbacks can be nested 'max-nested-callbacks': [2, 4], // Limits the number of parameters that can be used in the function // declaration. 'max-params': [2, 3], // Specify the maximum number of statement allowed in a function 'max-statements': [2, 15], // Enforce a maximum number of statements allowed per line 'max-statements-per-line': [2, { max: 2 }], // Enforce newlines between operands of ternary expressions 'multiline-ternary': 0, // Require a capital letter for constructors 'new-cap': 2, // Disallow the omission of parentheses when invoking a constructor with no // arguments 'new-parens': 2, // Allow/disallow an empty newline after var statement 'newline-after-var': 2, // Require newline before return statement 'newline-before-return': 2, // Don't enforce newline after each call when chaining the calls 'newline-per-chained-call': 0, // Disallow use of the Array constructor 'no-array-constructor': 2, // Disallow use of bitwise operators 'no-bitwise': 2, // Disallow use of the continue statement 'no-continue': 0, // Disallow comments inline after code 'no-inline-comments': 0, // Disallow if as the only statement in an else block 'no-lonely-if': 2, // Allow mixes of different operators 'no-mixed-operators': 0, // Disallow mixed spaces and tabs for indentation 'no-mixed-spaces-and-tabs': 2, // Disallow multiple empty lines 'no-multiple-empty-lines': [2, { max: 1, maxEOF: 1 }], // Disallow negated conditions 'no-negated-condition': 2, // Disallow nested ternary expressions 'no-nested-ternary': 2, // Disallow use of the Object constructor 'no-new-object': 2, // Disallow use of unary operators, ++ and -- 'no-plusplus': [2, { allowForLoopAfterthoughts: true }], // Disallow use of certain syntax in code 'no-restricted-syntax': 0, // Disallow tabs in file 'no-tabs': 2, // Disallow the use of ternary operators 'no-ternary': 0, // Disallow trailing whitespace at the end of lines 'no-trailing-spaces': 2, // Allow dangling underscores in identifiers 'no-underscore-dangle': 0, // Disallow the use of Boolean literals in conditional expressions 'no-unneeded-ternary': 2, // Disallow whitespace before properties 'no-whitespace-before-property': 2, // Require or disallow line breaks inside braces 'object-curly-newline': 0, // Require or disallow padding inside curly braces 'object-curly-spacing': [2, 'always', { objectsInObjects: false }], // Don't enforce placing object properties on separate lines 'object-property-newline': 0, // Allow or disallow one variable declaration per function 'one-var': [2, 'never'], // Require or disallow an newline around variable declarations 'one-var-declaration-per-line': [2, 'always'], // Require assignment operator shorthand where possible or prohibit it // entirely 'operator-assignment': [2, 'always'], // Enforce operators to be placed before or after line breaks 'operator-linebreak': [2, 'after', { overrides: { ':': 'before', '?': 'before' } }], // Enforce padding within blocks 'padded-blocks': [2, 'never'], // Require quotes around object literal property names 'quote-props': [2, 'as-needed'], // Specify whether backticks, double or single quotes should be used 'quotes': [2, 'single', 'avoid-escape'], // Don't require JSDoc comment 'require-jsdoc': 0, // Enforce spacing before and after semicolons 'semi-spacing': [2, { before: false, after: true }], // Require or disallow use of semicolons instead of ASI 'semi': [2, 'always'], // Don't require object keys to be sorted 'sort-keys': 0, // Sort variables within the same declaration block 'sort-vars': [2, { ignoreCase: false }], // Require or disallow space before blocks 'space-before-blocks': [2, 'always'], // Require or disallow space before function opening parenthesis 'space-before-function-paren': [2, { anonymous: 'never', asyncArrow: 'always', named: 'never' }], // Require or disallow spaces inside parentheses 'space-in-parens': [2, 'never'], // Require spaces around operators 'space-infix-ops': 2, // Require or disallow spaces before/after unary operators (words on by // default, nonwords) 'space-unary-ops': [2, { nonwords: false, words: true }], // Require or disallow a space immediately following the // or /* in a comment 'spaced-comment': [2, 'always'], // Require or disallow the Unicode Byte Order Mark (BOM) 'unicode-bom': 0, // Require regex literals to be wrapped in parentheses 'wrap-regex': 0 };
// -------------------------------------------------------------------------------------------------------------------- // // amazon.js - the base class for all Amazon Web Services // // Copyright (c) 2011 AppsAttic Ltd - http://www.appsattic.com/ // Written by Andrew Chilton <chilts@appsattic.com> // // License: http://opensource.org/licenses/MIT // // -------------------------------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------------------------------- // requires var util = require("util"); // our own library var awssum = require("awssum"); var awsSignatureV2 = require('./lib/aws-signature-v2.js'); var awsSignatureV4 = require('./lib/aws-signature-v4.js'); // -------------------------------------------------------------------------------------------------------------------- // constants var MARK = 'amazon: '; var US_EAST_1 = 'us-east-1'; var US_WEST_1 = 'us-west-1'; var US_WEST_2 = 'us-west-2'; var EU_WEST_1 = 'eu-west-1'; var AP_SOUTHEAST_1 = 'ap-southeast-1'; var AP_SOUTHEAST_2 = 'ap-southeast-2'; var AP_NORTHEAST_1 = 'ap-northeast-1'; var SA_EAST_1 = 'sa-east-1'; var US_GOV_WEST_1 = 'us-gov-west-1'; // See : http://aws.amazon.com/about-aws/globalinfrastructure/ var Region = { US_EAST_1 : true, US_WEST_1 : true, US_WEST_2 : true, EU_WEST_1 : true, AP_SOUTHEAST_1 : true, AP_SOUTHEAST_2 : true, AP_NORTHEAST_1 : true, SA_EAST_1 : true, US_GOV_WEST_1 : true, }; // -------------------------------------------------------------------------------------------------------------------- // constructor var Amazon = function(opts) { var self = this; var accessKeyId, secretAccessKey, awsAccountId, _awsAccountId, region, token; // call the superclass for initialisation Amazon.super_.call(this, opts); // check that we have each of these values if ( ! opts.accessKeyId ) { throw MARK + 'accessKeyID is required'; } if ( ! opts.secretAccessKey ) { throw MARK + 'secretAccessKey is required'; } if ( ! opts.region ) { throw MARK + 'region is required'; } // set the local vars so the functions below can close over them accessKeyId = opts.accessKeyId; secretAccessKey = opts.secretAccessKey; region = opts.region; // for services which can use the Simple Token Service (STS) if ( opts.token ) { token = opts.token; } // getters and setters self.setAccessKeyId = function(newStr) { accessKeyId = newStr; }; self.setSecretAccessKey = function(newStr) { secretAccessKey = newStr; }; self.setAwsAccountId = function(newStr) { var m; if ( m = newStr.match(/^(\d{4})(\d{4})(\d{4})$/) ) { awsAccountId = newStr; _awsAccountId = m[1] + '-' + m[2] + '-' + m[3]; } else if ( m = newStr.match(/^\d{4}-\d{4}-\d{4}$/) ) { _awsAccountId = newStr; awsAccountId = newStr.replace(/-/g, ''); } else { throw MARK + "invalid awsAccountId, must be '111122223333' or '1111-2222-3333'"; } }; self.accessKeyId = function() { return accessKeyId; }; self.secretAccessKey = function() { return secretAccessKey; }; self.region = function() { return region; }; self.awsAccountId = function() { return awsAccountId; }; self._awsAccountId = function() { return _awsAccountId; }; self.token = function() { return token; }; // use the setAwsAccountId setter (which contains extra logic) if ( opts.awsAccountId ) { self.setAwsAccountId(opts.awsAccountId); } return self; }; // inherit from AwsSum util.inherits(Amazon, awssum.AwsSum); // -------------------------------------------------------------------------------------------------------------------- // functions to be overriden by inheriting class // see ../awssum.js for more details Amazon.prototype.extractBody = function() { // most amazon services return XML, so override in inheriting classes if needed return 'xml'; }; // -------------------------------------------------------------------------------------------------------------------- // functions to be overriden by inheriting (Amazon) class // function version() -> string (the version of this service) // function signatureVersion() -> string (the signature version used) // function signatureMethod() -> string (the signature method used) // function strToSign(options) -> string (the string that needs to be signed) // function signature(strToSign) -> string (the signature itself) // function addSignature(options, signature) -> side effect, adds the signature to the 'options' // -------------------------------------------------------------------------------------------------------------------- // create 2 other versions of the Amazon constructor for v2 and v4 signatures // This service uses (defaults to) the AWS Signature v2. var AmazonSignatureV2 = function(opts) { var self = this; // call the superclass for initialisation AmazonSignatureV2.super_.call(self, opts); return self; }; util.inherits(AmazonSignatureV2, Amazon); AmazonSignatureV2.prototype.signatureVersion = awsSignatureV2.signatureVersion; AmazonSignatureV2.prototype.signatureMethod = awsSignatureV2.signatureMethod; AmazonSignatureV2.prototype.strToSign = awsSignatureV2.strToSign; AmazonSignatureV2.prototype.signature = awsSignatureV2.signature; AmazonSignatureV2.prototype.addSignature = awsSignatureV2.addSignature; AmazonSignatureV2.prototype.addCommonOptions = awsSignatureV2.addCommonOptions; // This service uses (defaults to) the AWS Signature v4. var AmazonSignatureV4 = function(opts) { var self = this; // call the superclass for initialisation AmazonSignatureV4.super_.call(self, opts); return self; }; util.inherits(AmazonSignatureV4, Amazon); AmazonSignatureV4.prototype.signatureVersion = awsSignatureV4.signatureVersion; AmazonSignatureV4.prototype.signatureMethod = awsSignatureV4.signatureMethod; AmazonSignatureV4.prototype.strToSign = awsSignatureV4.strToSign; AmazonSignatureV4.prototype.signature = awsSignatureV4.signature; AmazonSignatureV4.prototype.addSignature = awsSignatureV4.addSignature; AmazonSignatureV4.prototype.addCommonOptions = awsSignatureV4.addCommonOptions; AmazonSignatureV4.prototype.contentType = awsSignatureV4.contentType; // -------------------------------------------------------------------------------------------------------------------- // exports // constants exports.US_EAST_1 = US_EAST_1; exports.US_WEST_1 = US_WEST_1; exports.US_WEST_2 = US_WEST_2; exports.EU_WEST_1 = EU_WEST_1; exports.AP_SOUTHEAST_1 = AP_SOUTHEAST_1; exports.AP_SOUTHEAST_2 = AP_SOUTHEAST_2; exports.AP_NORTHEAST_1 = AP_NORTHEAST_1; exports.US_GOV_WEST_1 = US_GOV_WEST_1; exports.SA_EAST_1 = SA_EAST_1; // object constructor exports.Amazon = Amazon; exports.AmazonSignatureV2 = AmazonSignatureV2; exports.AmazonSignatureV4 = AmazonSignatureV4; // --------------------------------------------------------------------------------------------------------------------
/** * @file mip-hs-showmore 组件 * @author */ define(function (require) { 'use strict'; var $ = require('zepto'); var viewport = require('viewport'); var customElement = require('customElement').create(); /** * 第一次进入可视区回调,只会执行一次 */ customElement.prototype.firstInviewCallback = function () { var wW = viewport.getWidth(); if ($(this.element).find('.text_warp .viewmore_co').height() <= 100) { $(this.element).find('.text_warp .btnmore').addClass('hide'); } else { $(this.element).find('.text_warp .viewmore_co').addClass('limit-height'); } $(this.element).find('.icon-down').parent().addClass('gradient'); $(this.element).find('.icon-down').css('left', (wW - $(this.element).find('.icon-down').width()) / 2); $(this.element).on('click', '.btnmore', function () { if ($(this).find('.icon').hasClass('icon-down') || $(this).find('.text').hasClass('down')) { $(this).find('.icon').removeClass('icon-down').addClass('icon-up'); $(this).find('.icon').html('收起'); $(this).find('.text').removeClass('down').html($(this).find('.text').attr('data-up')); $(this).parent().find('.viewmore_co').addClass('show'); $(this).find('.icon-up').parent().removeClass('gradient'); } else { $(this).find('.icon').html('查看全部内容'); $(this).find('.icon').removeClass('icon-up').addClass('icon-down'); $(this).find('.text').addClass('down').html($(this).find('.text').attr('data-down')); $(this).parent().find('.viewmore_co').removeClass('show'); $(this).find('.icon-down').parent().addClass('gradient'); } }); }; return customElement; });
var LocalStrategy = require('passport-local').Strategy; var mango = require('../database/mango'); var models = require('../database/models'); var User = models.user; var passportUtils = require('./utilities.js'); var gunner = require('../gunner/gunner.js'); module.exports = function(passport){ passport.use('register', new LocalStrategy({ passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, username, password, done) { username = username.toLowerCase(); findOrCreateUser = function(){ // find a user in Mongo with provided username User.findOne({ 'username' : username }, function(err, user) { // In case of any error, return using the done method if (err){ console.log('Error in Register: '+err); return done(err); } // already exists if (user) { console.log('User already exists with username: '+username); return done(null, false, {message:'User Already Exists'}); } else { // if there is no user with that email // create the user var saveCallback = function(newUser, err) { if (err){ console.log('Error in Saving user: '+err); throw err; } console.log('User Registration succesful'); var message = 'Your verification code is: ' + newUser.email_verification_code + ' \n Please Sign in and go to Members > Member Info > Verify Email to verify your email.'; gunner.sendEmail(newUser.username, null, null, 'FBC Waco College -- Email Verification Code', message, null, null); return done(null, newUser); }; mango.addUser(username, passportUtils.createHash(password), req.body.firstname, req.body.lastname, saveCallback); // TODO send email verification message } }); }; // Delay the execution of findOrCreateUser and execute the method // in the next tick of the event loop process.nextTick(findOrCreateUser); }) ); };
import 'babel/polyfill'; import SurvivorSelection from './survivor-selection'; import Recombination from './recombination'; import Mutation from './mutation'; import { MissingRequiredPropertyError, ImproperlyConfiguredError } from '../errors'; import { extend, items } from '../utils'; const properties = { populationSize: { type: 'number' }, maxGenerations: { type: 'number' }, individual: { type: 'function' }, survivorSelection: { required: true, class: SurvivorSelection }, recombination: { required: true, class: Recombination }, mutation: { required: true, class: Mutation } }; export default class GeneticAlgorithm { constructor(options = {}) { this.populationSize = 10; this.survivalRate = 0.2; this.maxGenerations = 1000; extend(this, options); for (let [key, config] of items(properties)) { if (config.required && !this.hasOwnProperty(key)) { throw new MissingRequiredPropertyError(key); } else if (config.class && !(this[key] instanceof config.class) || config.type && typeof this[key] !== config.type) { throw new ImproperlyConfiguredError(key); } } } generatePopulation() { var population = []; for (let i = 0; i < this.populationSize; i++) { population.push(this.individual()); } return population; } }
import React, { Component, PropTypes } from 'react'; import { AddRouteWithData } from '../../components/chapel/chapel.js' export default class NewRoute extends Component { constructor(props, context) { super(props, context); this.addBench = this.addBench.bind(this); this.removeLastBench = this.removeLastBench.bind(this); this.state = { benches: [], } } addBench(e) { const benches = this.state.benches; benches.push(parseInt(e.target.dataset.count, 10)); this.setState({ benches }); } calculateHeight() { return 100 + this.state.benches.reduce((a, b) => (a + (b > 0 ? 30 : 10)), 0); } removeLastBench() { const benches = this.state.benches; benches.pop(); this.setState({ benches }); } render() { return ( <div className="container"> <div className="btn-toolbar mt-3 mr-auto ml-auto" role="toolbar" aria-label="Toolbar with button groups" style={{ width: '300px', }} > <div className="btn-group mr-2" role="group" aria-label="First group"> <button onClick={this.removeLastBench} type="button" className="btn btn-secondary">X</button> </div> <div className="btn-group mr-2" role="group" aria-label="Second group"> <button onClick={this.addBench} type="button" className="btn btn-secondary" data-count="0">0</button> <button onClick={this.addBench} type="button" className="btn btn-secondary" data-count="1">1</button> <button onClick={this.addBench} type="button" className="btn btn-secondary" data-count="2">2</button> <button onClick={this.addBench} type="button" className="btn btn-secondary" data-count="3">3</button> <button onClick={this.addBench} type="button" className="btn btn-secondary" data-count="4">4</button> </div> </div> <AddRouteWithData {...this.props.params} chapelLayout={{ version: 1, benches: this.state.benches, height: this.calculateHeight(), }} deacons={[]} /> </div> ); } } NewRoute.contextTypes = { };
module.exports = require('highcharts-editor.js');
import React, { Component } from 'react'; import Moment from 'moment'; class WeatherAlerts extends Component{ render() { // First, see if we have any alerts if(this.props.alerts.length < 1) { return null; } // If we have multiple, just display the first one: var alert = this.props.alerts[0]; var title = alert.title; var expires = alert.expires; var formattedexpires = Moment(expires * 1000).fromNow(); var description = alert.description || ""; description = description.substring(0, 150) + "..."; // If there is an 'elipsis' at the beginning // of the description, remove it: if(description.substring(0, 3) === "...") { description = description.substring(3); } // If there is an 'elipsis' in the description, // break the description on that if(description.indexOf("...") > 0) { var breakLocation = description.indexOf("..."); description = description.substring(0, breakLocation); } return ( <div className="alert alert-info"> <span className="forecast-alert-title"><b>{title}</b> expires {formattedexpires}</span><br/> <span>{description}</span> </div> ); } } export default WeatherAlerts;
/*! * CanJS - 1.1.7 * http://canjs.us/ * Copyright (c) 2013 Bitovi * Wed, 24 Jul 2013 00:23:28 GMT * Licensed MIT * Includes: CanJS default build * Download from: http://canjs.us/ */ define(["can/util/string"], function(can) { // ## construct.js // `can.Construct` // _This is a modified version of // [John Resig's class](http://ejohn.org/blog/simple-javascript-inheritance/). // It provides class level inheritance and callbacks._ // A private flag used to initialize a new class instance without // initializing it's bindings. var initializing = 0; /** * @add can.Construct */ can.Construct = function() { if (arguments.length) { return can.Construct.extend.apply(can.Construct, arguments); } }; /** * @static */ can.extend(can.Construct, { /** * @property {Boolean} can.Construct.constructorExtends constructorExtends * @parent can.Construct.static * * @description * * Toggles the behavior of a constructor function called * without `new` to extend the constructor function or * create a new instance. * * @body * * If `constructorExtends` is: * * - `true` - the constructor extends * - `false` - a new instance of the constructor is created * * For 1.1, `constructorExtends` defaults to true. For * 1.2, `constructorExtends` will default to false. */ constructorExtends: true, /** * @function can.Construct.newInstance newInstance * @parent can.Construct.static * * @description Returns an instance of `can.Construct`. This method * can be overridden to return a cached instance. * * @signature `can.Construct.newInstance([...args])` * * @param {*} [args] arguments that get passed to [can.Construct::setup] and [can.Construct::init]. Note * that if [can.Construct::setup] returns an array, those arguments will be passed to [can.Construct::init] * instead. * @return {class} instance of the class * * @body * Creates a new instance of the constructor function. This method is useful for creating new instances * with arbitrary parameters. Typically, however, you will simply want to call the constructor with the * __new__ operator. * * ## Example * * The following creates a `Person` Construct and then creates a new instance of Person, * using `apply` on newInstance to pass arbitrary parameters. * * @codestart * var Person = can.Construct({ * init : function(first, middle, last) { * this.first = first; * this.middle = middle; * this.last = last; * } * }); * * var args = ["Justin","Barry","Meyer"], * justin = new Person.newInstance.apply(null, args); * @codeend */ newInstance: function() { // Get a raw instance object (`init` is not called). var inst = this.instance(), arg = arguments, args; // Call `setup` if there is a `setup` if ( inst.setup ) { args = inst.setup.apply(inst, arguments); } // Call `init` if there is an `init` // If `setup` returned `args`, use those as the arguments if ( inst.init ) { inst.init.apply(inst, args || arguments); } return inst; }, // Overwrites an object with methods. Used in the `super` plugin. // `newProps` - New properties to add. // `oldProps` - Where the old properties might be (used with `super`). // `addTo` - What we are adding to. _inherit: function( newProps, oldProps, addTo ) { can.extend(addTo || newProps, newProps || {}) }, // used for overwriting a single property. // this should be used for patching other objects // the super plugin overwrites this _overwrite : function(what, oldProps, propName, val){ what[propName] = val; }, // Set `defaults` as the merger of the parent `defaults` and this // object's `defaults`. If you overwrite this method, make sure to // include option merging logic. /** * @function can.Construct.setup setup * @parent can.Construct.static * * @description Perform initialization logic for a constructor function. * * @signature `can.Construct.setup(base, fullName, staticProps, protoProps)` * * A static `setup` method provides inheritable setup functionality * for a Constructor function. The following example * creates a Group constructor function. Any constructor * functions that inherit from Group will be added to * `Group.childGroups`. * * * Group = can.Construct.extend({ * setup: function(Construct, fullName, staticProps, protoProps){ * this.childGroups = []; * if(Construct !== can.Construct){ * this.childGroups(Construct) * } * Construct.setup.apply(this, arguments) * } * },{}) * var Flock = Group.extend(...) * Group.childGroups[0] //-> Flock * * @param {constructor} base The base constructor that is being inherited from. * @param {String} fullName The name of the new constructor. * @param {Object} staticProps The static properties of the new constructor. * @param {Object} protoProps The prototype properties of the new constructor. * * @body * The static `setup` method is called immediately after a constructor * function is created and * set to inherit from its base constructor. It is useful for setting up * additional inheritance work. * Do not confuse this with the prototype `[can.Construct::setup]` method. * * ## Setup Extends Defaults * * Setup deeply extends the static `defaults` property of the base constructor with * properties of the inheriting constructor. For example: * * @codestart * Parent = can.Construct({ * defaults : { * parentProp: 'foo' * } * },{}) * * Child = Parent({ * defaults : { * childProp : 'bar' * } * },{} * * Child.defaults // {parentProp: 'foo', 'childProp': 'bar'} * @codeend * * ## Example * * This `Parent` class adds a reference to its base class to itself, and * so do all the classes that inherit from it. * * @codestart * Parent = can.Construct({ * setup : function(base, fullName, staticProps, protoProps){ * this.base = base; * * // call base functionality * can.Construct.setup.apply(this, arguments) * } * },{}); * * Parent.base; // can.Construct * * Child = Parent({}); * * Child.base; // Parent * @codeend */ setup: function( base, fullName ) { this.defaults = can.extend(true,{}, base.defaults, this.defaults); }, // Create's a new `class` instance without initializing by setting the // `initializing` flag. instance: function() { // Prevents running `init`. initializing = 1; var inst = new this(); // Allow running `init`. initializing = 0; return inst; }, // Extends classes. /** * @function can.Construct.extend extend * @parent can.Construct.static * * @signature `can.Construct.extend([name,] [staticProperties,] instanceProperties)` * * Extends `can.Construct`, or constructor functions derived from `can.Construct`, * to create a new constructor function. Example: * * Animal = can.Construct.extend({ * sayHi: function(){ * console.log("hi") * } * }) * var animal = new Animal() * animal.sayHi(); * * @param {String} [name] Creates the necessary properties and * objects that point from the `window` to the created constructor function. The following: * * can.Construct.extend("company.project.Constructor",{}) * * creates a `company` object on window if it does not find one, a * `project` object on `company` if it does not find one, and it will set the * `Constructor` property on the `project` object to point to the constructor function. * * Finally, it sets "company.project.Constructor" as [can.Construct.fullName fullName] * and "Constructor" as [can.Construct.shortName shortName]. * * @param {Object} [staticProperties] Properties that are added the constructor * function directly. For example: * * Animal = can.Construct.extend({ * findAll: function(){ * return can.ajax({url: "/animals"}) * } * },{}); * * Animal.findAll().then(function(json){ ... }) * * The [can.Construct.setup static setup] method can be used to * specify inheritable behavior when a Constructor function is created. * * @param {Object} instanceProperties Properties that belong to * instances made with the constructor. These properties are added to the * constructor's `prototype` object. Example: * * Animal = can.Construct.extend({ * init: function(name){ * this.name = name; * }, * sayHi: function(){ * console.log(this.name,"says hi") * } * }) * var animal = new Animal() * animal.sayHi(); * * The [can.Construct::init init] and [can.Construct::setup setup] properties * are used for initialization. * * @return {function} The constructor function. * */ extend: function( fullName, klass, proto ) { // Figure out what was passed and normalize it. if ( typeof fullName != 'string' ) { proto = klass; klass = fullName; fullName = null; } if ( ! proto ) { proto = klass; klass = null; } proto = proto || {}; var _super_class = this, _super = this.prototype, name, shortName, namespace, prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor). prototype = this.instance(); // Copy the properties over onto the new prototype. can.Construct._inherit(proto, _super, prototype); // The dummy class constructor. function Constructor() { // All construction is actually done in the init method. if ( ! initializing ) { return this.constructor !== Constructor && arguments.length && Constructor.constructorExtends? // We are being called without `new` or we are extending. arguments.callee.extend.apply(arguments.callee, arguments) : // We are being called with `new`. Constructor.newInstance.apply(Constructor, arguments); } } // Copy old stuff onto class (can probably be merged w/ inherit) for ( name in _super_class ) { if ( _super_class.hasOwnProperty(name) ) { Constructor[name] = _super_class[name]; } } // Copy new static properties on class. can.Construct._inherit(klass, _super_class, Constructor); // Setup namespaces. if ( fullName ) { var parts = fullName.split('.'), shortName = parts.pop(), current = can.getObject(parts.join('.'), window, true), namespace = current, _fullName = can.underscore(fullName.replace(/\./g, "_")), _shortName = can.underscore(shortName); current[shortName] = Constructor; } // Set things that shouldn't be overwritten. can.extend(Constructor, { constructor: Constructor, prototype: prototype, /** * @property {String} can.Construct.namespace namespace * @parent can.Construct.static * * The `namespace` property returns the namespace your constructor is in. * This provides a way organize code and ensure globally unique types. The * `namespace` is the [can.Construct.fullName fullName] you passed without the [can.Construct.shortName shortName]. * * @codestart * can.Construct("MyApplication.MyConstructor",{},{}); * MyApplication.MyConstructor.namespace // "MyApplication" * MyApplication.MyConstructor.shortName // "MyConstructor" * MyApplication.MyConstructor.fullName // "MyApplication.MyConstructor" * @codeend */ namespace: namespace, /** * @property {String} can.Construct.shortName shortName * @parent can.Construct.static * * If you pass a name when creating a Construct, the `shortName` property will be set to the * name you passed without the [can.Construct.namespace namespace]. * * @codestart * can.Construct("MyApplication.MyConstructor",{},{}); * MyApplication.MyConstructor.namespace // "MyApplication" * MyApplication.MyConstructor.shortName // "MyConstructor" * MyApplication.MyConstructor.fullName // "MyApplication.MyConstructor" * @codeend */ _shortName : _shortName, /** * @property {String} can.Construct.fullName fullName * @parent can.Construct.static * * If you pass a name when creating a Construct, the `fullName` property will be set to * the name you passed. The `fullName` consists of the [can.Construct.namespace namespace] and * the [can.Construct.shortName shortName]. * * @codestart * can.Construct("MyApplication.MyConstructor",{},{}); * MyApplication.MyConstructor.namespace // "MyApplication" * MyApplication.MyConstructor.shortName // "MyConstructor" * MyApplication.MyConstructor.fullName // "MyApplication.MyConstructor" * @codeend */ fullName: fullName, _fullName: _fullName }); // Dojo and YUI extend undefined if(shortName !== undefined) { Constructor.shortName = shortName; } // Make sure our prototype looks nice. Constructor.prototype.constructor = Constructor; // Call the class `setup` and `init` var t = [_super_class].concat(can.makeArray(arguments)), args = Constructor.setup.apply(Constructor, t ); if ( Constructor.init ) { Constructor.init.apply(Constructor, args || t ); } /** * @prototype */ return Constructor; // /** * @property {Function} can.Construct.prototype.constructor constructor * @parent can.Construct.prototype * * A reference to the constructor function that created the instance. This allows you to access * the constructor's static properties from an instance. * * ## Example * * This class has a static counter that counts how mane instances have been created: * * @codestart * can.Construct("Counter", { * count: 0 * }, { * init: function() { * this.constructor.count++; * } * }); * * new Counter(); * Counter.count; // 1 * @codeend */ } }); /** * @function can.Construct.prototype.setup setup * @parent can.Construct.prototype * * @signature `construct.setup(...args)` * * A setup function for the instantiation of a constructor function. * * @param {*} args The arguments passed to the constructor. * * @return {Array|undefined} If an array is returned, the array's items are passed as * arguments to [can.Construct::init init]. The following example always makes * sure that init is called with a jQuery wrapped element: * * WidgetFactory = can.Construct.extend({ * setup: function(element){ * return [$(element)] * } * }) * * MyWidget = WidgetFactory.extend({ * init: function($el){ * $el.html("My Widget!!") * } * }) * * Otherwise, the arguments to the * constructor are passed to [can.Construct::init] and the return value of `setup` is discarded. * * @body * * ## Deciding between `setup` and `init` * * * Usually, you should use [can.Construct::init init] to do your constructor function's initialization. * Use `setup` instead for: * * - initialization code that you want to run before the inheriting constructor's * `init` method is called. * - initialization code that should run whether or not inheriting constructors * call their base's `init` methods. * - modifying the arguments that will get passed to `init`. * * ## Example * * This code is a simplified version of the code in [can.Control]'s setup * method. It converts the first argument to a jQuery collection and * extends the controller's defaults with the options that were passed. * * * can.Control = can.Construct.extend({ * setup: function(domElement, rawOptions) { * // set up this.element * this.element = $(domElement); * * // set up this.options * this.options = can.extend({}, * this.constructor.defaults, * rawOptions * ); * * // pass this.element and this.options to init. * return [this.element, this.options]; * } * }); * */ can.Construct.prototype.setup = function(){}; /** * @function can.Construct.prototype.init init * @parent can.Construct.prototype * * @description Called when a new instance of a can.Construct is created. * * @signature `construct.init(...args)` * @param {*} args the arguments passed to the constructor (or the elements of the array returned from [can.Construct::setup]) * * @body * If a prototype `init` method is provided, it is called when a new Construct is created, * after [can.Construct::setup]. The `init` method is where the bulk of your initialization code * should go, and a common thing to do in `init` is to save the arguments passed into the constructor. * * ## Examples * * First, we'll make a Person constructor that has a first and last name: * * @codestart * can.Construct("Person", { * init: function(first, last) { * this.first = first; * this.last = last; * } * }); * * var justin = new Person("Justin", "Meyer"); * justin.first; // "Justin" * justin.last; // "Meyer" * @codeend * * Then we'll extend Person into Programmer and add a favorite language: * * @codestart * Person("Programmer", { * init: function(first, last, language) { * // call base's init * Person.prototype.init.apply(this, arguments); * * // other initialization code * this.language = language; * }, * bio: function() { * return 'Hi! I'm ' + this.first + ' ' + this.last + * ' and I write ' + this.language + '.'; * } * }); * * var brian = new Programmer("Brian", "Moschel", 'ECMAScript'); * brian.bio(); // "Hi! I'm Brian Moschel and I write ECMAScript."; * @codeend * * ## Be Aware * * [can.Construct::setup] is able to modify the arguments passed to `init`. * If you aren't receiving the right arguments to `init`, check to make sure * that they aren't being changed by `setup` somewhere along the inheritance chain. */ can.Construct.prototype.init = function(){}; return can.Construct; });
let postcss = require('postcss'), util = require('postcss-plugin-utilities'); module.exports = postcss.plugin('postcss-styler-var', () => { let applyVars = o => { ['params', 'selector', 'prop', 'value'].forEach(prop => { if (o.hasOwnProperty(prop)) { o[prop] = o[prop].replace(/(^v\(|[\s\(\,\)]v\()/ig, (s) => { return s.replace('v(', 'var('); }); o[prop] = o[prop].replace(/(^c\(|[\s\(\,\)]c\()/ig, (s) => { return s.replace('c(', 'var(color-'); }); o[prop] = o[prop].replace(/var\(([^\,\)]+)(\,((([^\(\)]+)?\(([^\(\)]+)?\)([^\(\)]+)?)|[^\)]+))?\)/ig, (s, v, d = null) => { if (d) { d = d.slice(2); } if (d === 'null' || d === 'false') { d = null; } if (util.sassHasVar(v, o)) { return `$${v}`; } else if (d) { return d; } else { if (o.type !== 'atrule') { removeEmpty(o); } return null; } }); } }); }; let removeEmpty = o => { let parent = o.parent; o.remove(); if (parent && parent.nodes.lenght == 0) { removeEmpty(parent); } } return css => { css.walkAtRules(atrule => { applyVars(atrule); }); css.walkRules(rule => { applyVars(rule); }); css.walkDecls(decl => { applyVars(decl); }); } });
export * from './state-provider' export * from './statefull' export * from './state-gameobject'
// Regular expression that matches all symbols with the `Variation_Selector` property as per Unicode v5.1.0: /[\u180B-\u180D\uFE00-\uFE0F]|\uDB40[\uDD00-\uDDEF]/;
/** * @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v25.1.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=iSideBar.js.map
var reserve = require("./reserve")(8000) var IP = require("./IP") module.exports = function( grunt, taskName, options, runOptions ){ var tinylr = require("./livereload")(grunt) var middleWareStack = options.middleware || [] options.middleware = function ( connect, options, middlewares ){ middleWareStack.forEach(function( src ){ try{ require(src)(grunt, connect, options, middlewares) } catch( e ){ console.warn("Unable to load middlware '%s'", src) console.warn(e) } }) return middlewares } grunt.config("connect.boomer.options", options) grunt.registerTask(taskName||"default", "Serve files with Boomer!", function (){ var done = this.async() reserve(2, function ( lrPort, serverPort ){ var serverRoot = grunt.config.get("connect.boomer.options.base") , webAddress = "http://" + IP + ":" + serverPort grunt.config("connect.boomer.options.port", serverPort) grunt.config("connect.boomer.options.open", webAddress) grunt.config("connect.boomer.options.livereload", lrPort) grunt.event.once("connect.boomer.listening", function (){ console.log("Boomer is serving %s on %s", serverRoot, webAddress) // and let watch keep it alive grunt.task.run("watch") runOptions.onStarted({ host: IP, port: serverPort, liveReload: lrPort }) }) // create lr server tinylr.listen(lrPort, function ( err ){ console.log('Live reload server started on port %d', lrPort) done() // open server grunt.task.run("connect:boomer") }) }) }) }
const NCAPModel = require('~/models/ncap'); const navigateWithData = require('~/utils/navigateWithData'); const ctx = NCAPModel.getEmptyPlaceholder(); const loadYearData = () => { ctx.set('isLoading', true); return NCAPModel.get('').then(r => { ctx.set('items', r); ctx.set('isLoading', false); }, err => { ctx.set('isLoading', false); ctx.set('items', [{Model: err.message}]); throw err; }); }; exports.onNavigatingTo = args => { const page = args.object; if (args.isBackNavigation) { return; } page.bindingContext = ctx; loadYearData(); }; exports.gotoMakes = args => { const year = ctx.items[args.index].ModelYear; return navigateWithData(ctx, '/modelyear/' + year, 'views/make/make'); };
module.exports.toJSON = (s) => { try { return JSON.stringify(s); } catch(err) { return null; } }; module.exports.fromJSON = (json) => { try { return JSON.parse(json); } catch(err) { return null; } }; module.exports.randomString = (length) => { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (let i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; };
// @flow import defaultPersister from '../../../_configuration/urb-base-server/graphql/defaultPersister' defaultPersister.addTableSchema('Translaticiarum', { fields: { id: 'uuid', Translaticiarum_User_id: 'uuid', Translaticiarum_Stop: 'timestamp', Translaticiarum_Start: 'timestamp', Translaticiarum_Description: 'text', }, key: [ 'id' ], custom_indexes: [ { on: 'Translaticiarum_User_id', using: 'org.apache.cassandra.index.sasi.SASIIndex', options: {}, }, ], }) export default true
import React from 'react' import { storiesOf } from '@storybook/react' import { withInfo } from '@storybook/addon-info' import Navigation from './Navigation' storiesOf('Navigation', module) .addDecorator(withInfo({ header: false, inline: true, excludedPropTypes: ['children'] })) .add('default', () => ( <Navigation title='DonderStarter' /> )) .add('with children on right', () => ( <Navigation title='DonderStarter'> <button>LOGIN</button> </Navigation> ))
{ var _this; return false || _this; }
angular .module('confRegistrationWebApp') .directive('questionToolbar', function ($document, $timeout) { return { restrict: 'A', link: function ($scope) { //Debouncing plugin for jQuery from http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/ (function (jQuery, sr) { // debouncing function from John Hann // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/ var debounce = function (func, threshold, execAsap) { var timeout; return function debounced() { var obj = this, args = arguments; function delayed() { if (!execAsap) { func.apply(obj, args); } timeout = null; } if (timeout) { clearTimeout(timeout); } else if (execAsap) { func.apply(obj, args); } timeout = $timeout(delayed, threshold || 500); }; }; // smartresize jQuery.fn[sr] = function (fn) { return fn ? this.on('resize', debounce(fn)) : this.trigger(sr); }; })(angular.element, 'smartresize'); //keep placeholder the same size when the toolbar is affixed function setQuestionToolbarSize() { var placeholder = angular.element('.questions-toolbar-placeholder'); if (placeholder.length) { angular .element('.questions-toolbar') .data('bs.affix').options.offset.top = placeholder.offset().top; placeholder.css('min-height', function () { return angular.element('.questions-toolbar').outerHeight(true); }); } } $scope.questionsToolbarVisible = true; $scope.toggleQuestionsToolbar = function () { $scope.questionsToolbarVisible = !$scope.questionsToolbarVisible; $timeout(setQuestionToolbarSize, 0); }; angular.element(function () { angular.element('.questions-toolbar').affix({ offset: { top: function () { return (this.top = angular .element('.questions-toolbar-placeholder') .offset().top); }, }, }); $timeout(setQuestionToolbarSize, 0); angular.element(window).smartresize(function () { setQuestionToolbarSize(); }); }); $scope.questions = [ { id: 'paragraphContent', defaultTitle: 'Information', iconClass: 'fa-info-circle', name: 'Information', }, { id: 'textQuestion', defaultTitle: 'Question', iconClass: 'fa-pencil-square-o', name: 'Text', }, { id: 'textareaQuestion', defaultTitle: 'Question', iconClass: 'fa-text-height', name: 'Multi Line Text', }, { id: 'radioQuestion', defaultTitle: 'Multiple Choice Question', iconClass: 'fa-list', name: 'Multiple Choice', tooltip: 'Choose one', }, { id: 'checkboxQuestion', defaultTitle: 'Checkbox Question', iconClass: 'fa-check-square-o', name: 'Checkbox', tooltip: 'Choose one or more', }, { id: 'selectQuestion', defaultTitle: 'Dropdown Question', iconClass: 'fa-chevron-down', name: 'Dropdown', }, { id: 'numberQuestion', defaultTitle: 'Number', iconClass: 'fa-superscript', name: 'Number', }, { id: 'dateQuestion', defaultTitle: 'Date', iconClass: 'fa-calendar', name: 'Date', }, { id: 'nameQuestion', defaultTitle: 'Name', iconClass: 'fa-user', name: 'Name', }, { id: 'emailQuestion', defaultTitle: 'Email', iconClass: 'fa-envelope-o', name: 'Email', }, { id: 'phoneQuestion', defaultTitle: 'Telephone', defaultProfile: 'PHONE', iconClass: 'fa-phone-square', name: 'Telephone', }, { id: 'addressQuestion', defaultTitle: 'Address', defaultProfile: 'ADDRESS', iconClass: 'fa-home', name: 'Address', }, { id: 'genderQuestion', defaultTitle: 'Gender', defaultProfile: 'GENDER', iconClass: 'fa-male', name: 'Gender', }, { id: 'yearInSchoolQuestion', defaultTitle: 'Year in School', defaultProfile: 'YEAR_IN_SCHOOL', iconClass: 'fa-graduation-cap', name: 'Year in School', }, { id: 'birthDateQuestion', defaultTitle: 'Date of Birth', defaultProfile: 'BIRTH_DATE', iconClass: 'fa-calendar', name: 'Date of Birth', }, { id: 'campusQuestion', defaultTitle: 'Campus', defaultProfile: 'CAMPUS', iconClass: 'fa-graduation-cap', name: 'Campus', }, { id: 'dormitoryQuestion', defaultTitle: 'Dormitory', defaultProfile: 'DORMITORY', iconClass: 'fa-graduation-cap', name: 'Dormitory', }, ]; }, }; });
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : global.Ransac = factory(); })(this, function () { 'use strict'; var Ransac = (function () { function Ransac(problem) { _classCallCheck(this, Ransac); this.problem = problem; } // Get a randome sample from problem of sampleSize _createClass(Ransac, [{ key: 'sample', value: function sample(sampleSize) { var sample = []; var currentSample = 0; while (currentSample < sampleSize) { var randomIndex = Math.floor(Math.random() * this.problem.data.length); // Avoid adding duplicated entries if (sample.indexOf(this.problem.data[randomIndex]) === -1) { sample.push(this.problem.data[randomIndex]); ++currentSample; } } return sample; } // Tell how good a model is, for all points. By default, // it uses sum of squared differences }, { key: 'modelError', value: function modelError(model) { var problem = this.problem; var ssd = problem.data.reduce(function (a, b) { var error = problem.fit(model, b); return a + Math.pow(error, 2); }, 0); return ssd; } // Tell which elements in data are inliers }, { key: 'classifyInliers', value: function classifyInliers(model, sample, options) { var inliers = []; var outliers = []; var problem = this.problem; problem.data.forEach(function (point) { // Exclude inliers if (sample.indexOf(point) === -1) { if (problem.fit(model, point) <= options.threshold) { inliers.push(point); } else { outliers.push(point); } } }); return { inliers: inliers, outliers: outliers }; } // Actually perform RANSAC model fitting }, { key: 'estimate', value: function estimate(options) { // Default options options = options || {}; options.sampleSize = options.sampleSize || 2; options.threshold = options.threshold || 0.1; options.maxIterations = options.maxIterations || 30; options.inliersRatio = options.inliersRatio || 0.7; if (typeof options.improveModelWithConcensusSet === 'undefined') { options.improveModelWithConcensusSet = true; } var iteration = 0; // When iterating, we keep track of the best model so far var bestSolution = { error: Infinity, model: {}, inliers: [], outliers: [], status: 'Failed' }; while (iteration < options.maxIterations) { // Get a Sample. Only indexes are returned var sample = this.sample(options.sampleSize); // Estimate a model from the sample var model = this.problem.model(sample); // Get the inlier set var pointGroups = this.classifyInliers(model, sample, options); var inliers = pointGroups.inliers; var outliers = pointGroups.outliers; var inliersRatio = inliers.length / parseFloat(this.problem.data.length); if (inliersRatio >= options.inliersRatio) { var candidateModel = model; if (options.improveModelWithConcensusSet) { // Found a good model. Now fit all inliers and sampled candidateModel = this.problem.model(inliers.concat(sample)); } var candidateError = this.modelError(candidateModel); if (candidateError < bestSolution.error) { bestSolution = { inliers: inliers, outliers: outliers, model: candidateModel, error: candidateError, status: 'Success' }; } } ++iteration; } return bestSolution; } }]); return Ransac; })(); var ransac = Ransac; return ransac; }); //# sourceMappingURL=ransac.js.map
version https://git-lfs.github.com/spec/v1 oid sha256:4bb8bf8e02fbd345da3ddf1bf8a55ae225446d7fab641db7f2d8f39a834a6c60 size 16675
(function () { angular .module('meanApp') .service('consulta', consulta); consulta.$inject = ['$http', '$window', 'authentication']; function consulta ($http, $window, authentication) { var consulta = function(req) { return $http .post('/api/system', req) .success(function(res) { console.log('service:',res); }) .error(function(e) { console.log(e); }); } var cables = function(req) { return $http .post('/api/cables', req) .success(function(res) { console.log('service:',res); }) .error(function(e) { console.log(e); }); } var saveResults = function(req) { return $http .post('/api/report', req, { headers: { Authorization: 'Bearer '+ authentication.getToken() } }) .success(function(res) { console.log('service:',res); }) .error(function(e) { console.log(e); }); } var getResults = function(user_id) { console.log(user_id) return $http .get('/api/reports/' + user_id, { headers: { Authorization: 'Bearer '+ authentication.getToken() } }) .success(function(res) { console.log('service:',res); }) .error(function(e) { console.log(e); }); } var deleteResults = function(id) { return $http .delete('/api/report/' + id, { headers: { Authorization: 'Bearer '+ authentication.getToken() } }) .success(function(res) { console.log('service:', res); }) .error(function(e) { console.log(e); }); } return { consulta : consulta, cables : cables, saveResults: saveResults, getResults: getResults, deleteResults: deleteResults }; } })();
import React from "react"; export default class Order extends React.Component { render() { return( <li class=""> <div class="icon-feed"> <i class="material-icons">local_shipping</i> </div> <a class="order-items"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod </a> <span class="float-right italic">just now</span> </li> ); } }
import * as tslib_1 from "tslib"; /** * @license Angular v4.2.5 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ import { AUTO_STYLE, NoopAnimationPlayer } from '@angular/animations'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _contains = function (elm1, elm2) { return false; }; var _matches = function (element, selector) { return false; }; var _query = function (element, selector, multi) { return []; }; if (typeof Element != 'undefined') { // this is well supported in all browsers _contains = function (elm1, elm2) { return elm1.contains(elm2); }; if (Element.prototype.matches) { _matches = function (element, selector) { return element.matches(selector); }; } else { var proto = Element.prototype; var fn_1 = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; if (fn_1) { _matches = function (element, selector) { return fn_1.apply(element, [selector]); }; } } _query = function (element, selector, multi) { var results = []; if (multi) { results.push.apply(results, element.querySelectorAll(selector)); } else { var elm = element.querySelector(selector); if (elm) { results.push(elm); } } return results; }; } var matchesElement = _matches; var containsElement = _contains; var invokeQuery = _query; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @experimental Animation support is experimental. */ var MockAnimationDriver = (function () { function MockAnimationDriver() { } MockAnimationDriver.prototype.matchesElement = function (element, selector) { return matchesElement(element, selector); }; MockAnimationDriver.prototype.containsElement = function (elm1, elm2) { return containsElement(elm1, elm2); }; MockAnimationDriver.prototype.query = function (element, selector, multi) { return invokeQuery(element, selector, multi); }; MockAnimationDriver.prototype.computeStyle = function (element, prop, defaultValue) { return defaultValue || ''; }; MockAnimationDriver.prototype.animate = function (element, keyframes, duration, delay, easing, previousPlayers) { if (previousPlayers === void 0) { previousPlayers = []; } var player = new MockAnimationPlayer(element, keyframes, duration, delay, easing, previousPlayers); MockAnimationDriver.log.push(player); return player; }; return MockAnimationDriver; }()); MockAnimationDriver.log = []; /** * @experimental Animation support is experimental. */ var MockAnimationPlayer = (function (_super) { tslib_1.__extends(MockAnimationPlayer, _super); function MockAnimationPlayer(element, keyframes, duration, delay, easing, previousPlayers) { var _this = _super.call(this) || this; _this.element = element; _this.keyframes = keyframes; _this.duration = duration; _this.delay = delay; _this.easing = easing; _this.previousPlayers = previousPlayers; _this.__finished = false; _this.__started = false; _this.previousStyles = {}; _this._onInitFns = []; _this.currentSnapshot = {}; previousPlayers.forEach(function (player) { if (player instanceof MockAnimationPlayer) { var styles_1 = player.currentSnapshot; Object.keys(styles_1).forEach(function (prop) { return _this.previousStyles[prop] = styles_1[prop]; }); } }); _this.totalTime = delay + duration; return _this; } /* @internal */ MockAnimationPlayer.prototype.onInit = function (fn) { this._onInitFns.push(fn); }; /* @internal */ MockAnimationPlayer.prototype.init = function () { _super.prototype.init.call(this); this._onInitFns.forEach(function (fn) { return fn(); }); this._onInitFns = []; }; MockAnimationPlayer.prototype.finish = function () { _super.prototype.finish.call(this); this.__finished = true; }; MockAnimationPlayer.prototype.destroy = function () { _super.prototype.destroy.call(this); this.__finished = true; }; /* @internal */ MockAnimationPlayer.prototype.triggerMicrotask = function () { }; MockAnimationPlayer.prototype.play = function () { _super.prototype.play.call(this); this.__started = true; }; MockAnimationPlayer.prototype.hasStarted = function () { return this.__started; }; MockAnimationPlayer.prototype.beforeDestroy = function () { var _this = this; var captures = {}; Object.keys(this.previousStyles).forEach(function (prop) { captures[prop] = _this.previousStyles[prop]; }); if (this.hasStarted()) { // when assembling the captured styles, it's important that // we build the keyframe styles in the following order: // {other styles within keyframes, ... previousStyles } this.keyframes.forEach(function (kf) { Object.keys(kf).forEach(function (prop) { if (prop != 'offset') { captures[prop] = _this.__finished ? kf[prop] : AUTO_STYLE; } }); }); } this.currentSnapshot = captures; }; return MockAnimationPlayer; }(NoopAnimationPlayer)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the platform-browser/animations/testing package. */ export { MockAnimationDriver, MockAnimationPlayer }; //# sourceMappingURL=testing.es5.js.map
/*! Material Components for the web Copyright (c) 2017 Google Inc. License: Apache-2.0 */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["radio"] = factory(); else root["mdc"] = root["mdc"] || {}, root["mdc"]["radio"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/assets/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 67); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @template A */ var MDCFoundation = function () { _createClass(MDCFoundation, null, [{ key: "cssClasses", /** @return enum{cssClasses} */ get: function get() { // Classes extending MDCFoundation should implement this method to return an object which exports every // CSS class the foundation class needs as a property. e.g. {ACTIVE: 'mdc-component--active'} return {}; } /** @return enum{strings} */ }, { key: "strings", get: function get() { // Classes extending MDCFoundation should implement this method to return an object which exports all // semantic strings as constants. e.g. {ARIA_ROLE: 'tablist'} return {}; } /** @return enum{numbers} */ }, { key: "numbers", get: function get() { // Classes extending MDCFoundation should implement this method to return an object which exports all // of its semantic numbers as constants. e.g. {ANIMATION_DELAY_MS: 350} return {}; } /** @return {!Object} */ }, { key: "defaultAdapter", get: function get() { // Classes extending MDCFoundation may choose to implement this getter in order to provide a convenient // way of viewing the necessary methods of an adapter. In the future, this could also be used for adapter // validation. return {}; } /** * @param {A=} adapter */ }]); function MDCFoundation() { var adapter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, MDCFoundation); /** @protected {!A} */ this.adapter_ = adapter; } _createClass(MDCFoundation, [{ key: "init", value: function init() { // Subclasses should override this method to perform initialization routines (registering events, etc.) } }, { key: "destroy", value: function destroy() { // Subclasses should override this method to perform de-initialization routines (de-registering events, etc.) } }]); return MDCFoundation; }(); /* harmony default export */ __webpack_exports__["a"] = (MDCFoundation); /***/ }), /***/ 1: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation__ = __webpack_require__(0); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @template F */ var MDCComponent = function () { _createClass(MDCComponent, null, [{ key: 'attachTo', /** * @param {!Element} root * @return {!MDCComponent} */ value: function attachTo(root) { // Subclasses which extend MDCBase should provide an attachTo() method that takes a root element and // returns an instantiated component with its root set to that element. Also note that in the cases of // subclasses, an explicit foundation class will not have to be passed in; it will simply be initialized // from getDefaultFoundation(). return new MDCComponent(root, new __WEBPACK_IMPORTED_MODULE_0__foundation__["a" /* default */]()); } /** * @param {!Element} root * @param {F=} foundation * @param {...?} args */ }]); function MDCComponent(root) { var foundation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; _classCallCheck(this, MDCComponent); /** @protected {!Element} */ this.root_ = root; for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } this.initialize.apply(this, args); // Note that we initialize foundation here and not within the constructor's default param so that // this.root_ is defined and can be used within the foundation class. /** @protected {!F} */ this.foundation_ = foundation === undefined ? this.getDefaultFoundation() : foundation; this.foundation_.init(); this.initialSyncWithDOM(); } _createClass(MDCComponent, [{ key: 'initialize', value: function initialize() /* ...args */{} // Subclasses can override this to do any additional setup work that would be considered part of a // "constructor". Essentially, it is a hook into the parent constructor before the foundation is // initialized. Any additional arguments besides root and foundation will be passed in here. /** * @return {!F} foundation */ }, { key: 'getDefaultFoundation', value: function getDefaultFoundation() { // Subclasses must override this method to return a properly configured foundation class for the // component. throw new Error('Subclasses must override getDefaultFoundation to return a properly configured ' + 'foundation class'); } }, { key: 'initialSyncWithDOM', value: function initialSyncWithDOM() { // Subclasses should override this method if they need to perform work to synchronize with a host DOM // object. An example of this would be a form control wrapper that needs to synchronize its internal state // to some property or attribute of the host DOM. Please note: this is *not* the place to perform DOM // reads/writes that would cause layout / paint, as this is called synchronously from within the constructor. } }, { key: 'destroy', value: function destroy() { // Subclasses may implement this method to release any resources / deregister any listeners they have // attached. An example of this might be deregistering a resize event from the window object. this.foundation_.destroy(); } /** * Wrapper method to add an event listener to the component's root element. This is most useful when * listening for custom events. * @param {string} evtType * @param {!Function} handler */ }, { key: 'listen', value: function listen(evtType, handler) { this.root_.addEventListener(evtType, handler); } /** * Wrapper method to remove an event listener to the component's root element. This is most useful when * unlistening for custom events. * @param {string} evtType * @param {!Function} handler */ }, { key: 'unlisten', value: function unlisten(evtType, handler) { this.root_.removeEventListener(evtType, handler); } /** * Fires a cross-browser-compatible custom event from the component root of the given type, * with the given data. * @param {string} evtType * @param {!Object} evtData * @param {boolean=} shouldBubble */ }, { key: 'emit', value: function emit(evtType, evtData) { var shouldBubble = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var evt = void 0; if (typeof CustomEvent === 'function') { evt = new CustomEvent(evtType, { detail: evtData, bubbles: shouldBubble }); } else { evt = document.createEvent('CustomEvent'); evt.initCustomEvent(evtType, shouldBubble, false, evtData); } this.root_.dispatchEvent(evt); } }]); return MDCComponent; }(); /* harmony default export */ __webpack_exports__["a"] = (MDCComponent); /***/ }), /***/ 3: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SelectionControlState; }); /** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @typedef {!{ * checked: boolean, * indeterminate: boolean, * disabled: boolean, * value: ?string * }} */ var SelectionControlState = void 0; /***/ }), /***/ 4: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint no-unused-vars: [2, {"args": "none"}] */ /** * Adapter for MDC Ripple. Provides an interface for managing * - classes * - dom * - CSS variables * - position * - dimensions * - scroll position * - event handlers * - unbounded, active and disabled states * * Additionally, provides type information for the adapter to the Closure * compiler. * * Implement this adapter for your framework of choice to delegate updates to * the component in your framework of choice. See architecture documentation * for more details. * https://github.com/material-components/material-components-web/blob/master/docs/architecture.md * * @record */ var MDCRippleAdapter = function () { function MDCRippleAdapter() { _classCallCheck(this, MDCRippleAdapter); } _createClass(MDCRippleAdapter, [{ key: "browserSupportsCssVars", /** @return {boolean} */ value: function browserSupportsCssVars() {} /** @return {boolean} */ }, { key: "isUnbounded", value: function isUnbounded() {} /** @return {boolean} */ }, { key: "isSurfaceActive", value: function isSurfaceActive() {} /** @return {boolean} */ }, { key: "isSurfaceDisabled", value: function isSurfaceDisabled() {} /** @param {string} className */ }, { key: "addClass", value: function addClass(className) {} /** @param {string} className */ }, { key: "removeClass", value: function removeClass(className) {} /** * @param {string} evtType * @param {!Function} handler */ }, { key: "registerInteractionHandler", value: function registerInteractionHandler(evtType, handler) {} /** * @param {string} evtType * @param {!Function} handler */ }, { key: "deregisterInteractionHandler", value: function deregisterInteractionHandler(evtType, handler) {} /** * @param {!Function} handler */ }, { key: "registerResizeHandler", value: function registerResizeHandler(handler) {} /** * @param {!Function} handler */ }, { key: "deregisterResizeHandler", value: function deregisterResizeHandler(handler) {} /** * @param {string} varName * @param {?number|string} value */ }, { key: "updateCssVariable", value: function updateCssVariable(varName, value) {} /** @return {!ClientRect} */ }, { key: "computeBoundingRect", value: function computeBoundingRect() {} /** @return {{x: number, y: number}} */ }, { key: "getWindowPageOffset", value: function getWindowPageOffset() {} }]); return MDCRippleAdapter; }(); /* unused harmony default export */ var _unused_webpack_default_export = (MDCRippleAdapter); /***/ }), /***/ 5: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (immutable) */ __webpack_exports__["supportsCssVariables"] = supportsCssVariables; /* harmony export (immutable) */ __webpack_exports__["applyPassive"] = applyPassive; /* harmony export (immutable) */ __webpack_exports__["getMatchesProperty"] = getMatchesProperty; /* harmony export (immutable) */ __webpack_exports__["getNormalizedEventCoords"] = getNormalizedEventCoords; /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @private {boolean|undefined} */ var supportsPassive_ = void 0; /** * @param {!Window} windowObj * @return {boolean|undefined} */ function supportsCssVariables(windowObj) { var supportsFunctionPresent = windowObj.CSS && typeof windowObj.CSS.supports === 'function'; if (!supportsFunctionPresent) { return; } var explicitlySupportsCssVars = windowObj.CSS.supports('--css-vars', 'yes'); // See: https://bugs.webkit.org/show_bug.cgi?id=154669 // See: README section on Safari var weAreFeatureDetectingSafari10plus = windowObj.CSS.supports('(--css-vars: yes)') && windowObj.CSS.supports('color', '#00000000'); return explicitlySupportsCssVars || weAreFeatureDetectingSafari10plus; } // /** * Determine whether the current browser supports passive event listeners, and if so, use them. * @param {!Window=} globalObj * @param {boolean=} forceRefresh * @return {boolean|{passive: boolean}} */ function applyPassive() { var globalObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; var forceRefresh = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (supportsPassive_ === undefined || forceRefresh) { var isSupported = false; try { globalObj.document.addEventListener('test', null, { get passive() { isSupported = true; } }); } catch (e) {} supportsPassive_ = isSupported; } return supportsPassive_ ? { passive: true } : false; } /** * @param {!Object} HTMLElementPrototype * @return {!Array<string>} */ function getMatchesProperty(HTMLElementPrototype) { return ['webkitMatchesSelector', 'msMatchesSelector', 'matches'].filter(function (p) { return p in HTMLElementPrototype; }).pop(); } /** * @param {!Event} ev * @param {!{x: number, y: number}} pageOffset * @param {!ClientRect} clientRect * @return {!{x: number, y: number}} */ function getNormalizedEventCoords(ev, pageOffset, clientRect) { var x = pageOffset.x, y = pageOffset.y; var documentX = x + clientRect.left; var documentY = y + clientRect.top; var normalizedX = void 0; var normalizedY = void 0; // Determine touch point relative to the ripple container. if (ev.type === 'touchstart') { normalizedX = ev.changedTouches[0].pageX - documentX; normalizedY = ev.changedTouches[0].pageY - documentY; } else { normalizedX = ev.pageX - documentX; normalizedY = ev.pageY - documentY; } return { x: normalizedX, y: normalizedY }; } /***/ }), /***/ 6: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRipple", function() { return MDCRipple; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_component__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(5); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRippleFoundation", function() { return __WEBPACK_IMPORTED_MODULE_2__foundation__["a"]; }); /* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "util", function() { return __WEBPACK_IMPORTED_MODULE_3__util__; }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @extends MDCComponent<!MDCRippleFoundation> */ var MDCRipple = function (_MDCComponent) { _inherits(MDCRipple, _MDCComponent); /** @param {...?} args */ function MDCRipple() { var _ref; _classCallCheck(this, MDCRipple); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } /** @type {boolean} */ var _this = _possibleConstructorReturn(this, (_ref = MDCRipple.__proto__ || Object.getPrototypeOf(MDCRipple)).call.apply(_ref, [this].concat(args))); _this.disabled = false; /** @private {boolean} */ _this.unbounded_; return _this; } /** * @param {!Element} root * @param {{isUnbounded: (boolean|undefined)}=} options * @return {!MDCRipple} */ _createClass(MDCRipple, [{ key: 'activate', value: function activate() { this.foundation_.activate(); } }, { key: 'deactivate', value: function deactivate() { this.foundation_.deactivate(); } }, { key: 'layout', value: function layout() { this.foundation_.layout(); } /** @return {!MDCRippleFoundation} */ }, { key: 'getDefaultFoundation', value: function getDefaultFoundation() { return new __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */](MDCRipple.createAdapter(this)); } }, { key: 'initialSyncWithDOM', value: function initialSyncWithDOM() { this.unbounded = 'mdcRippleIsUnbounded' in this.root_.dataset; } }, { key: 'unbounded', /** @return {boolean} */ get: function get() { return this.unbounded_; } /** @param {boolean} unbounded */ , set: function set(unbounded) { var UNBOUNDED = __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */].cssClasses.UNBOUNDED; this.unbounded_ = Boolean(unbounded); if (this.unbounded_) { this.root_.classList.add(UNBOUNDED); } else { this.root_.classList.remove(UNBOUNDED); } } }], [{ key: 'attachTo', value: function attachTo(root) { var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref2$isUnbounded = _ref2.isUnbounded, isUnbounded = _ref2$isUnbounded === undefined ? undefined : _ref2$isUnbounded; var ripple = new MDCRipple(root); // Only override unbounded behavior if option is explicitly specified if (isUnbounded !== undefined) { ripple.unbounded = /** @type {boolean} */isUnbounded; } return ripple; } /** * @param {!RippleCapableSurface} instance * @return {!MDCRippleAdapter} */ }, { key: 'createAdapter', value: function createAdapter(instance) { var MATCHES = __WEBPACK_IMPORTED_MODULE_3__util__["getMatchesProperty"](HTMLElement.prototype); return { browserSupportsCssVars: function browserSupportsCssVars() { return __WEBPACK_IMPORTED_MODULE_3__util__["supportsCssVariables"](window); }, isUnbounded: function isUnbounded() { return instance.unbounded; }, isSurfaceActive: function isSurfaceActive() { return instance.root_[MATCHES](':active'); }, isSurfaceDisabled: function isSurfaceDisabled() { return instance.disabled; }, addClass: function addClass(className) { return instance.root_.classList.add(className); }, removeClass: function removeClass(className) { return instance.root_.classList.remove(className); }, registerInteractionHandler: function registerInteractionHandler(evtType, handler) { return instance.root_.addEventListener(evtType, handler, __WEBPACK_IMPORTED_MODULE_3__util__["applyPassive"]()); }, deregisterInteractionHandler: function deregisterInteractionHandler(evtType, handler) { return instance.root_.removeEventListener(evtType, handler, __WEBPACK_IMPORTED_MODULE_3__util__["applyPassive"]()); }, registerResizeHandler: function registerResizeHandler(handler) { return window.addEventListener('resize', handler); }, deregisterResizeHandler: function deregisterResizeHandler(handler) { return window.removeEventListener('resize', handler); }, updateCssVariable: function updateCssVariable(varName, value) { return instance.root_.style.setProperty(varName, value); }, computeBoundingRect: function computeBoundingRect() { return instance.root_.getBoundingClientRect(); }, getWindowPageOffset: function getWindowPageOffset() { return { x: window.pageXOffset, y: window.pageYOffset }; } }; } }]); return MDCRipple; }(__WEBPACK_IMPORTED_MODULE_0__material_base_component__["a" /* default */]); /** * See Material Design spec for more details on when to use ripples. * https://material.io/guidelines/motion/choreography.html#choreography-creation * @record */ var RippleCapableSurface = function RippleCapableSurface() { _classCallCheck(this, RippleCapableSurface); }; /** @protected {!Element} */ RippleCapableSurface.prototype.root_; /** * Whether or not the ripple bleeds out of the bounds of the element. * @type {boolean|undefined} */ RippleCapableSurface.prototype.unbounded; /** * Whether or not the ripple is attached to a disabled component. * @type {boolean|undefined} */ RippleCapableSurface.prototype.disabled; /***/ }), /***/ 67: /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(68); /***/ }), /***/ 68: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRadio", function() { return MDCRadio; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_component__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__material_base_selection_control__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation__ = __webpack_require__(69); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__material_ripple__ = __webpack_require__(6); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRadioFoundation", function() { return __WEBPACK_IMPORTED_MODULE_2__foundation__["a"]; }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-unused-vars */ /* eslint-enable no-unused-vars */ /** * @extends MDCComponent<!MDCRadioFoundation> */ var MDCRadio = function (_MDCComponent) { _inherits(MDCRadio, _MDCComponent); _createClass(MDCRadio, [{ key: 'checked', /** @return {boolean} */ get: function get() { return this.foundation_.isChecked(); } /** @param {boolean} checked */ , set: function set(checked) { this.foundation_.setChecked(checked); } /** @return {boolean} */ }, { key: 'disabled', get: function get() { return this.foundation_.isDisabled(); } /** @param {boolean} disabled */ , set: function set(disabled) { this.foundation_.setDisabled(disabled); } /** @return {?string} */ }, { key: 'value', get: function get() { return this.foundation_.getValue(); } /** @param {?string} value */ , set: function set(value) { this.foundation_.setValue(value); } /** @return {!MDCRipple} */ }, { key: 'ripple', get: function get() { return this.ripple_; } }], [{ key: 'attachTo', value: function attachTo(root) { return new MDCRadio(root); } }]); function MDCRadio() { var _ref; _classCallCheck(this, MDCRadio); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } /** @private {!MDCRipple} */ var _this = _possibleConstructorReturn(this, (_ref = MDCRadio.__proto__ || Object.getPrototypeOf(MDCRadio)).call.apply(_ref, [this].concat(args))); _this.ripple_ = _this.initRipple_(); return _this; } /** * @return {!MDCRipple} * @private */ _createClass(MDCRadio, [{ key: 'initRipple_', value: function initRipple_() { var _this2 = this; var adapter = _extends(__WEBPACK_IMPORTED_MODULE_3__material_ripple__["MDCRipple"].createAdapter(this), { isUnbounded: function isUnbounded() { return true; }, // Radio buttons technically go "active" whenever there is *any* keyboard interaction. This is not the // UI we desire. isSurfaceActive: function isSurfaceActive() { return false; }, registerInteractionHandler: function registerInteractionHandler(type, handler) { return _this2.nativeControl_.addEventListener(type, handler); }, deregisterInteractionHandler: function deregisterInteractionHandler(type, handler) { return _this2.nativeControl_.removeEventListener(type, handler); }, computeBoundingRect: function computeBoundingRect() { var _root_$getBoundingCli = _this2.root_.getBoundingClientRect(), left = _root_$getBoundingCli.left, top = _root_$getBoundingCli.top; var DIM = 40; return { top: top, left: left, right: left + DIM, bottom: top + DIM, width: DIM, height: DIM }; } }); var foundation = new __WEBPACK_IMPORTED_MODULE_3__material_ripple__["MDCRippleFoundation"](adapter); return new __WEBPACK_IMPORTED_MODULE_3__material_ripple__["MDCRipple"](this.root_, foundation); } /** * Returns the state of the native control element, or null if the native control element is not present. * @return {?SelectionControlState} * @private */ }, { key: 'destroy', value: function destroy() { this.ripple_.destroy(); _get(MDCRadio.prototype.__proto__ || Object.getPrototypeOf(MDCRadio.prototype), 'destroy', this).call(this); } /** @return {!MDCRadioFoundation} */ }, { key: 'getDefaultFoundation', value: function getDefaultFoundation() { var _this3 = this; return new __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */]({ addClass: function addClass(className) { return _this3.root_.classList.add(className); }, removeClass: function removeClass(className) { return _this3.root_.classList.remove(className); }, getNativeControl: function getNativeControl() { return _this3.root_.querySelector(__WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */].strings.NATIVE_CONTROL_SELECTOR); } }); } }, { key: 'nativeControl_', get: function get() { var NATIVE_CONTROL_SELECTOR = __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */].strings.NATIVE_CONTROL_SELECTOR; var el = /** @type {?SelectionControlState} */this.root_.querySelector(NATIVE_CONTROL_SELECTOR); return el; } }]); return MDCRadio; }(__WEBPACK_IMPORTED_MODULE_0__material_base_component__["a" /* default */]); /***/ }), /***/ 69: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_foundation__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__material_base_selection_control__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__adapter__ = __webpack_require__(70); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__constants__ = __webpack_require__(71); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-unused-vars */ /* eslint-enable no-unused-vars */ /** * @extends {MDCFoundation<!MDCRadioAdapter>} */ var MDCRadioFoundation = function (_MDCFoundation) { _inherits(MDCRadioFoundation, _MDCFoundation); function MDCRadioFoundation() { _classCallCheck(this, MDCRadioFoundation); return _possibleConstructorReturn(this, (MDCRadioFoundation.__proto__ || Object.getPrototypeOf(MDCRadioFoundation)).apply(this, arguments)); } _createClass(MDCRadioFoundation, [{ key: 'isChecked', /** @return {boolean} */ value: function isChecked() { return this.getNativeControl_().checked; } /** @param {boolean} checked */ }, { key: 'setChecked', value: function setChecked(checked) { this.getNativeControl_().checked = checked; } /** @return {boolean} */ }, { key: 'isDisabled', value: function isDisabled() { return this.getNativeControl_().disabled; } /** @param {boolean} disabled */ }, { key: 'setDisabled', value: function setDisabled(disabled) { var DISABLED = MDCRadioFoundation.cssClasses.DISABLED; this.getNativeControl_().disabled = disabled; if (disabled) { this.adapter_.addClass(DISABLED); } else { this.adapter_.removeClass(DISABLED); } } /** @return {?string} */ }, { key: 'getValue', value: function getValue() { return this.getNativeControl_().value; } /** @param {?string} value */ }, { key: 'setValue', value: function setValue(value) { this.getNativeControl_().value = value; } /** * @return {!SelectionControlState} * @private */ }, { key: 'getNativeControl_', value: function getNativeControl_() { return this.adapter_.getNativeControl() || { checked: false, disabled: false, value: null }; } }], [{ key: 'cssClasses', /** @return enum {cssClasses} */ get: function get() { return __WEBPACK_IMPORTED_MODULE_3__constants__["a" /* cssClasses */]; } /** @return enum {strings} */ }, { key: 'strings', get: function get() { return __WEBPACK_IMPORTED_MODULE_3__constants__["b" /* strings */]; } /** @return {!MDCRadioAdapter} */ }, { key: 'defaultAdapter', get: function get() { return (/** @type {!MDCRadioAdapter} */{ addClass: function addClass() /* className: string */{}, removeClass: function removeClass() /* className: string */{}, getNativeControl: function getNativeControl() /* !SelectionControlState */{} } ); } }]); return MDCRadioFoundation; }(__WEBPACK_IMPORTED_MODULE_0__material_base_foundation__["a" /* default */]); /* harmony default export */ __webpack_exports__["a"] = (MDCRadioFoundation); /***/ }), /***/ 7: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_foundation__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__constants__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(5); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @typedef {!{ * isActivated: (boolean|undefined), * hasDeactivationUXRun: (boolean|undefined), * wasActivatedByPointer: (boolean|undefined), * wasElementMadeActive: (boolean|undefined), * activationStartTime: (number|undefined), * activationEvent: Event, * isProgrammatic: (boolean|undefined) * }} */ var ActivationStateType = void 0; /** * @typedef {!{ * activate: (string|undefined), * deactivate: (string|undefined), * focus: (string|undefined), * blur: (string|undefined) * }} */ var ListenerInfoType = void 0; /** * @typedef {!{ * activate: function(!Event), * deactivate: function(!Event), * focus: function(), * blur: function() * }} */ var ListenersType = void 0; /** * @typedef {!{ * x: number, * y: number * }} */ var PointType = void 0; /** * @enum {string} */ var DEACTIVATION_ACTIVATION_PAIRS = { mouseup: 'mousedown', pointerup: 'pointerdown', touchend: 'touchstart', keyup: 'keydown', blur: 'focus' }; /** * @extends {MDCFoundation<!MDCRippleAdapter>} */ var MDCRippleFoundation = function (_MDCFoundation) { _inherits(MDCRippleFoundation, _MDCFoundation); _createClass(MDCRippleFoundation, [{ key: 'isSupported_', /** * We compute this property so that we are not querying information about the client * until the point in time where the foundation requests it. This prevents scenarios where * client-side feature-detection may happen too early, such as when components are rendered on the server * and then initialized at mount time on the client. * @return {boolean} */ get: function get() { return this.adapter_.browserSupportsCssVars(); } }], [{ key: 'cssClasses', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */]; } }, { key: 'strings', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */]; } }, { key: 'numbers', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */]; } }, { key: 'defaultAdapter', get: function get() { return { browserSupportsCssVars: function browserSupportsCssVars() /* boolean - cached */{}, isUnbounded: function isUnbounded() /* boolean */{}, isSurfaceActive: function isSurfaceActive() /* boolean */{}, isSurfaceDisabled: function isSurfaceDisabled() /* boolean */{}, addClass: function addClass() /* className: string */{}, removeClass: function removeClass() /* className: string */{}, registerInteractionHandler: function registerInteractionHandler() /* evtType: string, handler: EventListener */{}, deregisterInteractionHandler: function deregisterInteractionHandler() /* evtType: string, handler: EventListener */{}, registerResizeHandler: function registerResizeHandler() /* handler: EventListener */{}, deregisterResizeHandler: function deregisterResizeHandler() /* handler: EventListener */{}, updateCssVariable: function updateCssVariable() /* varName: string, value: string */{}, computeBoundingRect: function computeBoundingRect() /* ClientRect */{}, getWindowPageOffset: function getWindowPageOffset() /* {x: number, y: number} */{} }; } }]); function MDCRippleFoundation(adapter) { _classCallCheck(this, MDCRippleFoundation); /** @private {number} */ var _this = _possibleConstructorReturn(this, (MDCRippleFoundation.__proto__ || Object.getPrototypeOf(MDCRippleFoundation)).call(this, _extends(MDCRippleFoundation.defaultAdapter, adapter))); _this.layoutFrame_ = 0; /** @private {!ClientRect} */ _this.frame_ = /** @type {!ClientRect} */{ width: 0, height: 0 }; /** @private {!ActivationStateType} */ _this.activationState_ = _this.defaultActivationState_(); /** @private {number} */ _this.xfDuration_ = 0; /** @private {number} */ _this.initialSize_ = 0; /** @private {number} */ _this.maxRadius_ = 0; /** @private {!Array<{ListenerInfoType}>} */ _this.listenerInfos_ = [{ activate: 'touchstart', deactivate: 'touchend' }, { activate: 'pointerdown', deactivate: 'pointerup' }, { activate: 'mousedown', deactivate: 'mouseup' }, { activate: 'keydown', deactivate: 'keyup' }, { focus: 'focus', blur: 'blur' }]; /** @private {!ListenersType} */ _this.listeners_ = { activate: function activate(e) { return _this.activate_(e); }, deactivate: function deactivate(e) { return _this.deactivate_(e); }, focus: function focus() { return requestAnimationFrame(function () { return _this.adapter_.addClass(MDCRippleFoundation.cssClasses.BG_FOCUSED); }); }, blur: function blur() { return requestAnimationFrame(function () { return _this.adapter_.removeClass(MDCRippleFoundation.cssClasses.BG_FOCUSED); }); } }; /** @private {!Function} */ _this.resizeHandler_ = function () { return _this.layout(); }; /** @private {!{left: number, top:number}} */ _this.unboundedCoords_ = { left: 0, top: 0 }; /** @private {number} */ _this.fgScale_ = 0; /** @private {number} */ _this.activationTimer_ = 0; /** @private {number} */ _this.fgDeactivationRemovalTimer_ = 0; /** @private {boolean} */ _this.activationAnimationHasEnded_ = false; /** @private {!Function} */ _this.activationTimerCallback_ = function () { _this.activationAnimationHasEnded_ = true; _this.runDeactivationUXLogicIfReady_(); }; return _this; } /** * @return {!ActivationStateType} */ _createClass(MDCRippleFoundation, [{ key: 'defaultActivationState_', value: function defaultActivationState_() { return { isActivated: false, hasDeactivationUXRun: false, wasActivatedByPointer: false, wasElementMadeActive: false, activationStartTime: 0, activationEvent: null, isProgrammatic: false }; } }, { key: 'init', value: function init() { var _this2 = this; if (!this.isSupported_) { return; } this.addEventListeners_(); var _MDCRippleFoundation$ = MDCRippleFoundation.cssClasses, ROOT = _MDCRippleFoundation$.ROOT, UNBOUNDED = _MDCRippleFoundation$.UNBOUNDED; requestAnimationFrame(function () { _this2.adapter_.addClass(ROOT); if (_this2.adapter_.isUnbounded()) { _this2.adapter_.addClass(UNBOUNDED); } _this2.layoutInternal_(); }); } /** @private */ }, { key: 'addEventListeners_', value: function addEventListeners_() { var _this3 = this; this.listenerInfos_.forEach(function (info) { Object.keys(info).forEach(function (k) { _this3.adapter_.registerInteractionHandler(info[k], _this3.listeners_[k]); }); }); this.adapter_.registerResizeHandler(this.resizeHandler_); } /** * @param {Event} e * @private */ }, { key: 'activate_', value: function activate_(e) { var _this4 = this; if (this.adapter_.isSurfaceDisabled()) { return; } var activationState = this.activationState_; if (activationState.isActivated) { return; } activationState.isActivated = true; activationState.isProgrammatic = e === null; activationState.activationEvent = e; activationState.wasActivatedByPointer = activationState.isProgrammatic ? false : e.type === 'mousedown' || e.type === 'touchstart' || e.type === 'pointerdown'; activationState.activationStartTime = Date.now(); requestAnimationFrame(function () { // This needs to be wrapped in an rAF call b/c web browsers // report active states inconsistently when they're called within // event handling code: // - https://bugs.chromium.org/p/chromium/issues/detail?id=635971 // - https://bugzilla.mozilla.org/show_bug.cgi?id=1293741 activationState.wasElementMadeActive = e && e.type === 'keydown' ? _this4.adapter_.isSurfaceActive() : true; if (activationState.wasElementMadeActive) { _this4.animateActivation_(); } else { // Reset activation state immediately if element was not made active. _this4.activationState_ = _this4.defaultActivationState_(); } }); } }, { key: 'activate', value: function activate() { this.activate_(null); } /** @private */ }, { key: 'animateActivation_', value: function animateActivation_() { var _this5 = this; var _MDCRippleFoundation$2 = MDCRippleFoundation.strings, VAR_FG_TRANSLATE_START = _MDCRippleFoundation$2.VAR_FG_TRANSLATE_START, VAR_FG_TRANSLATE_END = _MDCRippleFoundation$2.VAR_FG_TRANSLATE_END; var _MDCRippleFoundation$3 = MDCRippleFoundation.cssClasses, BG_ACTIVE_FILL = _MDCRippleFoundation$3.BG_ACTIVE_FILL, FG_DEACTIVATION = _MDCRippleFoundation$3.FG_DEACTIVATION, FG_ACTIVATION = _MDCRippleFoundation$3.FG_ACTIVATION; var DEACTIVATION_TIMEOUT_MS = MDCRippleFoundation.numbers.DEACTIVATION_TIMEOUT_MS; var translateStart = ''; var translateEnd = ''; if (!this.adapter_.isUnbounded()) { var _getFgTranslationCoor = this.getFgTranslationCoordinates_(), startPoint = _getFgTranslationCoor.startPoint, endPoint = _getFgTranslationCoor.endPoint; translateStart = startPoint.x + 'px, ' + startPoint.y + 'px'; translateEnd = endPoint.x + 'px, ' + endPoint.y + 'px'; } this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_START, translateStart); this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_END, translateEnd); // Cancel any ongoing activation/deactivation animations clearTimeout(this.activationTimer_); clearTimeout(this.fgDeactivationRemovalTimer_); this.rmBoundedActivationClasses_(); this.adapter_.removeClass(FG_DEACTIVATION); // Force layout in order to re-trigger the animation. this.adapter_.computeBoundingRect(); this.adapter_.addClass(BG_ACTIVE_FILL); this.adapter_.addClass(FG_ACTIVATION); this.activationTimer_ = setTimeout(function () { return _this5.activationTimerCallback_(); }, DEACTIVATION_TIMEOUT_MS); } /** * @private * @return {{startPoint: PointType, endPoint: PointType}} */ }, { key: 'getFgTranslationCoordinates_', value: function getFgTranslationCoordinates_() { var activationState = this.activationState_; var activationEvent = activationState.activationEvent, wasActivatedByPointer = activationState.wasActivatedByPointer; var startPoint = void 0; if (wasActivatedByPointer) { startPoint = Object(__WEBPACK_IMPORTED_MODULE_3__util__["getNormalizedEventCoords"])( /** @type {!Event} */activationEvent, this.adapter_.getWindowPageOffset(), this.adapter_.computeBoundingRect()); } else { startPoint = { x: this.frame_.width / 2, y: this.frame_.height / 2 }; } // Center the element around the start point. startPoint = { x: startPoint.x - this.initialSize_ / 2, y: startPoint.y - this.initialSize_ / 2 }; var endPoint = { x: this.frame_.width / 2 - this.initialSize_ / 2, y: this.frame_.height / 2 - this.initialSize_ / 2 }; return { startPoint: startPoint, endPoint: endPoint }; } /** @private */ }, { key: 'runDeactivationUXLogicIfReady_', value: function runDeactivationUXLogicIfReady_() { var _this6 = this; var FG_DEACTIVATION = MDCRippleFoundation.cssClasses.FG_DEACTIVATION; var _activationState_ = this.activationState_, hasDeactivationUXRun = _activationState_.hasDeactivationUXRun, isActivated = _activationState_.isActivated; var activationHasEnded = hasDeactivationUXRun || !isActivated; if (activationHasEnded && this.activationAnimationHasEnded_) { this.rmBoundedActivationClasses_(); this.adapter_.addClass(FG_DEACTIVATION); this.fgDeactivationRemovalTimer_ = setTimeout(function () { _this6.adapter_.removeClass(FG_DEACTIVATION); }, __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */].FG_DEACTIVATION_MS); } } /** @private */ }, { key: 'rmBoundedActivationClasses_', value: function rmBoundedActivationClasses_() { var _MDCRippleFoundation$4 = MDCRippleFoundation.cssClasses, BG_ACTIVE_FILL = _MDCRippleFoundation$4.BG_ACTIVE_FILL, FG_ACTIVATION = _MDCRippleFoundation$4.FG_ACTIVATION; this.adapter_.removeClass(BG_ACTIVE_FILL); this.adapter_.removeClass(FG_ACTIVATION); this.activationAnimationHasEnded_ = false; this.adapter_.computeBoundingRect(); } /** * @param {Event} e * @private */ }, { key: 'deactivate_', value: function deactivate_(e) { var _this7 = this; var activationState = this.activationState_; // This can happen in scenarios such as when you have a keyup event that blurs the element. if (!activationState.isActivated) { return; } // Programmatic deactivation. if (activationState.isProgrammatic) { var evtObject = null; var _state = /** @type {!ActivationStateType} */_extends({}, activationState); requestAnimationFrame(function () { return _this7.animateDeactivation_(evtObject, _state); }); this.activationState_ = this.defaultActivationState_(); return; } var actualActivationType = DEACTIVATION_ACTIVATION_PAIRS[e.type]; var expectedActivationType = activationState.activationEvent.type; // NOTE: Pointer events are tricky - https://patrickhlauke.github.io/touch/tests/results/ // Essentially, what we need to do here is decouple the deactivation UX from the actual // deactivation state itself. This way, touch/pointer events in sequence do not trample one // another. var needsDeactivationUX = actualActivationType === expectedActivationType; var needsActualDeactivation = needsDeactivationUX; if (activationState.wasActivatedByPointer) { needsActualDeactivation = e.type === 'mouseup'; } var state = /** @type {!ActivationStateType} */_extends({}, activationState); requestAnimationFrame(function () { if (needsDeactivationUX) { _this7.activationState_.hasDeactivationUXRun = true; _this7.animateDeactivation_(e, state); } if (needsActualDeactivation) { _this7.activationState_ = _this7.defaultActivationState_(); } }); } }, { key: 'deactivate', value: function deactivate() { this.deactivate_(null); } /** * @param {Event} e * @param {!ActivationStateType} options * @private */ }, { key: 'animateDeactivation_', value: function animateDeactivation_(e, _ref) { var wasActivatedByPointer = _ref.wasActivatedByPointer, wasElementMadeActive = _ref.wasElementMadeActive; var BG_FOCUSED = MDCRippleFoundation.cssClasses.BG_FOCUSED; if (wasActivatedByPointer || wasElementMadeActive) { // Remove class left over by element being focused this.adapter_.removeClass(BG_FOCUSED); this.runDeactivationUXLogicIfReady_(); } } }, { key: 'destroy', value: function destroy() { var _this8 = this; if (!this.isSupported_) { return; } this.removeEventListeners_(); var _MDCRippleFoundation$5 = MDCRippleFoundation.cssClasses, ROOT = _MDCRippleFoundation$5.ROOT, UNBOUNDED = _MDCRippleFoundation$5.UNBOUNDED; requestAnimationFrame(function () { _this8.adapter_.removeClass(ROOT); _this8.adapter_.removeClass(UNBOUNDED); _this8.removeCssVars_(); }); } /** @private */ }, { key: 'removeEventListeners_', value: function removeEventListeners_() { var _this9 = this; this.listenerInfos_.forEach(function (info) { Object.keys(info).forEach(function (k) { _this9.adapter_.deregisterInteractionHandler(info[k], _this9.listeners_[k]); }); }); this.adapter_.deregisterResizeHandler(this.resizeHandler_); } /** @private */ }, { key: 'removeCssVars_', value: function removeCssVars_() { var _this10 = this; var strings = MDCRippleFoundation.strings; Object.keys(strings).forEach(function (k) { if (k.indexOf('VAR_') === 0) { _this10.adapter_.updateCssVariable(strings[k], null); } }); } }, { key: 'layout', value: function layout() { var _this11 = this; if (this.layoutFrame_) { cancelAnimationFrame(this.layoutFrame_); } this.layoutFrame_ = requestAnimationFrame(function () { _this11.layoutInternal_(); _this11.layoutFrame_ = 0; }); } /** @private */ }, { key: 'layoutInternal_', value: function layoutInternal_() { this.frame_ = this.adapter_.computeBoundingRect(); var maxDim = Math.max(this.frame_.height, this.frame_.width); var surfaceDiameter = Math.sqrt(Math.pow(this.frame_.width, 2) + Math.pow(this.frame_.height, 2)); // 60% of the largest dimension of the surface this.initialSize_ = maxDim * MDCRippleFoundation.numbers.INITIAL_ORIGIN_SCALE; // Diameter of the surface + 10px this.maxRadius_ = surfaceDiameter + MDCRippleFoundation.numbers.PADDING; this.fgScale_ = this.maxRadius_ / this.initialSize_; this.xfDuration_ = 1000 * Math.sqrt(this.maxRadius_ / 1024); this.updateLayoutCssVars_(); } /** @private */ }, { key: 'updateLayoutCssVars_', value: function updateLayoutCssVars_() { var _MDCRippleFoundation$6 = MDCRippleFoundation.strings, VAR_SURFACE_WIDTH = _MDCRippleFoundation$6.VAR_SURFACE_WIDTH, VAR_SURFACE_HEIGHT = _MDCRippleFoundation$6.VAR_SURFACE_HEIGHT, VAR_FG_SIZE = _MDCRippleFoundation$6.VAR_FG_SIZE, VAR_LEFT = _MDCRippleFoundation$6.VAR_LEFT, VAR_TOP = _MDCRippleFoundation$6.VAR_TOP, VAR_FG_SCALE = _MDCRippleFoundation$6.VAR_FG_SCALE; this.adapter_.updateCssVariable(VAR_SURFACE_WIDTH, this.frame_.width + 'px'); this.adapter_.updateCssVariable(VAR_SURFACE_HEIGHT, this.frame_.height + 'px'); this.adapter_.updateCssVariable(VAR_FG_SIZE, this.initialSize_ + 'px'); this.adapter_.updateCssVariable(VAR_FG_SCALE, this.fgScale_); if (this.adapter_.isUnbounded()) { this.unboundedCoords_ = { left: Math.round(this.frame_.width / 2 - this.initialSize_ / 2), top: Math.round(this.frame_.height / 2 - this.initialSize_ / 2) }; this.adapter_.updateCssVariable(VAR_LEFT, this.unboundedCoords_.left + 'px'); this.adapter_.updateCssVariable(VAR_TOP, this.unboundedCoords_.top + 'px'); } } }]); return MDCRippleFoundation; }(__WEBPACK_IMPORTED_MODULE_0__material_base_foundation__["a" /* default */]); /* harmony default export */ __webpack_exports__["a"] = (MDCRippleFoundation); /***/ }), /***/ 70: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_selection_control__ = __webpack_require__(3); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-unused-vars */ /* eslint no-unused-vars: [2, {"args": "none"}] */ /** * Adapter for MDC Radio. Provides an interface for managing * - classes * - dom * * Additionally, provides type information for the adapter to the Closure * compiler. * * Implement this adapter for your framework of choice to delegate updates to * the component in your framework of choice. See architecture documentation * for more details. * https://github.com/material-components/material-components-web/blob/master/docs/architecture.md * * @record */ var MDCRadioAdapter = function () { function MDCRadioAdapter() { _classCallCheck(this, MDCRadioAdapter); } _createClass(MDCRadioAdapter, [{ key: 'addClass', /** @param {string} className */ value: function addClass(className) {} /** @param {string} className */ }, { key: 'removeClass', value: function removeClass(className) {} /** @return {!SelectionControlState} */ }, { key: 'getNativeControl', value: function getNativeControl() {} }]); return MDCRadioAdapter; }(); /* unused harmony default export */ var _unused_webpack_default_export = (MDCRadioAdapter); /***/ }), /***/ 71: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return strings; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cssClasses; }); /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @enum {string} */ var strings = { NATIVE_CONTROL_SELECTOR: '.mdc-radio__native-control' }; /** @enum {string} */ var cssClasses = { ROOT: 'mdc-radio', DISABLED: 'mdc-radio--disabled' }; /***/ }), /***/ 8: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cssClasses; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return strings; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return numbers; }); /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var cssClasses = { // Ripple is a special case where the "root" component is really a "mixin" of sorts, // given that it's an 'upgrade' to an existing component. That being said it is the root // CSS class that all other CSS classes derive from. ROOT: 'mdc-ripple-upgraded', UNBOUNDED: 'mdc-ripple-upgraded--unbounded', BG_FOCUSED: 'mdc-ripple-upgraded--background-focused', BG_ACTIVE_FILL: 'mdc-ripple-upgraded--background-active-fill', FG_ACTIVATION: 'mdc-ripple-upgraded--foreground-activation', FG_DEACTIVATION: 'mdc-ripple-upgraded--foreground-deactivation' }; var strings = { VAR_SURFACE_WIDTH: '--mdc-ripple-surface-width', VAR_SURFACE_HEIGHT: '--mdc-ripple-surface-height', VAR_FG_SIZE: '--mdc-ripple-fg-size', VAR_LEFT: '--mdc-ripple-left', VAR_TOP: '--mdc-ripple-top', VAR_FG_SCALE: '--mdc-ripple-fg-scale', VAR_FG_TRANSLATE_START: '--mdc-ripple-fg-translate-start', VAR_FG_TRANSLATE_END: '--mdc-ripple-fg-translate-end' }; var numbers = { PADDING: 10, INITIAL_ORIGIN_SCALE: 0.6, DEACTIVATION_TIMEOUT_MS: 300, FG_DEACTIVATION_MS: 83 }; /***/ }) /******/ }); });
export const SET_AUTH_ERROR = 'SET_AUTH_ERROR'; export const CLEAR_AUTH_ERROR = 'CLEAR_AUTH_ERROR'; export const SET_CREATE_ACC_NAV_POS = 'SET_CREATE_ACC_NAV_POS'; export const RESET_CREATE_ACC_NAV_POS = 'RESET_CREATE_ACC_NAV_POS'; export const SET_SECRET_STRENGTH = 'SET_SECRET_STRENGTH'; export const SET_PASSWORD_STRENGTH = 'SET_PASSWORD_STRENGTH'; export const SET_ACC_SECRET = 'SET_ACC_SECRET'; export const CLEAR_ACC_SECRET = 'CLEAR_ACC_SECRET'; export const SET_ACC_PASSWORD = 'SET_ACC_PASSWORD'; export const CLEAR_ACC_PASSWORD = 'CLEAR_ACC_PASSWORD'; export const SET_INVITE_CODE = 'SET_INVITE_CODE'; export const CLEAR_INVITE_CODE = 'CLEAR_INVITE_CODE'; export const SET_AUTH_LOADER = 'SET_AUTH_LOADER'; export const CLEAR_AUTH_LOADER = 'CLEAR_AUTH_LOADER'; export const CREATE_ACC = 'CREATE_ACC'; export const TOGGLE_INVITE_POPUP = 'TOGGLE_INVITE_POPUP'; export const LOGIN = 'LOGIN'; export const LOGOUT = 'LOGOUT'; export const SHOW_LIB_ERR_POPUP = 'SHOW_LIB_ERR_POPUP'; export const setCreateAccNavPos = (pos) => ( { type: SET_CREATE_ACC_NAV_POS, position: pos } ); export const resetCreateAccNavPos = () => ( { type: RESET_CREATE_ACC_NAV_POS } ); export const setSecretStrength = (val) => ( { type: SET_SECRET_STRENGTH, strength: val } ); export const setPasswordStrength = (val) => ( { type: SET_PASSWORD_STRENGTH, strength: val } ); export const setError = (err) => ({ type: SET_AUTH_ERROR, error: err }); export const clearError = () => ({ type: CLEAR_AUTH_ERROR }); export const setAccSecret = (secret) => ({ type: SET_ACC_SECRET, secret }); export const clearAccSecret = () => ({ type: CLEAR_ACC_SECRET }); export const setAccPassword = (password) => ({ type: SET_ACC_PASSWORD, password }); export const clearAccPassword = () => ({ type: CLEAR_ACC_PASSWORD }); export const setInviteCode = (invite) => ({ type: SET_INVITE_CODE, invite }); export const clearInviteCode = () => ({ type: CLEAR_INVITE_CODE }); export const setAuthLoader = () => ({ type: SET_AUTH_LOADER }); export const toggleInvitePopup = () => ({ type: TOGGLE_INVITE_POPUP }); export const clearAuthLoader = () => ({ type: CLEAR_AUTH_LOADER }); export const createAccount = (secret, password, invitation) => ({ type: CREATE_ACC, payload: window.safeAuthenticator.createAccount(secret, password, invitation) }); export const login = (secret, password) => ({ type: LOGIN, payload: window.safeAuthenticator.login(secret, password) }); export const logout = () => ({ type: LOGOUT, payload: Promise.resolve(window.safeAuthenticator.logout()) }); export const showLibErrPopup = () => ({ type: SHOW_LIB_ERR_POPUP });
var connect = require('connect'); var http = require('http'); var WebSocket = require('ws'); var WebSocketServer = WebSocket.Server; var wss = new WebSocketServer({port: 9000}); var Entities = require('./shared/Entities'); var lastTime = new Date().getTime(); var GAMETIME = 1000 * 60 * 5; //minutes var runningTime = 0; var delta = 0; var board; // global entities variable, holds onto all game objects global.entities = new Entities(); // serve static files (index.html, minified client js) var app = connect() .use(connect.static('public')) .use(connect.directory('public')); http.createServer(app).listen(3000); // short-hand function to send data as json to a connected client WebSocket.prototype.sendJSON = function(data) { this.send(JSON.stringify(data)); }; // send json to all connected clients WebSocketServer.prototype.broadcast = function(data) { for (var id in this.clients) { this.clients[id].sendJSON(data); } }; // websocket server events wss.on('connection', function(ws) { ws.on('close', function() { if (ws.player) { ws.player.ondisconnect(); global.entities.remove(ws.player.id); } }); ws.on('error', function(error) { console.log(error); }); ws.on('message', function(message) { message = message.trim().toLowerCase(); if (! message) return; // player exists, let player process message/command && return if (ws.player) return ws.player.onmessage(message, board); // TODO: sessions // player is reconnecting if (message.match(/^hi, i am back \w+-\w+-\w+-\w+-\w+$/)) { var id = message.match(/^hi, i am back (\w+-\w+-\w+-\w+-\w+)$/)[1]; var player = global.entities.find(id); if (player && ! player.isConnected) { ws.player = player; ws.sendJSON({hi: {id: ws.player.id}}); ws.sendJSON({entities: global.entities._out()}); ws.sendJSON({timeLeft: GAMETIME - runningTime}); return ws.player.onconnect(); } } // create a new player if (message.match(/^hi, i am \w+.*$/)) { var name = message.match(/^hi, i am (.*)$/)[1].substring(0, 26); var playerId = global.entities.create('Player', { position: board.spawnPosition(), isAlive: true, isConnected: true, name: name }); ws.player = global.entities.find(playerId); ws.sendJSON({hi: {id: ws.player.id}}); ws.sendJSON({entities: global.entities._out()}); ws.sendJSON({timeLeft: GAMETIME - runningTime}); return ws.player.onconnect(); } }); }); function newGame() { // delete all non-player entities entities.each(function(entity) { if (entity.constructor !== 'Player') entity.object = undefined; }); // create a new game board var boardId = global.entities.create('Board', {h: 60, w: 60}); board = global.entities.find(boardId); // reset all players (bring them back to life) entities.each(function(entity) { if (entity.constructor === 'Player') entity.object.reset(board); }); wss.broadcast({timeLeft: GAMETIME - runningTime}); } function update() { // update delta (time since last update) var now = new Date().getTime(); delta = now - lastTime; lastTime = now; // update all game entities global.entities.update(now, delta, board); // send updates/deletes to all players if there are any var message = {entities: global.entities._out({diff: true})}; if (message.entities.remove.length || Object.keys(message.entities.update).length) { wss.broadcast(message); } runningTime += delta; // crude way to restarting game after amount of time has passed if (runningTime >= GAMETIME) { runningTime = 0; newGame(); return setTimeout(update, 10); } return setTimeout(update, 10); } // the game newGame(); update();
#!/usr/bin/env node /* Copyright 2013 Igor Shevchenko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*eslint no-console:0 */ var optimist = require('optimist') .options('a', { alias: 'autosemicolon', 'default': false }) .boolean('autosemicolon') .describe('a', 'insert a semicolon after the last ruleset') .boolean('a') .alias('c', 'config') .describe('c', 'json config file to use') .alias('f', 'file') .describe('f', 'file to beautify or glob pattern') .alias('h', 'help') .describe('h', 'show this help message') .options('i', { alias: 'indent', 'default': ' ' }) .describe('i', 'string used for the indentation of the declaration (spaces, tabs or number of spaces)') .options('o', { alias: 'openbrace', 'default': 'end-of-line' }) .describe('o', 'the placement of open curly brace, either end-of-line or separate-line') .string('o') .alias('s', 'stdin') .describe('s', 'use stdin as input') .alias('v', 'version') .describe('v', 'Display program version') .alias('w', 'writefile') .describe('w', 'write output to file') .usage('Usage:\n\t$0 [options] -f filename\n\t$0 [options] -s'), package = require('../package'), isUndefined = function (value) { return typeof value === 'undefined'; }; /** * @constructor * may be invoked without new operator */ function CssbeautifyCli() { if (! (this instanceof CssbeautifyCli)) { return new CssbeautifyCli(); } } CssbeautifyCli.optionNames = ['autosemicolon', 'indent', 'openbrace']; CssbeautifyCli.ERRORS = { autosemicolon: function () { console.log('Error: invalid autosemicolon value, use boolean'); }, configFile: function (e) { console.log('Error: could not read config file: ', e); }, file: function () { console.log('Error: no input file.\n'); optimist.showHelp(); }, indent: function () { console.log('Error: invalid indent value, only spaces,tabs or number of spaces are allowed'); }, openbrace: function () { console.log('Error: invalid openbrace value, use either "end-of-line" or "separate-line"'); }, kindaerror: function () { console.log('Error: kinda unknown error occured'); } }; /** * Processes process.argv with optimist and saves result to this.argv * @return {CssbeautifyCli} instance for chaining */ CssbeautifyCli.prototype.parse = function () { this.argv = optimist.parse(process.argv); return this; }; /** * Checks parameter validity * @param {string} name * @param {string} value * @return {Boolean} */ function isValid(name, value) { var tests = { indent: function (value) { return (/^(\s*|\d*)$/).test(value); }, openbrace: function (value) { return (['end-of-line', 'separate-line']).indexOf(value) !== -1; }, autosemicolon: function (value) { return typeof value === 'boolean'; } }; return Boolean(tests[name] && tests[name](value)); } CssbeautifyCli.prototype.PROCESSORS = { indent: function (value) { var indent = parseInt(value, 10); var length = indent; if (indent === indent|0) { for (length = indent, indent = ''; indent.length < length; indent += ' '); this.options.indent = indent; } else { this.options.indent = value; } } }; CssbeautifyCli.prototype.processOption = function (name) { if (! isValid(name, this.argv[name])) { this.setExit((CssbeautifyCli.ERRORS[name] ? CssbeautifyCli.ERRORS[name] : CssbeautifyCli.ERRORS.kindaerror), 1); } else if (isUndefined(this.options[name])) { if (this.PROCESSORS[name]) { this.PROCESSORS[name].call(this, this.argv[name]); } else { this.options[name] = this.argv[name]; } } return this; }; CssbeautifyCli.prototype.processConfig = function () { var self = this; if (! isUndefined(this.argv.config)) { try { var config = require(process.cwd() + '/' + this.argv.config); CssbeautifyCli.optionNames.forEach(function (name) { if (! isUndefined(config[name])) { self.options = self.options || {}; if (isValid(name, config[name])) { self.PROCESSORS[name] ? self.PROCESSORS[name].call(self, config[name]) : (self.options[name] = config[name]); } } }); } catch (e) { this.setExit(function(e) {CssbeautifyCli.ERRORS.configFile(e);}, 1); } } return this; }; /** * Processes parameters provided (using command line/config) * @return {CssbeautifyCli} instance for chaining */ CssbeautifyCli.prototype.process = function () { var self = this; if (this.argv.h) { this.setExit(function () { optimist.showHelp(); }); } else if (this.argv.v) { this.setExit(function () { console.log(package.name + ' version ' + package.version); }); } else if (! this.argv.f && ! this.argv.s) { this.setExit(CssbeautifyCli.ERRORS.file, 1); } else { this.options = {}; this.writefile = this.argv.w; if (this.argv.f) { this.filename = this.argv.f; this.stdin = false; } else { this.stdin = true; } CssbeautifyCli.optionNames.forEach(function (name) { self.processOption(name); }); this.processConfig(); if (this.exit && this.exit.code !== 0) { this.options = null; } } return this; }; /** * Creates exit object for future use in callback function * @param {function} exitFunction * @param {number} exitCode * @return {CssbeautifyCli} instance for chaining */ CssbeautifyCli.prototype.setExit = function (exitFunction, exitCode) { this.exit = { fn: (exitFunction && typeof exitFunction === 'function') ? exitFunction : function () {}, code: exitCode|0 }; return this; }; /** * Sets callback parameter if exit function is available * @return {CssbeautifyCli} instance for chaining */ CssbeautifyCli.prototype.callback = function () { if (this.exit && this.exit.fn) { this.exit.fn(); process.exit(this.exit.code); } return this; }; module.exports = CssbeautifyCli;
define(["helpers/views/factory_classes", "helpers/views/contexted", "helpers/views/updateable_model", "helpers/views/updateable_collection", "helpers/views/unwrappable", "helpers/views/subviews_initializable", "helpers/views/attachable", "helpers/views/selectable", "helpers/views/stickerable", "helpers/views/validatable", "helpers/views/notifiable", "helpers/views/self_updateable"], function(Klasses, Contexted, UpdateableModel, UpdateableCollection, Unwrappable, SubViewsInitializable, Attachable, Selectable, Stickerable, Validatable, Notifiable, SelfUpdateable) { var factory; factory = function(name) { var Klass, Original, properties, reset; Klass = ""; Original = Klasses[name]; reset = function() { Klass = _(Original).clone(); }; reset(); properties = { klass: function(update) { if (update) { Klass = update; } return Klass; }, contexted: function() { Klass = Klass.extend(Contexted); return this; }, selectable: function() { Klass = Klass.extend(Selectable); return this; }, attachable: function() { Klass = Klass.extend(Attachable); return this; }, editable: function() { Klass = Klass.extend(Editable); return this; }, self_updateable: function() { Klass = Klass.extend(SelfUpdateable); return this; }, updateable_collection: function() { Klass = Klass.extend(UpdateableCollection); return this; }, updateable: function() { return this.updateable_model(); }, stickerable: function() { Klass = Klass.extend(Stickerable); return this; }, notifiable: function() { Klass = Klass.extend(Notifiable); return this; }, validatable: function() { Klass = Klass.extend(Validatable); return this; }, updateable_model: function() { Klass = Klass.extend(UpdateableModel); return this; }, subViewsInitializable: function() { Klass = Klass.extend(SubViewsInitializable); return this; }, unwrappable: function() { Klass = Klass.extend(Unwrappable); return this; } }; properties[name] = function() { var OUT; OUT = _(Klass).clone(); reset(); return OUT; }; return properties; }; return factory; });
// jquery.animcloud.js - (c) tuomas.salo@iki.fi (function($) { var fill = function($target, wordlist) { if(!wordlist) { wordlist = []; } $target.html(''); var styles = [ {color: '#F7F6F4', fontSize: 0}, {color: '#aaa', fontSize: 12}, {color: '#888', fontSize: 18}, {color: '#666', fontSize: 22}, {color: '#333', fontSize: 26}, {color: '#000', fontSize: 30} ]; var $div = $('<div/>'); $div.addClass('animcloud'); $.each(wordlist, function(i, e) { var $a = $('<a/>'); $a.attr('href', '/sanat/' + e[0]); $a.text(e[0]); $a.css(styles[e[1]]); //addClass('word'+e[1]); $a.addClass('word-' + e[0]); $div.append($a); $div.append(document.createTextNode(' \u00a0')); }); $target.append($div); }; var morph = function($from, $to) { // 1st pass: record positions $from.find('a').each(function() { var $old = $(this); $old.data('pos', $old.position()); }); $from.find('a').each(function() { var $old = $(this); $old[0].className.match(/(word-\S+)/); var css = $old.data('pos'); css.position = 'absolute'; $old.css(css); var animateTo; var $new = $to.find('.' + RegExp.$1); if($new[0]) { animateTo = $new.position(); animateTo.fontSize = $new.css('fontSize'); animateTo.color = $new.css('color'); $new.addClass('ok'); //console.log(animateTo); } else { animateTo = { color: '#F7F6F4', fontSize: 0}; } //setTimeout(function() { $old.animate(animateTo, 500); //}, 500); }); // handle words that were not present in $from $to.find('a').not('.ok').each(function() { var $new = $(this); var pos = $new.position(); var gotoPos = jQuery.extend({}, pos); var css = pos; css.fontSize = 0; css.color = '#F7F6F4'; css.position = 'absolute'; css.left += $new.width() / 2; css.top += $new.height() / 2; var $item = $('<a/>'); $item.text($new.text()); $item.attr('href', '/sanat/' + $new.text()); $item.addClass('word-' + $new.text()); $item.css(css); $from.find('div').append($item); //setTimeout(function() { $item.animate({ color: $new.css('color'), fontSize: $new.css('fontSize'), left: gotoPos.left, top: gotoPos.top }, 500); //}, 500); }); } $.fn.animcloud = function(wordlist) { var $target = $(this); var $backBuffer = $target.data('bb'); if(!$backBuffer) { $backBuffer = $('<div class="animcloud-backbuffer"/>'); $target.data('bb', $backBuffer); } if($target.find('a')[0]) { // old words exists => animate var $bB = $('#backBuffer'); fill($bB, wordlist); morph($target, $bB); } else { // first run, no animation fill($target, wordlist); } }; })(jQuery);
import React from 'react'; function Choice(props) { return ( <div className="choice"> <input type={props.type} value={props.text} name={props.type}/> <label>{props.text}</label> </div> ); }; export default Choice;
// // A Grid to snap transformations. // In other words, a Grid defines a discrete set of transformations // and provides methods to find the nearest transformation in the set // for any given transformation. // var EPSILON = require('./epsilon') var Vector = require('./Vector') var Path = require('./Path') var extend = require('extend') var DEFAULT_STEPMODE = { xStep: 0, yStep: 0, scaleStep: 0, rotateStep: 0, xPhase: 0, yPhase: 0, scalePhase: 0, rotatePhase: 0, xRotation: 0, // The angle of the xy grid yRotation: Math.PI / 2 } var hasProp = function (obj, prop) { return obj && Object.prototype.hasOwnProperty.call(obj, prop) } var snap = function (x, step, phase) { // Find x' in { i * step + phase | i in N } // such that abs(x - x') is minimal. N is the set of integers. // // Parameters: // x // number // step // number // phase // number // // Return // number // return Math.round((x - phase) / step) * step + phase } var Grid = function (stepMode) { if (typeof stepMode !== 'object') { stepMode = DEFAULT_STEPMODE } else { stepMode = extend({}, DEFAULT_STEPMODE, stepMode) } if ( (stepMode.xStep < EPSILON && stepMode.yStep > EPSILON) || (stepMode.xStep > EPSILON && stepMode.yStep < EPSILON) ) { throw new Error( 'Grid xStep and yStep must be either both zero or ' + 'both greater than zero.' ) // because otherwise handling with grid basis vectors becomes // unnecessarily complicated. } if (Math.abs(stepMode.xRotation - stepMode.yRotation) < EPSILON) { throw new Error('Grid xRotation and yRotation cannot be the same.') // because otherwise grid basis vectors become linearly dependent // and could not be used as basis vectors without unnecessarily // complicated checking for special cases. } this.mode = stepMode } var proto = Grid.prototype proto.almostEqual = function (grid) { // Return bool. True if modes of the grids are equal // with a tiny margin left for floating point arithmetic rounding errors. var k var tm = this.mode var gm = grid.mode for (k in tm) { if (hasProp(tm, k)) { if (hasProp(gm, k)) { if (Math.abs(tm[k] - gm[k]) > EPSILON) { return false } } else { return false } } } return true } proto.at = function (i, j) { // Get a Vector to the crossing (i, j) on the grid. // The vector grid.at(0,0) equals the grid.getOrigin() // // Return // Vector // var m = this.mode if (m.xStep === 0 || m.yStep === 0) { // No grid return new Vector(0, 0) } // Grid basis vectors var gbx = Vector.createFromPolar(m.xStep, m.xRotation) var gby = Vector.createFromPolar(m.yStep, m.yRotation) // Get origin defined by phase var phx = gbx.multiply(m.xPhase / m.xStep) var phy = gby.multiply(m.yPhase / m.yStep) var origin = phx.add(phy) // Add grid coordinate vectors to the origin to get the result. return origin.add(gbx.multiply(i)).add(gby.multiply(j)) } proto.equal = proto.equals = function (grid) { // Return bool. True if modes of the grids equal. // var k var tm = this.mode var gm = grid.mode for (k in tm) { if (hasProp(tm, k)) { if (hasProp(gm, k)) { if (tm[k] !== gm[k]) { return false } } else { return false } } } return true } proto.getHullOf = function (i, j) { // Get hull Path of (i, j):th eye of the grid. // To define the (0, 0):th eye, consider the example: // Let G be grid with xStep=1, yStep=1, xPhase=0.5, yPhase=0. // Now the hull of (0, 0) is a four-point Path: // [(0.5, 0), (0.5, 1), (1.5, 1), (1.5, 0)] // Thus, the eye at x,y origin may not be (0, 0). // // Parameters: // i // number // j // number // // Return: // Path // null // if xStep=0 or yStep=0 // // Grid basis vectors var m = this.mode var gbx = Vector.createFromPolar(m.xStep, m.xRotation) var gby = Vector.createFromPolar(m.yStep, m.yRotation) // Vector to grid origin var vor = this.getOrigin() // Corners var c0 = vor.add(gbx.multiply(i)).add(gby.multiply(j)) var c1 = vor.add(gbx.multiply(i)).add(gby.multiply(j + 1)) var c2 = vor.add(gbx.multiply(i + 1)).add(gby.multiply(j + 1)) var c3 = vor.add(gbx.multiply(i + 1)).add(gby.multiply(j)) // Call getHull to ensure correct order. return new Path([c0, c1, c2, c3]).getHull() } proto.getOrigin = function () { // Get the origin point of the grid, specified by xPhase and yPhase. // // Return: // Vector // // Grid basis vectors var m = this.mode var gbx = Vector.createFromPolar(m.xStep, m.xRotation) var gby = Vector.createFromPolar(m.yStep, m.yRotation) // Normalize phase and turn to components var phx = gbx.multiply(m.xPhase / m.xStep) var phy = gby.multiply(m.yPhase / m.yStep) // Together they point to the origin return phx.add(phy) } proto.snap = function (pivot, tr) { // Snap a Transform to the grid. // In other words, find the nearest Transform allowed // by the grid. // // Parameters // pivot // Vector, represented on the source plane of tr. // tr // Transform, a mapping from a node plane to its parent // // Return // Transform snapped to the grid. // var dx, dy var gbx, gby var tr1, tr2 var piv1, piv1g, piv2g, piv2 var oldScale, newScale, scalingMultiplier var oldRotation, newRotation var m = this.mode // short alias // The pivot is represented on source plane but the grid // is on the target. Thus convert the pivot onto target. piv1 = pivot.transform(tr) if (m.xStep === 0 || m.yStep === 0) { // No x y snapping piv2 = piv1 } else { // The pivot point must hit the grid. Therefore, for starters, // let us translate so that pivot is on the grid. // The grid is defined by basis vectors gvx, gvy. // Magnitude of gvx is xStep and direction xRotation // Magnitude of gvy is yStep and direction yRotation // Therefore for snapping, we change the basis of the pivot. gbx = Vector.createFromPolar(m.xStep, m.xRotation) // grid basis vectors gby = Vector.createFromPolar(m.yStep, m.yRotation) piv1g = piv1.changeBasis(gbx, gby) piv2g = new Vector( snap(piv1g.x, 1, m.xPhase / m.xStep), // snap step 1 because on grid snap(piv1g.y, 1, m.yPhase / m.yStep) ) // Change basis back to original coordinate space piv2 = piv2g.changeFromBasis(gbx, gby) } // How much did the pivot move? dx = piv2.x - piv1.x dy = piv2.y - piv1.y tr1 = tr.translateBy(dx, dy) // Now the pivot is on the grid. // Let us then snap the scaling. // Any change to the scale must be done around the pivot. oldScale = tr1.getScale() if (m.scaleStep === 0) { newScale = oldScale // needed below } else { newScale = snap(oldScale, m.scaleStep, m.scalePhase) } scalingMultiplier = newScale / oldScale tr2 = tr1.scaleBy(scalingMultiplier, piv2.toArray()) // After scaling, pivot stays the same. // Let us rotate around the pivot. oldRotation = tr2.getRotation() if (m.rotateStep === 0) { newRotation = oldRotation } else { // s = newScale * cos oldRotation // r = newScale * sin oldRotation // scale remains the same, only rotation changes newRotation = snap(oldRotation, m.rotateStep, m.rotatePhase) } // We can use the same pivot because scaling is done so that // it stays still. return tr2.rotateBy(newRotation - oldRotation, piv2.toArray()) } proto.toArray = function () { return [this.mode] } proto.transform = function (tr) { // Convert to another Grid var tm = this.mode var result = {} // transformed mode var scale = tr.getScale() var rotation = tr.getRotation() // Rotation step is not affected at all. // Rotation phase is affected by rotation. result.rotateStep = tm.rotateStep result.rotatePhase = tm.rotatePhase + rotation // Scale step is probably (TODO) not affected at all. // Scale phase however is affected by scaling. // For example, let 1, 2, 3, 4 be allowed scalings on source. // If target has x2 magnification, thus 2, 4, 6, and 8 are allowed. // Another example, let 1.5, 2.5, and 3.5 be allowed scalings on source. // Thus scaleStep = 1 and scalePhase = 0.5 // If target has x2 magnification, then 3, 5, and 7 are allowed. // Thus scaleStep = 2 and scalePhase = 1 on the target. result.scaleStep = tm.scaleStep * scale result.scalePhase = tm.scalePhase * scale if (tm.xStep === 0 || tm.yStep === 0) { // No xy snapping result.xStep = tm.xStep result.yStep = tm.yStep result.xRotation = tm.xRotation result.yRotation = tm.yRotation result.xPhase = tm.xPhase result.yPhase = tm.yPhase } else { // Update grid basis vectors. // Zero basis vectors do no trouble because they remain zero. // xStep and yStep are altered by scale and rotation but not by translation. // Represent step and rotation as Vector for easier transformation. var gbx = Vector.createFromPolar(tm.xStep, tm.xRotation) var gby = Vector.createFromPolar(tm.yStep, tm.yRotation) // Transform the basis, but without translation var trSR = tr.translateBy(-tr.tx, -tr.ty) // a bit dirty? var xt = gbx.transform(trSR) var yt = gby.transform(trSR) result.xStep = xt.getMagnitude() result.yStep = yt.getMagnitude() result.xRotation = xt.getRotation() result.yRotation = yt.getRotation() // Transformation affects the phase. // The xPhase/xStep and yPhase/yStep are coordinates on the grid var normXPhase = tm.xPhase / tm.xStep var normYPhase = tm.yPhase / tm.yStep var normPhaseOnSourceGrid = new Vector(normXPhase, normYPhase) var normPhaseOnSource = normPhaseOnSourceGrid.changeFromBasis(gbx, gby) // Phase is about to change. Convert phase to the target plane. var normPhaseOnTarget = normPhaseOnSource.transform(tr) // And from the target plane to the new grid on the target plane. var normPhaseOnTargetGrid = normPhaseOnTarget.changeBasis(xt, yt) // Then undo the normalization. var xPhaseOnTargetGrid = normPhaseOnTargetGrid.x * xt.getMagnitude() var yPhaseOnTargetGrid = normPhaseOnTargetGrid.y * yt.getMagnitude() // And store the result result.xPhase = xPhaseOnTargetGrid result.yPhase = yPhaseOnTargetGrid } return new Grid(result) } module.exports = Grid
/* =================================================== * bootstrap-transition.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#transitions * =================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ console.log('!!!') !function ($) { "use strict"; // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $(function () { $.support.transition = (function () { var transitionEnd = (function () { var el = document.createElement('bootstrap') , transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } , name for (name in transEndEventNames){ if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery);/* ========================================================== * bootstrap-alert.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#alerts * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* ALERT CLASS DEFINITION * ====================== */ var dismiss = '[data-dismiss="alert"]' , Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) , selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) e && e.preventDefault() $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) $parent.trigger(e = $.Event('close')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent .trigger('closed') .remove() } $.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement() } /* ALERT PLUGIN DEFINITION * ======================= */ var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('alert') if (!data) $this.data('alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert /* ALERT NO CONFLICT * ================= */ $.fn.alert.noConflict = function () { $.fn.alert = old return this } /* ALERT DATA-API * ============== */ $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery);/* ============================================================ * bootstrap-button.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#buttons * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* BUTTON PUBLIC CLASS DEFINITION * ============================== */ var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.button.defaults, options) } Button.prototype.setState = function (state) { var d = 'disabled' , $el = this.$element , data = $el.data() , val = $el.is('input') ? 'val' : 'html' state = state + 'Text' data.resetText || $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d) }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons-radio"]') $parent && $parent .find('.active') .removeClass('active') this.$element.toggleClass('active') } /* BUTTON PLUGIN DEFINITION * ======================== */ var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('button') , options = typeof option == 'object' && option if (!data) $this.data('button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.defaults = { loadingText: 'loading...' } $.fn.button.Constructor = Button /* BUTTON NO CONFLICT * ================== */ $.fn.button.noConflict = function () { $.fn.button = old return this } /* BUTTON DATA-API * =============== */ $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') }) }(window.jQuery);/* ========================================================== * bootstrap-carousel.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#carousel * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* CAROUSEL CLASS DEFINITION * ========================= */ var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.prototype = { cycle: function (e) { if (!e) this.paused = false if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } , getActiveIndex: function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } , to: function (pos) { var activeIndex = this.getActiveIndex() , that = this if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) } if (activeIndex == pos) { return this.pause().cycle() } return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } clearInterval(this.interval) this.interval = null return this } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('.item.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true isCycling && this.pause() $next = $next.length ? $next : this.$element.find('.item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] , direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } } /* CAROUSEL PLUGIN DEFINITION * ========================== */ var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('carousel') , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.defaults = { interval: 5000 , pause: 'hover' } $.fn.carousel.Constructor = Carousel /* CAROUSEL NO CONFLICT * ==================== */ $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } /* CAROUSEL DATA-API * ================= */ $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , slideIndex $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('carousel').pause().to(slideIndex).cycle() } e.preventDefault() }) }(window.jQuery);/* ============================================================= * bootstrap-collapse.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') $.support.transition && this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSE PLUGIN DEFINITION * ========================== */ var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSE NO CONFLICT * ==================== */ $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } /* COLLAPSE DATA-API * ================= */ $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') $(target).collapse(option) }) }(window.jQuery);/* ============================================================ * bootstrap-dropdown.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle=dropdown]' , Dropdown = function (element) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function (e) { var $this = $(this) , $parent , isActive if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') clearMenus() if (!isActive) { $parent.toggleClass('open') } $this.focus() return false } , keydown: function (e) { var $this , $items , $active , $parent , isActive , index if (!/(38|40|27)/.test(e.keyCode)) return $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items .eq(index) .focus() } } function clearMenus() { $(toggle).each(function () { getParent($(this)).removeClass('open') }) } function getParent($this) { var selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = selector && $(selector) if (!$parent || !$parent.length) $parent = $this.parent() return $parent } /* DROPDOWN PLUGIN DEFINITION * ========================== */ var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* DROPDOWN NO CONFLICT * ==================== */ $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(document) .on('click.dropdown.data-api', clearMenus) .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.dropdown-menu', function (e) { e.stopPropagation() }) .on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); /* ========================================================= * bootstrap-modal.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ !function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden') }) } , removeBackdrop: function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /* =========================================================== * bootstrap-tooltip.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#tooltips * Inspired by the original jQuery.tipsy by Jason Frame * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* TOOLTIP PUBLIC CLASS DEFINITION * =============================== */ var Tooltip = function (element, options) { this.init('tooltip', element, options) } Tooltip.prototype = { constructor: Tooltip , init: function (type, element, options) { var eventIn , eventOut , triggers , trigger , i this.type = type this.$element = $(element) this.options = this.getOptions(options) this.enabled = true triggers = this.options.trigger.split(' ') for (i = triggers.length; i--;) { trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' eventOut = trigger == 'hover' ? 'mouseleave' : 'blur' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } , getOptions: function (options) { options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } , enter: function (e) { var defaults = $.fn[this.type].defaults , options = {} , self this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }, this) self = $(e.currentTarget)[this.type](options).data(this.type) if (!self.options.delay || !self.options.delay.show) return self.show() clearTimeout(this.timeout) self.hoverState = 'in' this.timeout = setTimeout(function() { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } , leave: function (e) { var self = $(e.currentTarget)[this.type](this._options).data(this.type) if (this.timeout) clearTimeout(this.timeout) if (!self.options.delay || !self.options.delay.hide) return self.hide() self.hoverState = 'out' this.timeout = setTimeout(function() { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } , show: function () { var $tip , pos , actualWidth , actualHeight , placement , tp , e = $.Event('show') if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip = this.tip() this.setContent() if (this.options.animation) { $tip.addClass('fade') } placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement $tip .detach() .css({ top: 0, left: 0, display: 'block' }) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) pos = this.getPosition() actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight switch (placement) { case 'bottom': tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'top': tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'left': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} break case 'right': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} break } this.applyPlacement(tp, placement) this.$element.trigger('shown') } } , applyPlacement: function(offset, placement){ var $tip = this.tip() , width = $tip[0].offsetWidth , height = $tip[0].offsetHeight , actualWidth , actualHeight , delta , replace $tip .offset(offset) .addClass(placement) .addClass('in') actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight replace = true } if (placement == 'bottom' || placement == 'top') { delta = 0 if (offset.left < 0){ delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } , replaceArrow: function(delta, dimension, position){ this .arrow() .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } , setContent: function () { var $tip = this.tip() , title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } , hide: function () { var that = this , $tip = this.tip() , e = $.Event('hide') this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') function removeWithAnimation() { var timeout = setTimeout(function () { $tip.off($.support.transition.end).detach() }, 500) $tip.one($.support.transition.end, function () { clearTimeout(timeout) $tip.detach() }) } $.support.transition && this.$tip.hasClass('fade') ? removeWithAnimation() : $tip.detach() this.$element.trigger('hidden') return this } , fixTitle: function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } , hasContent: function () { return this.getTitle() } , getPosition: function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } , getTitle: function () { var title , $e = this.$element , o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } , tip: function () { return this.$tip = this.$tip || $(this.options.template) } , arrow: function(){ return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") } , validate: function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } , enable: function () { this.enabled = true } , disable: function () { this.enabled = false } , toggleEnabled: function () { this.enabled = !this.enabled } , toggle: function (e) { var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this self.tip().hasClass('in') ? self.hide() : self.show() } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } } /* TOOLTIP PLUGIN DEFINITION * ========================= */ var old = $.fn.tooltip $.fn.tooltip = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tooltip') , options = typeof option == 'object' && option if (!data) $this.data('tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip $.fn.tooltip.defaults = { animation: true , placement: 'top' , selector: false , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' , trigger: 'hover focus' , title: '' , delay: 0 , html: false , container: false } /* TOOLTIP NO CONFLICT * =================== */ $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(window.jQuery); /* =========================================================== * bootstrap-popover.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#popovers * =========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================================================== */ !function ($) { "use strict"; // jshint ;_; /* POPOVER PUBLIC CLASS DEFINITION * =============================== */ var Popover = function (element, options) { this.init('popover', element, options) } /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js ========================================== */ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, { constructor: Popover , setContent: function () { var $tip = this.tip() , title = this.getTitle() , content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content) $tip.removeClass('fade top bottom left right in') } , hasContent: function () { return this.getTitle() || this.getContent() } , getContent: function () { var content , $e = this.$element , o = this.options content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) || $e.attr('data-content') return content } , tip: function () { if (!this.$tip) { this.$tip = $(this.options.template) } return this.$tip } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } }) /* POPOVER PLUGIN DEFINITION * ======================= */ var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('popover') , options = typeof option == 'object' && option if (!data) $this.data('popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, { placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) /* POPOVER NO CONFLICT * =================== */ $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(window.jQuery); /* ============================================================= * bootstrap-scrollspy.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#scrollspy * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================== */ !function ($) { "use strict"; // jshint ;_; /* SCROLLSPY CLASS DEFINITION * ========================== */ function ScrollSpy(element, options) { var process = $.proxy(this.process, this) , $element = $(element).is('body') ? $(window) : $(element) , href this.options = $.extend({}, $.fn.scrollspy.defaults, options) this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.$body = $('body') this.refresh() this.process() } ScrollSpy.prototype = { constructor: ScrollSpy , refresh: function () { var self = this , $targets this.offsets = $([]) this.targets = $([]) $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , $href = /^#\w/.test(href) && $(href) return ( $href && $href.length && [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } , process: function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight , maxScroll = scrollHeight - this.$scrollElement.height() , offsets = this.offsets , targets = this.targets , activeTarget = this.activeTarget , i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate ( i ) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } , activate: function (target) { var active , selector this.activeTarget = target $(this.selector) .parent('.active') .removeClass('active') selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' active = $(selector) .parent('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active.closest('li.dropdown').addClass('active') } active.trigger('activate') } } /* SCROLLSPY PLUGIN DEFINITION * =========================== */ var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('scrollspy') , options = typeof option == 'object' && option if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.defaults = { offset: 10 } /* SCROLLSPY NO CONFLICT * ===================== */ $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } /* SCROLLSPY DATA-API * ================== */ $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(window.jQuery);/* ======================================================== * bootstrap-tab.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#tabs * ======================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================== */ !function ($) { "use strict"; // jshint ;_; /* TAB CLASS DEFINITION * ==================== */ var Tab = function (element) { this.element = $(element) } Tab.prototype = { constructor: Tab , show: function () { var $this = this.element , $ul = $this.closest('ul:not(.dropdown-menu)') , selector = $this.attr('data-target') , previous , $target , e if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ( $this.parent('li').hasClass('active') ) return previous = $ul.find('.active:last a')[0] e = $.Event('show', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown' , relatedTarget: previous }) }) } , activate: function ( element, container, callback) { var $active = container.find('> .active') , transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if ( element.parent('.dropdown-menu') ) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active.one($.support.transition.end, next) : next() $active.removeClass('in') } } /* TAB PLUGIN DEFINITION * ===================== */ // var old = $.fn.tab // $.fn.tab = function ( option ) { // return this.each(function () { // var $this = $(this) // , data = $this.data('tab') // if (!data) $this.data('tab', (data = new Tab(this))) // if (typeof option == 'string') data[option]() // }) // } // $.fn.tab.Constructor = Tab /* TAB NO CONFLICT * =============== */ // $.fn.tab.noConflict = function () { // $.fn.tab = old // return this // } /* TAB DATA-API * ============ */ // $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { // e.preventDefault() // $(this).tab('show') // }) }(window.jQuery); /* ============================================================= * bootstrap-typeahead.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#typeahead * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function($){ "use strict"; // jshint ;_; /* TYPEAHEAD PUBLIC CLASS DEFINITION * ================================= */ var Typeahead = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.typeahead.defaults, options) this.matcher = this.options.matcher || this.matcher this.sorter = this.options.sorter || this.sorter this.highlighter = this.options.highlighter || this.highlighter this.updater = this.options.updater || this.updater this.source = this.options.source this.$menu = $(this.options.menu) this.shown = false this.listen() } Typeahead.prototype = { constructor: Typeahead , select: function () { var val = this.$menu.find('.active').attr('data-value') this.$element .val(this.updater(val)) .change() return this.hide() } , updater: function (item) { return item } , show: function () { var pos = $.extend({}, this.$element.position(), { height: this.$element[0].offsetHeight }) this.$menu .insertAfter(this.$element) .css({ top: pos.top + pos.height , left: pos.left }) .show() this.shown = true return this } , hide: function () { this.$menu.hide() this.shown = false return this } , lookup: function (event) { var items this.query = this.$element.val() if (!this.query || this.query.length < this.options.minLength) { return this.shown ? this.hide() : this } items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source return items ? this.process(items) : this } , process: function (items) { var that = this items = $.grep(items, function (item) { return that.matcher(item) }) items = this.sorter(items) if (!items.length) { return this.shown ? this.hide() : this } return this.render(items.slice(0, this.options.items)).show() } , matcher: function (item) { return ~item.toLowerCase().indexOf(this.query.toLowerCase()) } , sorter: function (items) { var beginswith = [] , caseSensitive = [] , caseInsensitive = [] , item while (item = items.shift()) { if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item) else if (~item.indexOf(this.query)) caseSensitive.push(item) else caseInsensitive.push(item) } return beginswith.concat(caseSensitive, caseInsensitive) } , highlighter: function (item) { var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>' }) } , render: function (items) { var that = this items = $(items).map(function (i, item) { i = $(that.options.item).attr('data-value', item) i.find('a').html(that.highlighter(item)) return i[0] }) items.first().addClass('active') this.$menu.html(items) return this } , next: function (event) { var active = this.$menu.find('.active').removeClass('active') , next = active.next() if (!next.length) { next = $(this.$menu.find('li')[0]) } next.addClass('active') } , prev: function (event) { var active = this.$menu.find('.active').removeClass('active') , prev = active.prev() if (!prev.length) { prev = this.$menu.find('li').last() } prev.addClass('active') } , listen: function () { this.$element .on('focus', $.proxy(this.focus, this)) .on('blur', $.proxy(this.blur, this)) .on('keypress', $.proxy(this.keypress, this)) .on('keyup', $.proxy(this.keyup, this)) if (this.eventSupported('keydown')) { this.$element.on('keydown', $.proxy(this.keydown, this)) } this.$menu .on('click', $.proxy(this.click, this)) .on('mouseenter', 'li', $.proxy(this.mouseenter, this)) .on('mouseleave', 'li', $.proxy(this.mouseleave, this)) } , eventSupported: function(eventName) { var isSupported = eventName in this.$element if (!isSupported) { this.$element.setAttribute(eventName, 'return;') isSupported = typeof this.$element[eventName] === 'function' } return isSupported } , move: function (e) { if (!this.shown) return switch(e.keyCode) { case 9: // tab case 13: // enter case 27: // escape e.preventDefault() break case 38: // up arrow e.preventDefault() this.prev() break case 40: // down arrow e.preventDefault() this.next() break } e.stopPropagation() } , keydown: function (e) { this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27]) this.move(e) } , keypress: function (e) { if (this.suppressKeyPressRepeat) return this.move(e) } , keyup: function (e) { switch(e.keyCode) { case 40: // down arrow case 38: // up arrow case 16: // shift case 17: // ctrl case 18: // alt break case 9: // tab case 13: // enter if (!this.shown) return this.select() break case 27: // escape if (!this.shown) return this.hide() break default: this.lookup() } e.stopPropagation() e.preventDefault() } , focus: function (e) { this.focused = true } , blur: function (e) { this.focused = false if (!this.mousedover && this.shown) this.hide() } , click: function (e) { e.stopPropagation() e.preventDefault() this.select() this.$element.focus() } , mouseenter: function (e) { this.mousedover = true this.$menu.find('.active').removeClass('active') $(e.currentTarget).addClass('active') } , mouseleave: function (e) { this.mousedover = false if (!this.focused && this.shown) this.hide() } } /* TYPEAHEAD PLUGIN DEFINITION * =========================== */ var old = $.fn.typeahead $.fn.typeahead = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('typeahead') , options = typeof option == 'object' && option if (!data) $this.data('typeahead', (data = new Typeahead(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.typeahead.defaults = { source: [] , items: 8 , menu: '<ul class="typeahead dropdown-menu"></ul>' , item: '<li><a href="#"></a></li>' , minLength: 1 } $.fn.typeahead.Constructor = Typeahead /* TYPEAHEAD NO CONFLICT * =================== */ $.fn.typeahead.noConflict = function () { $.fn.typeahead = old return this } /* TYPEAHEAD DATA-API * ================== */ $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) { var $this = $(this) if ($this.data('typeahead')) return $this.typeahead($this.data()) }) }(window.jQuery); /* ========================================================== * bootstrap-affix.js v2.3.1 * http://twitter.github.com/bootstrap/javascript.html#affix * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* AFFIX CLASS DEFINITION * ====================== */ var Affix = function (element, options) { this.options = $.extend({}, $.fn.affix.defaults, options) this.$window = $(window) .on('scroll.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this)) this.$element = $(element) this.checkPosition() } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() , scrollTop = this.$window.scrollTop() , position = this.$element.offset() , offset = this.options.offset , offsetBottom = offset.bottom , offsetTop = offset.top , reset = 'affix affix-top affix-bottom' , affix if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && scrollTop <= offsetTop ? 'top' : false if (this.affixed === affix) return this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : '')) } /* AFFIX PLUGIN DEFINITION * ======================= */ var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('affix') , options = typeof option == 'object' && option if (!data) $this.data('affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix $.fn.affix.defaults = { offset: 0 } /* AFFIX NO CONFLICT * ================= */ $.fn.affix.noConflict = function () { $.fn.affix = old return this } /* AFFIX DATA-API * ============== */ $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) , data = $spy.data() data.offset = data.offset || {} data.offsetBottom && (data.offset.bottom = data.offsetBottom) data.offsetTop && (data.offset.top = data.offsetTop) $spy.affix(data) }) }) }(window.jQuery);
(function() { module('gpub.api.endToEndTest'); var sgfs = testdata.sgfs; var sgf = testdata.gogameguru_commentary; var base = testdata.base; test('Setup', function() { ok(sgf, 'testdata defined'); ok(glift, 'glift global defined'); ok(gpub, 'gpub global defined'); }); test('Testing validation: no template', function() { try { var out = gpub.create({ }); } catch (e) { ok(/Template parameter/.test(e).toString()); } }); test('Testing full happy path, no exceptions', function() { var output = gpub.create({ template: 'PROBLEM_EBOOK', games: {sgf: sgf}, grouping: [ 'sgf', ], diagramOptions: { maxDiagrams: 20 }, }) ok(output, 'Output should be defined'); }); test('Testing full happy path, groupings', function() { var output = gpub.create({ template: 'PROBLEM_EBOOK', games: {z1: sgf}, grouping: { title: 'zed', positions: [ 'z1', ], }, diagramOptions: { maxDiagrams: 20 }, }) ok(output, 'Output should be defined'); }); test('Testing full happy path: game commentary', function() { var output = gpub.create({ template: 'GAME_COMMENTARY_EBOOK', games: {z1: sgf}, grouping: ['z1'], }) ok(output, 'Output should be defined'); ok(output.spec, 'Should have spec'); ok(output.files, 'Should have files'); }); // TODO(kashomon): Add back in once book conversion is complete. // test('Testing PDF/X-1a:2001 compatibility (no exceptions)', function() { // var output = gpub.create({ // games: {'zed': sgfs.base}, // colorProfileFilePath: 'ISOcoated_v2_300_eci.icc', // pdfx1a: true // }); // ok(/\/MediaBox/.test(output), 'Media box must be defined'); // ok(/\/GTS_PDFXVersion/.test(output), 'PDFXVersion must be specified'); // ok(/\/Title/.test(output), 'Title must be specified'); // ok(/\\pdfminorversion=3/.test(output), 'PDF version be 1.3'); // ok(/\\pdfobjcompresslevel=0/.test(output), 'Compression should be off'); // ok(/\/OutputIntent/.test(output), 'OutputIntent must be specified'); // }); })();
define( [ 'angular', 'angular-mocks', 'mockQ', 'halp', 'jasmine' ], function( ng, _, mockQ, halp, jasmine ) { 'use strict'; // Examples are from the RFC: http://tools.ietf.org/html/draft-kelly-json-hal-06 var exampleOrders = { "_links": { "self": { "href": "/orders" }, "next": { "href": "/orders?page=2" }, "find": { "href": "/orders{?id}", "templated": true }, }, "_embedded": { "orders": [ { "_links": { "self": { "href": "/orders/123" }, "basket": { "href": "/baskets/98712" }, "customer": { "href": "/customers/7809" } }, "total": 30.00, "currency": "USD", "status": "shipped" }, { "_links": { "self": { "href": "/orders/124" }, "basket": { "href": "/baskets/97213" }, "customer": { "href": "/customers/12369" } }, "total": 20.00, "currency": "USD", "status": "processing" } ] }, "currentlyProcessing": 14, "shippedToday": 20 }; var exampleOrder = { "_links": { "self": { "href": "/orders/523" }, "warehouse": { "href": "/warehouse/56" }, "invoice": { "href": "/invoices/873" } }, "currency": "USD", "status": "shipped", "total": 10.20 }; // Another custom example: var exampleMultiResults = { "_links": { "self": { "href": "/results" }, "matches": [ { "href": "/results/617-761", name: "X" }, { "href": "http://example.com", name: "Z" }, { "href": "http://example.com/XYZ", name: "Y" } ] }, "results": [ { "title": "interesting result from this server", "rank": 0, "match": "X" }, { "title": "an example result", "rank": 20, "match": "Z" }, { "title": "example XYZ -- another example", "rank": 27, "match": "Y" } ] }; // Some shorthands: var exampleOrderLink = exampleOrder._links.self; var exampleEmbeddedOrder0 = exampleOrders._embedded.orders[ 0 ]; var exampleEmbeddedOrder1 = exampleOrders._embedded.orders[ 1 ]; describe( 'halp', function() { var hal; describe( 'without http', function() { var getSpy; beforeEach( function () { var $http = { 'get': function() {} }; getSpy = spyOn( $http, 'get' ); hal = halp( mockQ, $http ); } ); afterEach( function() { expect( getSpy ).not.toHaveBeenCalled(); } ); it( 'instantiates a link from a uri', function () { expect( hal.link( exampleOrderLink.href ).href ).toEqual( exampleOrderLink.href ); } ); it( 'instantiates a link from a hal-link representation', function () { expect( hal.link( exampleOrderLink ).href ).toEqual( exampleOrderLink.href ); } ); it( 'instantiates a resource from a hal-resource representation', function () { var order = hal.resource( exampleOrder ); expect( order ).toBeDefined(); } ); it( 'allows to resolve links from resources', function () { var order = hal.resource( exampleOrder ); expect( order.link( 'warehouse' ).href ).toEqual( exampleOrder._links.warehouse.href ); } ); } ); describe( 'using http', function() { var $httpBackend, $http; beforeEach( inject( function($injector) { $httpBackend = $injector.get( '$httpBackend' ); $httpBackend.when( 'GET', exampleOrder._links.self.href ).respond( exampleOrder ); $httpBackend.when( 'GET', '/results/617-761' ).respond( {} ); $http = $injector.get( '$http' ); } ) ); beforeEach( function () { hal = halp( mockQ, $http ); } ); it( 'allows to fetch resources from links', function() { var result = {}; hal.link( exampleOrderLink ).fetch().then( function( res ) { result = res; } ); $httpBackend.flush(); expect( result.link( 'self' ).href ).toEqual(exampleOrderLink.href ); } ); it( 'allows to follow links from resources', function() { var result = {}; var order = hal.resource( exampleOrder ); order.follow( 'self' ).then( function( res ) { result = res; } ); $httpBackend.flush(); expect( result.link( 'self' ).href ).toEqual(exampleOrderLink.href ); } ); // :TBD: /* it( 'allows to qualify relations by name when following links', function() { var searchResults = hal.resource( exampleMultiResults ); console.log( 'link', searchResults.link( 'matches', { name: 'X' } ) ); var result = {}; searchResults.follow( 'matches', { name: 'X' } ).then( function( res ) { result = res; } ); $httpBackend.flush(); expect( result.link( 'self' ).href ).toEqual( "/results/617-761" ); } ); */ } ) } ); } );
hljs.registerLanguage("clojure-repl",(()=>{"use strict";return e=>({ name:"Clojure REPL",contains:[{className:"meta",begin:/^([\w.-]+|\s*#_)?=>/, starts:{end:/$/,subLanguage:"clojure"}}]})}))();
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // MIT License. See license.txt frappe.provide('frappe.views'); // opts: // stats = list of fields // doctype // parent // set_filter = function called on click frappe.views.ListSidebar = Class.extend({ init: function(opts) { $.extend(this, opts); this.make(); this.get_stats(); }, make: function() { var sidebar_content = frappe.render_template("list_sidebar", {doctype: this.doclistview.doctype}); this.offcanvas_list_sidebar = $(".offcanvas .list-sidebar").html(sidebar_content); this.page_sidebar = $('<div class="list-sidebar hidden-xs hidden-sm"></div>') .html(sidebar_content) .appendTo(this.page.sidebar.empty()); this.sidebar = this.page_sidebar.add(this.offcanvas_list_sidebar); this.setup_reports(); this.setup_assigned_to_me(); if(frappe.views.calendar[this.doctype]) { this.sidebar.find(".calendar-link, .gantt-link").removeClass("hide"); } if(frappe.treeview_settings[this.doctype]) { this.sidebar.find(".tree-link").removeClass("hide"); } }, setup_reports: function() { // add reports linked to this doctype to the dropdown var me = this; var added = []; var dropdown = this.page.sidebar.find('.reports-dropdown'); var divider = false; var add_reports = function(reports) { $.each(reports, function(name, r) { if(!r.ref_doctype || r.ref_doctype==me.doctype) { var report_type = r.report_type==='Report Builder' ? 'Report/' + r.ref_doctype : 'query-report'; var route = r.route || report_type + '/' + r.name; if(added.indexOf(route)===-1) { // don't repeat added.push(route); if(!divider) { $('<li role="separator" class="divider"></li>').appendTo(dropdown); divider = true; } $('<li><a href="#'+ route + '">' + __(r.name)+'</a></li>').appendTo(dropdown); } } }); } // from reference doctype if(this.doclistview.listview.settings.reports) { add_reports(this.doclistview.listview.settings.reports) } // from specially tagged reports add_reports(frappe.boot.user.all_reports || []); }, setup_assigned_to_me: function() { var me = this; this.page.sidebar.find(".assigned-to-me a").on("click", function() { me.doclistview.assigned_to_me(); }); this.offcanvas_list_sidebar.find(".assigned-to-me a").on("click", function() { me.doclistview.assigned_to_me(); }); }, get_stats: function() { var me = this return frappe.call({ type: "GET", method: 'frappe.desk.reportview.get_stats', args: { stats: me.stats, doctype: me.doctype }, callback: function(r) { // This gives a predictable stats order $.each(me.stats, function(i, v) { me.render_stat(v, (r.message || {})[v]); }); // reload button at the end // if(me.stats.length) { // $('<a class="small text-muted">'+__('Refresh Stats')+'</a>') // .css({"margin-top":"15px", "display":"inline-block"}) // .click(function() { // me.reload_stats(); // return false; // }).appendTo($('<div class="stat-wrapper">') // .appendTo(me.sidebar)); // } me.doclistview.set_sidebar_height(); } }); }, render_stat: function(field, stat) { var me = this; var sum = 0; var label = frappe.meta.docfield_map[this.doctype][field] ? frappe.meta.docfield_map[this.doctype][field].label : field; var show_tags = '<a class="list-tag-preview hidden-xs" title="' + __("Show tags") + '"><i class="octicon octicon-pencil"></i></a>'; stat = (stat || []).sort(function(a, b) { return b[1] - a[1] }); $.each(stat, function(i,v) { sum = sum + v[1]; }) var context = { field: field, stat: stat, sum: sum, label: label==='_user_tags' ? (__("Tags") + show_tags) : __(label), }; var sidebar_stat = $(frappe.render_template("list_sidebar_stat", context)) .on("click", ".stat-link", function() { var fieldname = $(this).attr('data-field'); var label = $(this).attr('data-label'); me.set_filter(fieldname, label); return false; }) .appendTo(this.sidebar); }, reload_stats: function() { this.sidebar.find(".sidebar-stat").remove(); this.get_stats(); }, });
import gulp from 'gulp' import gutil from 'gulp-util' import uglify from 'gulp-uglify' import sourcemaps from 'gulp-sourcemaps' import source from 'vinyl-source-stream' import buffer from 'vinyl-buffer' import watchify from 'watchify' import browserify from 'browserify' import vueify from 'vueify' import babelify from 'babelify' import config from './../config' const setWatch = Symbol('set_watch'); const releaseMode = Symbol('release'); const debugMode = Symbol('debug'); const propBrowsify = Symbol('browsify'); const propWatchify = Symbol('watchify'); export default class BuildEs { constructor(entries, outputName, paths = ['./node_modules'], basedir = '.') { this.out = outputName; const debug = !config.release; this[propBrowsify] = browserify({ basedir, entries, paths, debug }).transform(vueify).transform(babelify); if (debug) this[setWatch](); } [setWatch]() { this[propWatchify] = watchify(this[propBrowsify]); this[propWatchify].on('update', this.bundle.bind(this)); this[propWatchify].on('log', gutil.log); } bundle() { if (config.release) return this[releaseMode](); return this[debugMode](); } [releaseMode]() { return this[propBrowsify].bundle() .pipe(source(this.out)) .pipe(buffer()) .pipe(uglify()) .pipe(gulp.dest(config.distJs)); } [debugMode]() { return this[propWatchify].bundle() .pipe(source(this.out)) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(uglify()) // Avoid writing to external as browsers does not update when new version is there .pipe(sourcemaps.write()) .pipe(gulp.dest(config.distJs)); } }
127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['408',"Tlece.Recruitment.Controllers Namespace","topic_000000000000018A.html"],['537',"QuestionVideoCreateController Class","topic_00000000000001F9.html"],['539',"Methods","topic_00000000000001F9_methods--.html"],['541',"Delete Method","topic_00000000000001FF.html"]];
(function () { 'use strict'; angular .module('videostoreApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig ($stateProvider) { $stateProvider.state('admin', { abstract: true, parent: 'app' }); } })();
var path = (process.argv[2]); var fs = require('fs'); var file = fs.readFileSync(path); console.log(file.toString().split('\n').length-1);
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M3 3v10c0 .55.45 1 1 1h2v7.15c0 .51.67.69.93.25l5.19-8.9c.39-.67-.09-1.5-.86-1.5H9l3.38-7.59c.29-.67-.2-1.41-.92-1.41H4c-.55 0-1 .45-1 1zm15-1c-.6 0-1.13.38-1.34.94L14.22 9.8c-.2.59.23 1.2.85 1.2.38 0 .72-.24.84-.6L16.4 9h3.2l.49 1.4c.13.36.46.6.84.6.62 0 1.05-.61.84-1.19l-2.44-6.86C19.13 2.38 18.6 2 18 2zm-1.15 5.65L18 4l1.15 3.65h-2.3z" }), 'FlashAutoRounded');
import alt from '../alt'; class ChatServerActionCreators { constructor() { this.generateActions('receiveServerStatus', 'receiveUsers', 'receiveMessages'); } } export default alt.createActions(ChatServerActionCreators);
"use babel"; import DocsParser from '../docsparser'; import { XRegExp } from 'xregexp'; class ActionscriptParser extends DocsParser { setupSettings() { var nameToken = '[a-zA-Z_][a-zA-Z0-9_]*'; this.settings = { 'typeInfo': false, 'curlyTypes': false, 'typeTag': '', 'commentCloser': ' */', 'fnIdentifier': nameToken, 'varIdentifier': '(%s)(?::%s)?' % (nameToken, nameToken), 'fnOpener': 'function(?:\\s+[gs]et)?(?:\\s+' + nameToken + ')?\\s*\\(', 'bool': 'bool', 'function': 'function' }; } parseFunction(line) { var regex = XRegExp( // fnName = function, fnName : function '(?:(?P<name1>' + this.settings.varIdentifier + ')\\s*[:=]\\s*)?' + 'function(?:\\s+(?P<getset>[gs]et))?' + // function fnName '(?:\\s+(?P<name2>' + this.settings.fnIdentifier + '))?' + // (arg1, arg2) '\\s*\\(\\s*(?P<args>.*?)\\)' ); var matches = XRegExp.exec(line, regex); if(matches === null) { return null; } regex = new RegExp(this.settings.varIdentifier, 'g'); var name = matches.name1 && (matches.name1 || matches.name2 || '').replace(regex, '\\1') || null; var args = matches.args; var options = {}; if(matches.getset == 'set') { options.as_setter = true; } return [name, args, null, options]; } parseVar(line) { return null; } getArgName(arg) { var regex = new RegExp(this.settings.varIdentifier + '(\\s*=.*)?', 'g'); return arg.replace(regex, '\\1'); } getArgType(arg) { // could actually figure it out easily, but it's not important for the documentation return null; } } export default ActionscriptParser;
'use strict'; var paths = { js: ['*.js', 'test/**/*.js', '!test/coverage/**', '!bower_components/**', 'packages/**/*.js', '!packages/**/node_modules/**'], html: ['packages/**/public/**/views/**', 'packages/**/server/views/**'], css: ['!bower_components/**', 'packages/**/public/**/css/*.css'] }; module.exports = function(grunt) { if (process.env.NODE_ENV !== 'production') { require('time-grunt')(grunt); } // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), assets: grunt.file.readJSON('config/assets.json'), clean: ['bower_components/build'], watch: { js: { files: paths.js, tasks: ['jshint'], options: { livereload: true } }, html: { files: paths.html, options: { livereload: true, interval: 500 } }, css: { files: paths.css, tasks: ['csslint'], options: { livereload: true } } }, jshint: { all: { src: paths.js, options: { jshintrc: true } } }, uglify: { core: { options: { mangle: false }, files: '<%= assets.core.js %>' } }, csslint: { options: { csslintrc: '.csslintrc' }, src: paths.css }, cssmin: { core: { files: '<%= assets.core.css %>' } }, nodemon: { dev: { script: 'server.js', options: { args: [], ignore: ['node_modules/**'], ext: 'js,html', nodeArgs: ['--debug'], delayTime: 1, cwd: __dirname } } }, concurrent: { tasks: ['nodemon', 'watch'], options: { logConcurrentOutput: true } }, mochaTest: { options: { reporter: 'spec', require: [ 'server.js', function() { require('meanio/lib/util').preload(__dirname + '/packages/**/server', 'model'); } ] }, src: ['packages/**/server/tests/**/*.js'] }, env: { test: { NODE_ENV: 'test' } }, karma: { unit: { configFile: 'karma.conf.js' } } }); //Load NPM tasks require('load-grunt-tasks')(grunt); //Default task(s). if (process.env.NODE_ENV === 'production') { grunt.registerTask('default', ['clean', 'cssmin', 'uglify', 'concurrent']); } else { grunt.registerTask('default', ['clean', 'csslint', 'concurrent']); } //Test task. grunt.registerTask('test', ['env:test', 'mochaTest', 'karma:unit']); // For Heroku users only. // Docs: https://github.com/linnovate/mean/wiki/Deploying-on-Heroku grunt.registerTask('heroku:production', ['cssmin', 'uglify']); };
import _ from 'underscore'; let isNumberOrNR = function() { if (this.isSet && (this.value === 'NR' || _.isFinite(this.value))) { return undefined; } else { return 'numOrNR'; } }, isNumericishString = function() { if (!this.isSet || this.value === null) return undefined; let v = this.value.replace(/[<,≤,=,≥,>]/g, ''); if(isFinite(parseFloat(v))) return undefined; return 'numericish'; }; export { isNumberOrNR }; export { isNumericishString };
var five = require('johnny-five'); var board = new five.Board(); board.on('ready', function(){ // Set up LEDS var red = five.Led(9), green = five.Led(10), blue = five.Led(11); // Inject into the repl board.repl.inject({ r: red, g: green, b: blue }); red.brightness(50); green.brightness(50); blue.brightness(50); });
import { css } from "lit-element"; export default css` .primary-map > div { width: 100%; height: 400px; } .primary: { color: red; } `;
var isFunction = require('./isFunction'), isObject = require('./isObject'); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @specs * * _.toNumber(3); * // => 3 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3'); * // => 3 */ function toNumber(value) { if (isObject(value)) { var other = isFunction(value.valueOf) ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber;
const jwt = require('jsonwebtoken'); const getVerify = function (token) { return new Promise((resolve, reject) => { jwt.verify(token, 'app.get(user)', function (err, decoded) { if (err) { reject(100); } else { resolve(decoded); } }); }) } const resolveToken = async function (ctx, next) { let token = ctx.request.body.token || ctx.request.query.token || ctx.request.header['x-access-token']; if (token) { try { const result = await getVerify(token); ctx.api_user = result; await next(); } catch(e) { if (e === 100) { ctx.status = 401; ctx.body = { success: false, message: 'token过期', errCode: 100, } } else { ctx.status = 500; ctx.body = { success: false, message: e.message, } } } } else { ctx.status = 403; ctx.body = { success: false, message: '缺少token', } } } module.exports = resolveToken;
define(['jquery', 'ekyna-form/collection'], function($) { "use strict"; /** * Supplier order item widget */ $.fn.supplierOrderWidget = function() { this.each(function() { var $this = $(this), $carrier = $this.find('.order-carrier'), $carrierFields = $this.find('.forwarder-fieldset'); $carrier.on('change', function() { if ($carrier.val()) { $carrierFields.slideDown(); } else { $carrierFields.slideUp(); } }).trigger('change'); }); return this; }; return { init: function($element) { $element.supplierOrderWidget(); } }; });
'use strict'; const assert = require('assert').strict; global.Ladders = require('../../.server-dist/ladders').Ladders; const {makeUser} = require('../users-utils'); describe('Matchmaker', function () { const FORMATID = 'gen7ou'; const addSearch = (player, rating = 1000, formatid = FORMATID) => { const search = new Ladders.BattleReady(player.id, formatid, player.battleSettings, rating); Ladders(formatid).addSearch(search, player); return search; }; const destroyPlayer = player => { player.resetName(); player.disconnectAll(); player.destroy(); return null; }; before(function () { clearInterval(Ladders.periodicMatchInterval); Ladders.periodicMatchInterval = null; }); beforeEach(function () { this.p1 = makeUser('Morfent', '192.168.0.1'); this.p1.battleSettings.team = 'Gengar||||lick||252,252,4,,,|||||'; Users.users.set(this.p1.id, this.p1); this.p2 = makeUser('Mrofnet', '192.168.0.2'); this.p2.battleSettings.team = 'Gengar||||lick||252,252,4,,,|||||'; Users.users.set(this.p2.id, this.p2); }); afterEach(function () { this.p1 = destroyPlayer(this.p1); this.p2 = destroyPlayer(this.p2); }); it('should add a search', function () { const s1 = addSearch(this.p1); assert(Ladders.searches.has(FORMATID)); const formatSearches = Ladders.searches.get(FORMATID).searches; assert(formatSearches instanceof Map); assert.equal(formatSearches.size, 1); assert.equal(s1.userid, this.p1.id); assert.equal(s1.settings.team, this.p1.battleSettings.team); assert.equal(s1.rating, 1000); }); it('should matchmake users when appropriate', function () { addSearch(this.p1); addSearch(this.p2); assert.equal(Ladders.searches.get(FORMATID).searches.size, 0); const [roomid] = [...this.p1.games]; Rooms.get(roomid).destroy(); }); it('should matchmake users within a reasonable rating range', function () { addSearch(this.p1); addSearch(this.p2, 2000); assert.equal(Ladders.searches.get(FORMATID).searches.size, 2); }); it('should cancel searches', function () { addSearch(this.p1); Ladders(FORMATID).cancelSearch(this.p1); Ladders.cancelSearches(this.p2); assert.equal(Ladders.searches.get(FORMATID).searches.size, 0); }); it('should periodically matchmake users when appropriate', function () { addSearch(this.p1); const s2 = addSearch(this.p2, 2000); assert.equal(Ladders.searches.get(FORMATID).searches.size, 2); s2.rating = 1000; Ladders.Ladder.periodicMatch(); assert.equal(Ladders.searches.get(FORMATID).searches.size, 0); const [roomid] = [...this.p1.games]; Rooms.get(roomid).destroy(); }); it('should create a new battle room after matchmaking', function () { assert.equal(this.p1.games.size, 0); addSearch(this.p1); addSearch(this.p2); assert.equal(this.p1.games.size, 1); for (const roomid of this.p1.games) { assert(Rooms.get(roomid).battle); } }); it('should cancel search on disconnect', function () { addSearch(this.p1); this.p1.onDisconnect(this.p1.connections[0]); assert.equal(Ladders.searches.get(FORMATID).searches.size, 0); }); it('should cancel search on merge', function () { addSearch(this.p1); this.p2.merge(this.p1); assert.equal(Ladders.searches.get(FORMATID).searches.size, 0); }); describe('#startBattle', function () { beforeEach(function () { this.s1 = addSearch(this.p1); this.s2 = addSearch(this.p2); }); afterEach(function () { this.s1 = null; this.s2 = null; }); it('should prevent battles from starting if both players are identical', function () { Object.assign(this.s2, this.s1); let room; try { room = Rooms.createBattle({ format: FORMATID, p1: {user: this.p1, team: this.s1.team}, p2: {user: this.p1, team: this.s2.team}, rated: 1000, }); } catch (e) {} assert.equal(room, undefined); }); before(function () { this.lockdown = Rooms.global.lockdown; Rooms.global.lockdown = true; }); after(function () { Rooms.global.lockdown = this.lockdown; this.lockdown = null; }); it('should prevent battles from starting if the server is in lockdown', function () { const room = Rooms.createBattle(FORMATID, {p1: this.p1, p2: this.p2, p1team: this.s1.team, p2team: this.s2.team, rated: 1000}); assert.equal(room, undefined); }); }); });
<% if (projectstylelint === 'strict') { %>const font = { properties: ['font', 'font-family', 'font-size', 'line-height', 'font-weight', 'font-style'] } const text = { properties: [ 'break', 'column', 'columns', 'hyphens', 'letter-spacing', 'tab-size', 'text', 'white-space', 'word-spacing', 'word-wrap' ] } const color = { properties: [ 'opacity', 'background', 'box-decoration-break', 'box-shadow', 'color', 'filter', 'layer', 'mask', 'mix-blend-mode' ] } const scrollbar = { properties: ['scrollbar'] } const outline = { properties: ['outline'] } const list = { properties: ['list-style', 'marker-offset'] } const tables = { properties: [ 'border-collapse', 'border-spacing', 'caption-side', 'empty-cells', 'speak-header', 'table-layout' ] } const classification = { properties: ['content', 'clear', 'display', 'float', 'isolation', 'visibility'] } const dimensions = { properties: [ 'block-size', 'box-sizing', 'size', 'width', 'min-width', 'max-width', 'height', 'min-height', 'max-height', 'inline-size', 'object' ] } const positioning = { properties: [ 'position', 'top', 'right', 'bottom', 'left', 'z-index', 'flex', 'flex-wrap', 'flex-direction', 'justify-content', 'align-content', 'align-items', 'align-self', 'grid', 'offset', 'order', 'overflow', 'text-overflow', 'clip', 'vertical-align' ] } const margins = { properties: ['margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left'] } const padding = { properties: ['padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left'] } const border = { properties: ['border', 'border-color', 'border-style', 'border-width'] } const dynamic = { properties: [ 'accelerator', 'behavior', 'caret-color', 'cursor', 'filter', 'pointer-events', 'resize', 'touch-action', 'zoom' ] } const generated = { properties: ['counter', 'fallback', 'include', 'quotes'] } const international = { properties: [ 'direction', 'ime-mode', 'layout', 'line-break', 'ruby', 'spacing', 'text-autospace', 'text-justify', 'text-kashida-space', 'unicode-bidi', 'word-break', 'writing-mode' ] } const print = { properties: ['marks', 'orphans', 'page-break', 'page', 'size', 'widows'] } const aural = { properties: [ 'azimut', 'cue', 'elevation', 'pause', 'pitch-range', 'play-during', 'richness', 'speak', 'speech', 'stress', 'voice-family', 'volume' ] } const animation = { properties: ['animation', 'transition', 'will-change'] } const transform = { properties: ['transform', 'backface-visibility', 'perspective'] } <% } %>module.exports = { 'plugins': [ 'stylelint-order', 'stylelint-scss', 'stylelint-selector-bem-pattern' ], 'extends': 'stylelint-config-sass-guidelines', 'rules': { 'at-rule-empty-line-before': [ 'never', { 'except': [ 'inside-block' ], 'ignore': [ 'after-comment', 'inside-block' ] } ], 'at-rule-name-case': 'lower', 'at-rule-name-newline-after': 'always-multi-line', 'at-rule-name-space-after': 'always', 'at-rule-no-unknown': null, 'at-rule-no-vendor-prefix': true, 'block-closing-brace-empty-line-before': 'never', 'block-closing-brace-newline-after': [ 'always', { 'ignoreAtRules': [ 'if', 'else' ] } ], 'block-closing-brace-newline-before': 'always-multi-line', 'block-closing-brace-space-after': 'always-single-line', 'block-closing-brace-space-before': 'always-single-line', 'block-no-empty': true, 'block-opening-brace-newline-after': 'always', 'block-opening-brace-newline-before': 'never-single-line', 'block-opening-brace-space-after': 'always-single-line', 'block-opening-brace-space-before': 'always-single-line', 'color-hex-case': 'lower', 'color-hex-length': 'short', 'color-named': 'never', 'color-no-invalid-hex': true, 'comment-empty-line-before': [ 'always', { 'except': [ 'first-nested' ], 'ignore': [ 'after-comment', 'stylelint-commands' ] } ], 'comment-no-empty': true, 'comment-whitespace-inside': 'always', 'custom-property-empty-line-before': 'never', 'declaration-bang-space-after': 'never', 'declaration-bang-space-before': 'always', 'declaration-block-no-duplicate-properties': [ true, { 'ignore': [ 'consecutive-duplicates-with-different-values' ] } ], 'declaration-block-no-shorthand-property-overrides': true, 'declaration-block-semicolon-newline-after': 'always', 'declaration-block-semicolon-newline-before': 'never-multi-line', 'declaration-block-semicolon-space-after': 'always-single-line', 'declaration-block-semicolon-space-before': 'never', 'declaration-block-single-line-max-declarations': 1, 'declaration-block-trailing-semicolon': 'always', 'declaration-colon-newline-after': 'always-multi-line', 'declaration-colon-space-after': 'always-single-line', 'declaration-colon-space-before': 'never', 'declaration-empty-line-before': 'never', 'font-family-name-quotes': 'always-where-recommended', 'font-family-no-duplicate-names': true, 'font-weight-notation': 'numeric', 'function-blacklist': [ 'rgb' ], 'function-calc-no-unspaced-operator': true, 'function-comma-newline-after': 'never-multi-line', 'function-comma-newline-before': 'never-multi-line', 'function-comma-space-after': 'always', 'function-comma-space-before': 'never', 'function-linear-gradient-no-nonstandard-direction': true, 'function-max-empty-lines': 0, 'function-parentheses-newline-inside': 'never-multi-line', 'function-parentheses-space-inside': 'never', 'function-url-quotes': 'always', 'function-whitespace-after': 'always', 'indentation': 2, 'keyframe-declaration-no-important': true, 'length-zero-no-unit': true, 'max-empty-lines': 2, 'max-nesting-depth': 5, 'media-feature-colon-space-after': 'always', 'media-feature-colon-space-before': 'never', 'media-feature-name-case': 'lower', 'media-feature-name-no-unknown': true, 'media-feature-name-no-vendor-prefix': true, 'media-feature-parentheses-space-inside': 'never', 'media-feature-range-operator-space-after': 'always', 'media-feature-range-operator-space-before': 'always', 'media-query-list-comma-newline-after': 'always', 'media-query-list-comma-newline-before': 'never-multi-line', 'media-query-list-comma-space-after': 'always-single-line', 'media-query-list-comma-space-before': 'never', 'no-duplicate-selectors': true, 'no-empty-source': true, 'no-eol-whitespace': true, 'no-extra-semicolons': true, 'no-invalid-double-slash-comments': true, 'no-missing-end-of-source-newline': true, 'no-unknown-animations': true, 'number-leading-zero': <% if ( projectprettier === true ) { %>'always'<% } else { %>'never'<% } %>, 'number-max-precision': 6, 'number-no-trailing-zeros': true,<% if (projectstylelint === 'strict') { %> 'order/order': [ 'custom-properties', 'dollar-variables', 'at-variables', { type: 'at-rule', name: 'include', hasBlock: false }, 'declarations', { type: 'at-rule', name: 'include', hasBlock: true }, { type: 'at-rule', name: 'media', hasBlock: true }, 'rules', 'at-rules' ], 'order/properties-order': [ classification, positioning, dimensions, padding, border, margins, list, tables, color, font, text, outline, transform, animation, dynamic, generated, international, print, aural, scrollbar ],<% } else { %> 'order/order': null, 'order/properties-order': null,<% } %> 'order/properties-alphabetical-order': null, 'property-case': 'lower', 'property-no-unknown': true, 'property-no-vendor-prefix': true, 'rule-empty-line-before': [ 'always', { 'except': [ 'after-single-line-comment', 'first-nested' ], 'ignore': [ 'after-comment' ] } ], 'selector-attribute-brackets-space-inside': 'never', 'selector-attribute-operator-space-after': 'never', 'selector-attribute-operator-space-before': 'never', 'selector-attribute-quotes': 'always', 'selector-combinator-space-after': 'always', 'selector-combinator-space-before': 'always', 'selector-descendant-combinator-no-non-space': true, 'selector-id-pattern': '^[a-zA-Z]+$', 'selector-max-compound-selectors': 5, 'selector-max-specificity': '0,4,0', 'selector-max-id': 0, 'selector-no-qualifying-type': [ true, { 'ignore': [ 'attribute' ] } ], 'selector-pseudo-class-case': 'lower', 'selector-pseudo-class-no-unknown': true, 'selector-pseudo-class-parentheses-space-inside': 'never', 'selector-pseudo-element-case': 'lower', 'selector-pseudo-element-colon-notation': 'double', 'selector-pseudo-element-no-unknown': true, 'selector-type-case': 'lower', 'selector-type-no-unknown': [true, { ignore: ['custom-elements', 'default-namespace'] }], 'selector-max-empty-lines': 0, 'selector-list-comma-newline-after': 'always-multi-line', 'selector-list-comma-newline-before': 'never-multi-line', 'selector-list-comma-space-after': 'always-single-line', 'selector-list-comma-space-before': 'never', 'shorthand-property-no-redundant-values': true, 'string-quotes': 'single', 'unit-blacklist': [], 'unit-case': 'lower', 'unit-no-unknown': true, 'value-no-vendor-prefix': true, 'value-list-comma-newline-after': 'always-multi-line', 'value-list-comma-newline-before': 'always-multi-line', 'value-list-comma-space-after': 'always', 'value-list-comma-space-before': 'never', 'value-list-max-empty-lines': 0 } }
ScalaJS.is.scala_Function1$mcII$sp = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_Function1$mcII$sp))) }); ScalaJS.as.scala_Function1$mcII$sp = (function(obj) { if ((ScalaJS.is.scala_Function1$mcII$sp(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.Function1$mcII$sp") } }); ScalaJS.isArrayOf.scala_Function1$mcII$sp = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_Function1$mcII$sp))) }); ScalaJS.asArrayOf.scala_Function1$mcII$sp = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_Function1$mcII$sp(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.Function1$mcII$sp;", depth) } }); ScalaJS.data.scala_Function1$mcII$sp = new ScalaJS.ClassTypeData({ scala_Function1$mcII$sp: 0 }, true, "scala.Function1$mcII$sp", undefined, { scala_Function1$mcII$sp: 1, scala_Function1: 1, java_lang_Object: 1 }); //@ sourceMappingURL=Function1$mcII$sp.js.map
/** * Created by Khoa on 12/27/2016. */ "use strict"; //configs let screenWidth, screenHeight; const STARTING_PARTICLE_NUM = 75; const PARTICLE_RADIUS = 3; const MAX_VELOCITY = 200; const app = angular.module("app", []); app.controller('MainCtrl', ['$scope','animate', ($scope, animate) => { $scope.dots = []; $scope.moreDots = (num) => { addParticle(num); } //build the dot with starting position x y and vector const buildShape = () => { return { x: Math.floor(Math.random() * screenWidth - PARTICLE_RADIUS * 2) + 1 + PARTICLE_RADIUS, y: Math.floor(Math.random() * screenHeight - PARTICLE_RADIUS * 2) + 1 + PARTICLE_RADIUS, velX: Math.random() * MAX_VELOCITY - MAX_VELOCITY/2, velY: Math.random() * MAX_VELOCITY - MAX_VELOCITY/2 }; } const addParticle = (num) => { for(let i = 0; i < num; i++) { $scope.dots.push(buildShape()); } } //initialize page const init = () => { screenWidth = window.innerWidth; screenHeight = window.innerHeight; addParticle(STARTING_PARTICLE_NUM); animator($scope.dots, animate); } init(); }]); /** * On-resize directive * This directive resizes the div to the size of the entire window. **/ app.directive('resizeOnWindow', ($window) => { return (scope, element, attributes) => { const w = angular.element($window); scope.$watch(() => { return { 'height': window.innerHeight, 'width': window.innerWidth }; }, (newValue, oldValue) => { screenWidth = newValue.width || window.innerWidth; screenHeight = newValue.height || window.innerHeight; scope.resizeDiv = (offSet) => { return { 'height': (newValue.height - offSet) + 'px', 'width': '100%' }; }; }, true); w.bind('resize', () => { scope.$apply(); }) } }); app.directive('ball', ($window) => { return { restrict: 'E', link: (scope, element, attrs) => { const w = angular.element($window); element.addClass('dot'); let randBlur = Math.random(); if(randBlur > 0.50) element.addClass('dot-blur1'); else element.addClass('dot-blur2'); scope.$watch(attrs.x, (x) => { element.css('left', x + 'px'); }); scope.$watch(attrs.y, (y) => { element.css('top', y + 'px'); }); } }; }); app.directive('kyleTitle', ['$window', ($window) => { return { restrict: 'A', link: (scope, element, attrs) => { const w = angular.element($window), topClass = attrs.kyleTitle, initialOffset = element.offset().top; w.bind('scroll', () => { let currentTop = w.scrollTop(); //get current pos if(currentTop < initialOffset) { //move element up/down against the scroll direction element.css('top', -1 * $window.pageYOffset + 'px'); element.removeClass(topClass); } //once current rect reaches 50, apply fixed if(currentTop > (initialOffset / 2)) { element.addClass(topClass); element.removeAttr('style'); } }); } }; }]); app.directive('fadeOnScroll', ['$window', ($window) => { return { restrict: 'A', link: (scope, element, attrs) => { const w = angular.element($window), fadeSpeed = attrs.fadeOnScroll; const height = $window.innerHeight; w.bind('scroll', () => { let offSet = $window.pageYOffset, scrolledPercentage = (offSet / height) * fadeSpeed; element.css('opacity', Math.max(1 - scrolledPercentage, 0)); }); } } }]); /** * Animate factory to be called to loop requestAnimationFrame */ app.factory('animate',['$window', '$rootScope', ($window, $rootScope) => { const requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame || $window.oRequestAnimationFrame || $window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; return (tick) => { requestAnimationFrame(() => { $rootScope.$apply(tick); }); }; }]); //function to animate dots on the screen const animator = (shapes, animate) => { (function tick(){ let i, shape, now; const maxY = screenHeight, maxX = document.body.clientWidth, multiplier = -30; //now = new Date().getTime(); for(i = 0; i < shapes.length; i++) { shape = shapes[i]; //multiplier = (shape.timestamp || now) - now; //shape.timestamp = now; const nextPosX = shape.x + multiplier * shape.velX / 1000; const nextPosY = shape.y + multiplier * shape.velY / 1000; //bounce off walls if(nextPosX < PARTICLE_RADIUS || nextPosX + PARTICLE_RADIUS > maxX) shape.velX *= -1; if(nextPosY < PARTICLE_RADIUS || nextPosY + PARTICLE_RADIUS > maxY) shape.velY *= -1; //update position shape.x += multiplier * shape.velX / 1000; shape.y += multiplier * shape.velY / 1000; //if the window is resized, bring the balls with you if(shape.x > maxX) shape.x = maxX - PARTICLE_RADIUS; if(shape.y > maxY) shape.y = maxY - PARTICLE_RADIUS; if(shape.x < 0) shape.x = PARTICLE_RADIUS; if(shape.y < PARTICLE_RADIUS) shape.y = PARTICLE_RADIUS; } animate(tick); })(); }
/** * * */ requirejs(['app'], function(app) { 'use strict'; console.log('%cfile: common.js', 'color: #C2ECFF'); app(); });
var linearScale = d3.scale.linear() .domain([0,100]) .range([0,10]); var scale = d3.scale.linear() .domain([0,1]) .range([150, 16]); var svgContainer = d3.select("body").append("svg") .attr("width", window.innerWidth) .attr("height", window.innerHeight); var rectangle_elems = [] var line_elems = [] var text_elems = [] chloroplast["elements"].forEach(function(elem) { if (elem["rectangle"]) { rectangle_elems.push(elem["rectangle"]); } if (elem["line"]) { line_elems.push(elem["line"]); } if (elem["text"]) { text_elems.push(elem["text"]); } }); var lines = svgContainer.selectAll("line") .data(line_elems) .enter() .append("line") var lineAttributes = lines .attr("x1", function (d) { return linearScale(d.x1); }) .attr("y1", function (d) { return linearScale(d.y1); }) .attr("x2", function (d) { return linearScale(d.x2); }) .attr("y2", function (d) { return linearScale(d.y2); }) .style("stroke", function(d) { return "black"; }); var rectangles = svgContainer.selectAll("rect") .data(rectangle_elems) .enter() .append("rect"); var rectangleAttributes = rectangles .attr("x", function (d) { return linearScale(d.x); }) .attr("y", function (d) { return linearScale(d.y); }) .attr("height", function (d) { return linearScale(d.height); }) .attr("width", function (d) { return linearScale(d.width); }) .style("fill", function(d) { return "red"; }) var labels = svgContainer.selectAll("text") .data(text_elems) .enter() .append("text") var labelAttributes = labels .attr("x", function (d) { return linearScale(d.x); }) .attr("y", function (d) { return linearScale(d.y); }) .style("fill", function(d) { return "black"; }) .text(function (d) { return d.seq; }); function zoomed() { svgContainer.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); labelAttributes .attr("y", function (d) { return linearScale(d.y) - (d3.event.scale * 20 * Math.PI); }) .style("font-size", function () { var size = d3.select(this).style("font-size").replace(/px/, ""); var increment = scale(d3.event.scale); if (increment <= 16) { return "16px"; } //if (increment >= 48) { // return "48px"; //} return increment + "px"; }) .attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); rectangleAttributes.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); lineAttributes.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); } var zoom = d3.behavior.zoom() .on("zoom", zoomed); var body = d3.select("svg").call(zoom);
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require common //= require_tree .
var playerInstance = null; var Player = Backbone.View.extend({ tagName: "div", videoInfoObject: null, templateID: "framework/player/generic", template: null, recreate_on_play: false, state: null, previousState : null, _hasBufferIndicator: false, playerCurrentTime: -1, seekImmediatellyToPosition: false, resumePlayDelay: 0, initialize: function(_deviceInfo) { this.deviceInfo = _deviceInfo; this.template = window.JST[this.templateID]; this.states = {}; this.states.playing = new PlayingState(this); this.states.pausing = new PausingState(this); this.states.stopping = new StoppingState(this); this.setInitialState(); playerInstance = this; }, setInitialState: function() { Logger.log('Player setInitialState ...'); //this.changeState(this.states.stopping); this.playerCurrentTime = -1; this.state = this.states.stopping; }, play: function() { Logger.log('Player play ...'); this.state.play(); }, pause: function() { Logger.log('Player pause ...'); this.state.pause(); }, stop: function() { Logger.log('Player stop ...'); this.state.stop(); }, playVideo: function(_videoInfoObject,_seekTo) { this.videoInfoObject = _videoInfoObject; this.blockPauseState = true; if(typeof _seekTo != 'undefined'){ this.seekImmediatellyToPosition = _seekTo; } else{ this.seekImmediatellyToPosition = false; } }, buffering_started: function() { Logger.log('Player buffering_started ...'); this.trigger("player:buffering_started"); }, buffering_completed: function() { Logger.log('Player buffering_completed ...'); this.trigger("player:buffering_completed"); }, buffering_progress: function(_time) { //Logger.log('Player buffering_progress ...'); this.trigger("player:buffering_progress",_time); }, time_update: function(_timeInSecs, _timeInDeviceFormat) { //Logger.log('Player time_update ...' + _timeInSecs); // unblock pause state if current playtime is greater than zero if (this.blockPauseState && (_timeInSecs > this.resumePlayDelay || (_timeInDeviceFormat && _timeInDeviceFormat > this.resumePlayDelay)) ) { this.blockPauseState = false; this.trigger("player:playback_started"); if(this.seekImmediatellyToPosition){ this.playerCurrentTime = 0; this.seek(this.seekImmediatellyToPosition); this.seekImmediatellyToPosition = false; } } this.playerCurrentTime = _timeInSecs; this.trigger("player:time_update",_timeInSecs); }, duration_update: function(_time) { //Logger.log('Player total_time_update ...'); this.trigger("player:duration_update",_time); }, playback_ended: function() { Logger.log('Player playback_ended'); this.reset(); this.trigger("player:playback_ended"); }, fatal_error: function() { Logger.log('Player fatal_error ...'); this.reset(); this.trigger("player:fatal_error"); }, changeState: function(state) { // Make sure the current state wasn't passed in if (this.state !== state) { // don't change into pausing state when it's not unblocked if (state instanceof PausingState && this.blockPauseState) { return false; } // Make sure the current state exists before // calling exit() on it if (this.state) { this.state.exit(); } this.previousState = this.state; this.state = state; this.state.enter(this.previousState); this.state.execute(); } return true; }, toggle_play_pause: function() { Logger.log('toggle_play_pause...'); if(this.state instanceof PlayingState) { this.pause(); } else { this.play(); } }, reset: function() { this.stop(); this.seekImmediatellyToPosition = false; this.setInitialState(); }, getRenderingContext: function() { if(this.videoInfoObject !== null){ return { url: this.videoInfoObject.url, type: this.videoInfoObject.type }; } else { return { url: '', type: Player.VIDEO_TYPES.MP4 }; } }, render: function() { this.$el.html(this.template(this.getRenderingContext())); return this; }, hide: function () { this.$el.hide(); }, show: function () { this.$el.show(); }, setDisplayArea: function(x,y,width, height) { // Must be implemented in extending subclass }, seekTo: function(timeInSeconds) { // Must be implemented in extending subclass }, /** * Seek relative from the current position * -10 means 10 secs back, 10 means 10 secs forward */ seek: function(timeInSeconds) { var time = this.playerCurrentTime + timeInSeconds; if (time < 0) { time = 0; } this.seekTo(time); }, /* * Device/technology specific methods */ doPlay: function () { // must be implemented in extending subclass }, doPause: function () { // must be implemented in extending subclass }, doStop: function () { // must be implemented in extending subclass }, createVideoObject: function(_url,_type){ Logger.warn("createVideoObject is deprecated -> build your own videoInfoObject: {url: ..,type: ..}, for types see: Player.VIDEO_TYPES") return {url: _url,type: _type}; }, isPaused: function(){ return (this.state instanceof PausingState); }, isPlaying: function(){ return (this.state instanceof PlayingState); }, isStopped: function(){ return (this.state instanceof StoppingState); }, hasBufferIndicator: function(){ return this._hasBufferIndicator; }, },{ VIDEO_TYPES: { MP4: "video/mp4", HLS: "application/vnd.apple.mpegurl", } });
import { module, test } from 'qunit'; import { visit, currentURL } from '@ember/test-helpers'; import { setupApplicationTest } from 'ember-qunit'; module('Acceptance | list rentals', function(hooks) { setupApplicationTest(hooks); test('should show rentals as the home page', async function(assert) { await visit('/'); assert.equals(currentURL, ) }); test('should link to information about the company', async function(assert) { }); test('should link to contact information', async function(assert) { }); test('should list available rentals', async function(assert) { }); test('should filter the list of rentals by city', async function(assert) { }); test('should show details for a selected rental', async function(assert) { }); });
/** * Module dependencies */ var ft = require('./fileTools') var formatTools = require('./formatTools') /** * Generate a Mongoose model * @param {string} path * @param {string} modelName * @param {array} modelFields * @param {function} cb */ function generateModel (path, modelName, modelFields, cb, es6) { ft.createDirIfIsNotDefined(path, 'models', function () { var fields = formatTools.getFieldsForModelTemplate(modelFields) var schemaName = modelName + 'Schema' var model = ft.loadTemplateSync(es6 ? 'model.es6.js' : 'model.js') model = model.replace(/{modelName}/, modelName) model = model.replace(/{schemaName}/g, schemaName) model = model.replace(/{fields}/, fields) if (es6) { ft.writeFile(path + '/models/' + modelName + '.js', model, null, cb) } else { ft.writeFile(path + '/models/' + modelName + 'Model.js', model, null, cb) } }) } /** * Generate a Express router * @param {string} path * @param {string} modelName * @param {function} cb */ function generateRouter (path, modelName, cb, es6) { ft.createDirIfIsNotDefined(path, 'routes', function () { var router = ft.loadTemplateSync(es6 ? 'router.es6.js' : 'router.js') var permissionsName = modelName.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase() router = router.replace(/{controllerName}/g, modelName + 'Controller') router = router.replace(/{permissionsName}/g, permissionsName) ft.writeFile(path + '/routes/' + modelName + '.js', router, null, cb) }) } /** * Generate Controller * @param {string} path * @param {string} modelName * @param {array} modelFields * @param {function} cb */ function generateController (path, modelName, modelFields, cb, es6) { ft.createDirIfIsNotDefined(path, 'controllers', function () { var controller = ft.loadTemplateSync(es6 ? 'controller.es6.js' : 'controller.js') var updateFields = '' var createFields = '\r' modelFields.forEach(function (f, index, fields) { var field = f.name updateFields += modelName + '.' + field + ' = req.body.' + field + ' ? req.body.' + field + ' : ' + modelName + '.' + field + ';' updateFields += '\r\t\t\t' createFields += '\t\t\t' + field + ' : req.body.' + field createFields += ((fields.length - 1) > index) ? ',\r' : '\r' }) var upperName = modelName upperName = upperName.charAt(0).toUpperCase() + upperName.slice(1) controller = controller.replace(/{modelName}/g, modelName + 'Model') controller = controller.replace(/{name}/g, modelName) controller = controller.replace(/{pluralName}/g, formatTools.pluralize(modelName)) controller = controller.replace(/{controllerName}/g, modelName + 'Controller') controller = controller.replace(/{createFields}/g, createFields) controller = controller.replace(/{updateFields}/g, updateFields) controller = controller.replace(/{upperName}/g, upperName + 'Model') if (es6) { ft.writeFile(path + '/controllers/' + modelName + '.js', controller, null, cb) } else { ft.writeFile(path + '/controllers/' + modelName + 'Controller.js', controller, null, cb) } }) } module.exports = { generateModel: generateModel, generateRouter: generateRouter, generateController: generateController }
/*! * jQuery UI Effects Slide 1.10.3 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/slide-effect/ * * Depends: * jquery.ui.effect.js */ (function( $, undefined ) { $.effects.effect.slide = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "width", "height" ], mode = $.effects.setMode( el, o.mode || "show" ), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {}; // Adjust $.effects.save( el, props ); el.show(); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); $.effects.createWrapper( el ).css({ overflow: "hidden" }); if ( show ) { el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); } // Animation animation[ ref ] = ( show ? ( positiveMotion ? "+=" : "-=") : ( positiveMotion ? "-=" : "+=")) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery);
var webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: "dist/assets", filename: "bundle.js", publicPath: "assets" }, devServer: { inline: true, contentBase: './dist', port: 5000 }, module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loader: ["babel-loader"], query: { presets: ["latest", "stage-0", "react"] } }, { test: /\.json$/, exclude: /(node_modules)/, loader: "json-loader" }, { test: /\.css$/, loader: 'style-loader!css-loader!autoprefixer-loader' }, { test: /\.scss$/, loader: 'style-loader!css-loader!autoprefixer-loader!sass-loader' } ] } }
var gulp = require('gulp'); var plug = require('gulp-load-plugins')(); var _ = require('lodash'); var isProduction = function(file) { return process.env.NODE_ENV === 'production'; }; var isDebug = function(file) { return isProduction(file); }; gulp.task('test', function () { return gulp.src('spec/*.js') .pipe(plug.jasmine({ verbose: true, includeStackTrace: true })); }); gulp.task('watch', ['test'], function() { gulp.watch(['lib/**/*.*'], ['test']); }); gulp.task('default', ['test']);
/*! * HTML5 export buttons for Buttons and DataTables. * 2016 SpryMedia Ltd - datatables.net/license * * FileSaver.js (1.1.20160328) - MIT license * Copyright © 2016 Eli Grey - http://eligrey.com */ (function( factory ){ if ( typeof define === 'function' && define.amd ) { // AMD define( ['jquery', 'datatables.net', 'datatables.net-buttons'], function ( $ ) { return factory( $, window, document ); } ); } else if ( typeof exports === 'object' ) { // CommonJS module.exports = function (root, $, jszip, pdfmake) { if ( ! root ) { root = window; } if ( ! $ || ! $.fn.dataTable ) { $ = require('datatables.net')(root, $).$; } if ( ! $.fn.dataTable.Buttons ) { require('datatables.net-buttons')(root, $); } return factory( $, root, root.document, jszip, pdfmake ); }; } else { // Browser factory( jQuery, window, document ); } }(function( $, window, document, jsZip, pdfMake, undefined ) { 'use strict'; var DataTable = $.fn.dataTable; // Allow the constructor to pass in JSZip and PDFMake from external requires. // Otherwise, use globally defined variables, if they are available. if ( jsZip === undefined ) { jsZip = window.JSZip; } if ( pdfMake === undefined ) { pdfMake = window.pdfMake; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * FileSaver.js dependency */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ var _saveAs = (function(view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet , get_URL = function() { return view.URL || view.webkitURL || view; } , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = "download" in save_link , click = function(node) { var event = new MouseEvent("click"); node.dispatchEvent(event); } , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent) , webkit_req_fs = view.webkitRequestFileSystem , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem , throw_outside = function(ex) { (view.setImmediate || view.setTimeout)(function() { throw ex; }, 0); } , force_saveable_type = "application/octet-stream" , fs_min_size = 0 // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to , arbitrary_revoke_timeout = 1000 * 40 // in ms , revoke = function(file) { var revoker = function() { if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } }; /* // Take note W3C: var uri = typeof file === "string" ? file : file.toURL() , revoker = function(evt) { // idealy DownloadFinishedEvent.data would be the URL requested if (evt.data === uri) { if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } } } ; views.addEventListener("downloadfinished", revoker); */ setTimeout(revoker, arbitrary_revoke_timeout); } , dispatch = function(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } } , auto_bom = function(blob) { // prepend BOM for UTF-8 XML and text/* types (including HTML) if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new Blob(["\ufeff", blob], {type: blob.type}); } return blob; } , FileSaver = function(blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } // First try a.download, then web filesystem, then object URLs var filesaver = this , type = blob.type , blob_changed = false , object_url , target_view , dispatch_all = function() { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object URLs , fs_error = function() { if (target_view && is_safari && typeof FileReader !== "undefined") { // Safari doesn't allow downloading of blob urls var reader = new FileReader(); reader.onloadend = function() { var base64Data = reader.result; target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/)); filesaver.readyState = filesaver.DONE; dispatch_all(); }; reader.readAsDataURL(blob); filesaver.readyState = filesaver.INIT; return; } // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_URL().createObjectURL(blob); } if (target_view) { target_view.location.href = object_url; } else { var new_tab = view.open(object_url, "_blank"); if (new_tab === undefined && is_safari) { //Apple do not allow window.open, see http://bit.ly/1kZffRI view.location.href = object_url } } filesaver.readyState = filesaver.DONE; dispatch_all(); revoke(object_url); } , abortable = function(func) { return function() { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; } , create_if_not_found = {create: true, exclusive: false} , slice ; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_URL().createObjectURL(blob); setTimeout(function() { save_link.href = object_url; save_link.download = name; click(save_link); dispatch_all(); revoke(object_url); filesaver.readyState = filesaver.DONE; }); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 // Update: Google errantly closed 91158, I submitted it again: // https://code.google.com/p/chromium/issues/detail?id=389642 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) { var save = function() { dir.getFile(name, create_if_not_found, abortable(function(file) { file.createWriter(abortable(function(writer) { writer.onwriteend = function(event) { target_view.location.href = file.toURL(); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); revoke(file); }; writer.onerror = function() { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function(event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function() { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, {create: false}, abortable(function(file) { // delete file if it already exists file.remove(); save(); }), abortable(function(ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); } , FS_proto = FileSaver.prototype , saveAs = function(blob, name, no_auto_bom) { return new FileSaver(blob, name, no_auto_bom); } ; // IE 10+ (native saveAs) if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { return function(blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } return navigator.msSaveOrOpenBlob(blob, name || "download"); }; } FS_proto.abort = function() { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; return saveAs; }( typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content )); // Expose file saver on the DataTables API. Can't attach to `DataTables.Buttons` // since this file can be loaded before Button's core! DataTable.fileSave = _saveAs; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Local (private) functions */ /** * Get the file name for an exported file. * * @param {object} config Button configuration * @param {boolean} incExtension Include the file name extension */ var _filename = function ( config, incExtension ) { // Backwards compatibility var filename = config.filename === '*' && config.title !== '*' && config.title !== undefined ? config.title : config.filename; if ( typeof filename === 'function' ) { filename = filename(); } if ( filename.indexOf( '*' ) !== -1 ) { filename = $.trim( filename.replace( '*', $('title').text() ) ); } // Strip characters which the OS will object to filename = filename.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); return incExtension === undefined || incExtension === true ? filename+config.extension : filename; }; /** * Get the sheet name for Excel exports. * * @param {object} config Button configuration */ var _sheetname = function ( config ) { var sheetName = 'Sheet1'; if ( config.sheetName ) { sheetName = config.sheetName.replace(/[\[\]\*\/\\\?\:]/g, ''); } return sheetName; }; /** * Get the title for an exported file. * * @param {object} config Button configuration */ var _title = function ( config ) { var title = config.title; if ( typeof title === 'function' ) { title = title(); } return title.indexOf( '*' ) !== -1 ? title.replace( '*', $('title').text() || 'Exported data' ) : title; }; /** * Get the newline character(s) * * @param {object} config Button configuration * @return {string} Newline character */ var _newLine = function ( config ) { return config.newline ? config.newline : navigator.userAgent.match(/Windows/) ? '\r\n' : '\n'; }; /** * Combine the data from the `buttons.exportData` method into a string that * will be used in the export file. * * @param {DataTable.Api} dt DataTables API instance * @param {object} config Button configuration * @return {object} The data to export */ var _exportData = function ( dt, config ) { var newLine = _newLine( config ); var data = dt.buttons.exportData( config.exportOptions ); var boundary = config.fieldBoundary; var separator = config.fieldSeparator; var reBoundary = new RegExp( boundary, 'g' ); var escapeChar = config.escapeChar !== undefined ? config.escapeChar : '\\'; var join = function ( a ) { var s = ''; // If there is a field boundary, then we might need to escape it in // the source data for ( var i=0, ien=a.length ; i<ien ; i++ ) { if ( i > 0 ) { s += separator; } s += boundary ? boundary + ('' + a[i]).replace( reBoundary, escapeChar+boundary ) + boundary : a[i]; } return s; }; var header = config.header ? join( data.header )+newLine : ''; var footer = config.footer && data.footer ? newLine+join( data.footer ) : ''; var body = []; for ( var i=0, ien=data.body.length ; i<ien ; i++ ) { body.push( join( data.body[i] ) ); } return { str: header + body.join( newLine ) + footer, rows: body.length }; }; /** * Safari's data: support for creating and downloading files is really poor, so * various options need to be disabled in it. See * https://bugs.webkit.org/show_bug.cgi?id=102914 * * @return {Boolean} `true` if Safari */ var _isSafari = function () { return navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1 && navigator.userAgent.indexOf('Opera') === -1; }; /** * Convert from numeric position to letter for column names in Excel * @param {int} n Column number * @return {string} Column letter(s) name */ function createCellPos( n ){ var ordA = 'A'.charCodeAt(0); var ordZ = 'Z'.charCodeAt(0); var len = ordZ - ordA + 1; var s = ""; while( n >= 0 ) { s = String.fromCharCode(n % len + ordA) + s; n = Math.floor(n / len) - 1; } return s; } try { var _serialiser = new XMLSerializer(); var _ieExcel; } catch (t) {} /** * Recursively add XML files from an object's structure to a ZIP file. This * allows the XSLX file to be easily defined with an object's structure matching * the files structure. * * @param {JSZip} zip ZIP package * @param {object} obj Object to add (recursive) */ function _addToZip( zip, obj ) { if ( _ieExcel === undefined ) { // Detect if we are dealing with IE's _awful_ serialiser by seeing if it // drop attributes _ieExcel = _serialiser .serializeToString( $.parseXML( excelStrings['xl/worksheets/sheet1.xml'] ) ) .indexOf( 'xmlns:r' ) === -1; } $.each( obj, function ( name, val ) { if ( $.isPlainObject( val ) ) { var newDir = zip.folder( name ); _addToZip( newDir, val ); } else { if ( _ieExcel ) { // IE's XML serialiser will drop some name space attributes from // from the root node, so we need to save them. Do this by // replacing the namespace nodes with a regular attribute that // we convert back when serialised. Edge does not have this // issue var worksheet = val.childNodes[0]; var i, ien; var attrs = []; for ( i=worksheet.attributes.length-1 ; i>=0 ; i-- ) { var attrName = worksheet.attributes[i].nodeName; var attrValue = worksheet.attributes[i].nodeValue; if ( attrName.indexOf( ':' ) !== -1 ) { attrs.push( { name: attrName, value: attrValue } ); worksheet.removeAttribute( attrName ); } } for ( i=0, ien=attrs.length ; i<ien ; i++ ) { var attr = val.createAttribute( attrs[i].name.replace( ':', '_dt_b_namespace_token_' ) ); attr.value = attrs[i].value; worksheet.setAttributeNode( attr ); } } var str = _serialiser.serializeToString(val); // Fix IE's XML if ( _ieExcel ) { // IE doesn't include the XML declaration if ( str.indexOf( '<?xml' ) === -1 ) { str = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+str; } // Return namespace attributes to being as such str = str.replace( /_dt_b_namespace_token_/g, ':' ); } // Both IE and Edge will put empty name space attributes onto the // rows and columns making them useless str = str .replace( /<row xmlns="" /g, '<row ' ) .replace( /<cols xmlns="">/g, '<cols>' ); zip.file( name, str ); } } ); } /** * Create an XML node and add any children, attributes, etc without needing to * be verbose in the DOM. * * @param {object} doc XML document * @param {string} nodeName Node name * @param {object} opts Options - can be `attr` (attributes), `children` * (child nodes) and `text` (text content) * @return {node} Created node */ function _createNode( doc, nodeName, opts ) { var tempNode = doc.createElement( nodeName ); if ( opts ) { if ( opts.attr ) { $(tempNode).attr( opts.attr ); } if( opts.children ) { $.each( opts.children, function ( key, value ) { tempNode.appendChild( value ); }); } if( opts.text ) { tempNode.appendChild( doc.createTextNode( opts.text ) ); } } return tempNode; } /** * Get the width for an Excel column based on the contents of that column * @param {object} data Data for export * @param {int} col Column index * @return {int} Column width */ function _excelColWidth( data, col ) { var max = data.header[col].length; var len; if ( data.footer && data.footer[col].length > max ) { max = data.footer[col].length; } for ( var i=0, ien=data.body.length ; i<ien ; i++ ) { len = data.body[i][col].toString().length; if ( len > max ) { max = len; } // Max width rather than having potentially massive column widths if ( max > 40 ) { break; } } // And a min width return max > 5 ? max : 5; } // Excel - Pre-defined strings to build a basic XLSX file var excelStrings = { "_rels/.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'+ '</Relationships>', "xl/_rels/workbook.xml.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>'+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>'+ '</Relationships>', "[Content_Types].xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'+ '<Default Extension="xml" ContentType="application/xml" />'+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />'+ '<Default Extension="jpeg" ContentType="image/jpeg" />'+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" />'+ '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" />'+ '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" />'+ '</Types>', "xl/workbook.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'+ '<fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="24816"/>'+ '<workbookPr showInkAnnotation="0" autoCompressPictures="0"/>'+ '<bookViews>'+ '<workbookView xWindow="0" yWindow="0" windowWidth="25600" windowHeight="19020" tabRatio="500"/>'+ '</bookViews>'+ '<sheets>'+ '<sheet name="" sheetId="1" r:id="rId1"/>'+ '</sheets>'+ '</workbook>', "xl/worksheets/sheet1.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ '<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">'+ '<sheetData/>'+ '</worksheet>', "xl/styles.xml": '<?xml version="1.0" encoding="UTF-8"?>'+ '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">'+ '<fonts count="5" x14ac:knownFonts="1">'+ '<font>'+ '<sz val="11" />'+ '<name val="Calibri" />'+ '</font>'+ '<font>'+ '<sz val="11" />'+ '<name val="Calibri" />'+ '<color rgb="FFFFFFFF" />'+ '</font>'+ '<font>'+ '<sz val="11" />'+ '<name val="Calibri" />'+ '<b />'+ '</font>'+ '<font>'+ '<sz val="11" />'+ '<name val="Calibri" />'+ '<i />'+ '</font>'+ '<font>'+ '<sz val="11" />'+ '<name val="Calibri" />'+ '<u />'+ '</font>'+ '</fonts>'+ '<fills count="6">'+ '<fill>'+ '<patternFill patternType="none" />'+ '</fill>'+ '<fill/>'+ // Excel appears to use this as a dotted background regardless of values '<fill>'+ '<patternFill patternType="solid">'+ '<fgColor rgb="FFD9D9D9" />'+ '<bgColor indexed="64" />'+ '</patternFill>'+ '</fill>'+ '<fill>'+ '<patternFill patternType="solid">'+ '<fgColor rgb="FFD99795" />'+ '<bgColor indexed="64" />'+ '</patternFill>'+ '</fill>'+ '<fill>'+ '<patternFill patternType="solid">'+ '<fgColor rgb="ffc6efce" />'+ '<bgColor indexed="64" />'+ '</patternFill>'+ '</fill>'+ '<fill>'+ '<patternFill patternType="solid">'+ '<fgColor rgb="ffc6cfef" />'+ '<bgColor indexed="64" />'+ '</patternFill>'+ '</fill>'+ '</fills>'+ '<borders count="2">'+ '<border>'+ '<left />'+ '<right />'+ '<top />'+ '<bottom />'+ '<diagonal />'+ '</border>'+ '<border diagonalUp="false" diagonalDown="false">'+ '<left style="thin">'+ '<color auto="1" />'+ '</left>'+ '<right style="thin">'+ '<color auto="1" />'+ '</right>'+ '<top style="thin">'+ '<color auto="1" />'+ '</top>'+ '<bottom style="thin">'+ '<color auto="1" />'+ '</bottom>'+ '<diagonal />'+ '</border>'+ '</borders>'+ '<cellStyleXfs count="1">'+ '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" />'+ '</cellStyleXfs>'+ '<cellXfs count="2">'+ '<xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="0" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="1" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="2" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="3" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '<xf numFmtId="0" fontId="4" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/>'+ '</cellXfs>'+ '<cellStyles count="1">'+ '<cellStyle name="Normal" xfId="0" builtinId="0" />'+ '</cellStyles>'+ '<dxfs count="0" />'+ '<tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4" />'+ '</styleSheet>' }; // Note we could use 3 `for` loops for the styles, but when gzipped there is // virtually no difference in size, since the above can be easily compressed /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Buttons */ // // Copy to clipboard // DataTable.ext.buttons.copyHtml5 = { className: 'buttons-copy buttons-html5', text: function ( dt ) { return dt.i18n( 'buttons.copy', 'Copy' ); }, action: function ( e, dt, button, config ) { var exportData = _exportData( dt, config ); var output = exportData.str; var hiddenDiv = $('<div/>') .css( { height: 1, width: 1, overflow: 'hidden', position: 'fixed', top: 0, left: 0 } ); if ( config.customize ) { output = config.customize( output, config ); } var textarea = $('<textarea readonly/>') .val( output ) .appendTo( hiddenDiv ); // For browsers that support the copy execCommand, try to use it if ( document.queryCommandSupported('copy') ) { hiddenDiv.appendTo( dt.table().container() ); textarea[0].focus(); textarea[0].select(); try { document.execCommand( 'copy' ); hiddenDiv.remove(); dt.buttons.info( dt.i18n( 'buttons.copyTitle', 'Copy to clipboard' ), dt.i18n( 'buttons.copySuccess', { 1: "Copied one row to clipboard", _: "Copied %d rows to clipboard" }, exportData.rows ), 2000 ); return; } catch (t) {} } // Otherwise we show the text box and instruct the user to use it var message = $('<span>'+dt.i18n( 'buttons.copyKeys', 'Press <i>ctrl</i> or <i>\u2318</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>'+ 'To cancel, click this message or press escape.' )+'</span>' ) .append( hiddenDiv ); dt.buttons.info( dt.i18n( 'buttons.copyTitle', 'Copy to clipboard' ), message, 0 ); // Select the text so when the user activates their system clipboard // it will copy that text textarea[0].focus(); textarea[0].select(); // Event to hide the message when the user is done var container = $(message).closest('.dt-button-info'); var close = function () { container.off( 'click.buttons-copy' ); $(document).off( '.buttons-copy' ); dt.buttons.info( false ); }; container.on( 'click.buttons-copy', close ); $(document) .on( 'keydown.buttons-copy', function (e) { if ( e.keyCode === 27 ) { // esc close(); } } ) .on( 'copy.buttons-copy cut.buttons-copy', function () { close(); } ); }, exportOptions: {}, fieldSeparator: '\t', fieldBoundary: '', header: true, footer: false }; // // CSV export // DataTable.ext.buttons.csvHtml5 = { className: 'buttons-csv buttons-html5', available: function () { return window.FileReader !== undefined && window.Blob; }, text: function ( dt ) { return dt.i18n( 'buttons.csv', 'CSV' ); }, action: function ( e, dt, button, config ) { // Set the text var output = _exportData( dt, config ).str; var charset = config.charset; if ( config.customize ) { output = config.customize( output, config ); } if ( charset !== false ) { if ( ! charset ) { charset = document.characterSet || document.charset; } if ( charset ) { charset = ';charset='+charset; } } else { charset = ''; } _saveAs( new Blob( [output], {type: 'text/csv'+charset} ), _filename( config ) ); }, filename: '*', extension: '.csv', exportOptions: {}, fieldSeparator: ',', fieldBoundary: '"', escapeChar: '"', charset: null, header: true, footer: false }; // // Excel (xlsx) export // DataTable.ext.buttons.excelHtml5 = { className: 'buttons-excel buttons-html5', available: function () { return window.FileReader !== undefined && jsZip !== undefined && ! _isSafari() && _serialiser; }, text: function ( dt ) { return dt.i18n( 'buttons.excel', 'Excel' ); }, action: function ( e, dt, button, config ) { var rowPos = 0; var getXml = function ( type ) { var str = excelStrings[ type ]; //str = str.replace( /xmlns:/g, 'xmlns_' ).replace( /mc:/g, 'mc_' ); return $.parseXML( str ); }; var rels = getXml('xl/worksheets/sheet1.xml'); var relsGet = rels.getElementsByTagName( "sheetData" )[0]; var xlsx = { _rels: { ".rels": getXml('_rels/.rels') }, xl: { _rels: { "workbook.xml.rels": getXml('xl/_rels/workbook.xml.rels') }, "workbook.xml": getXml('xl/workbook.xml'), "styles.xml": getXml('xl/styles.xml'), "worksheets": { "sheet1.xml": rels } }, "[Content_Types].xml": getXml('[Content_Types].xml') }; var data = dt.buttons.exportData( config.exportOptions ); var currentRow, rowNode; var addRow = function ( row ) { currentRow = rowPos+1; rowNode = _createNode( rels, "row", { attr: {r:currentRow} } ); for ( var i=0, ien=row.length ; i<ien ; i++ ) { // Concat both the Cell Columns as a letter and the Row of the cell. var cellId = createCellPos(i) + '' + currentRow; var cell; if ( row[i] === null || row[i] === undefined ) { row[i] = ''; } // Detect numbers - don't match numbers with leading zeros or a negative // anywhere but the start if ( typeof row[i] === 'number' || ( row[i].match && $.trim(row[i]).match(/^-?\d+(\.\d+)?$/) && ! $.trim(row[i]).match(/^0\d+/) ) ) { cell = _createNode( rels, 'c', { attr: { t: 'n', r: cellId }, children: [ _createNode( rels, 'v', { text: row[i] } ) ] } ); } else { // Replace non standard characters for text output var text = ! row[i].replace ? row[i] : row[i] .replace(/&(?!amp;)/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, ''); cell = _createNode( rels, 'c', { attr: { t: 'inlineStr', r: cellId }, children:{ row: _createNode( rels, 'is', { children: { row: _createNode( rels, 't', { text: text } ) } } ) } } ); } rowNode.appendChild( cell ); } relsGet.appendChild(rowNode); rowPos++; }; $( 'sheets sheet', xlsx.xl['workbook.xml'] ).attr( 'name', _sheetname( config ) ); if ( config.customizeData ) { config.customizeData( data ); } if ( config.header ) { addRow( data.header, rowPos ); $('row c', rels).attr( 's', '2' ); // bold } for ( var n=0, ie=data.body.length ; n<ie ; n++ ) { addRow( data.body[n], rowPos ); } if ( config.footer && data.footer ) { addRow( data.footer, rowPos); $('row:last c', rels).attr( 's', '2' ); // bold } // Set column widths var cols = _createNode( rels, 'cols' ); $('worksheet', rels).prepend( cols ); for ( var i=0, ien=data.header.length ; i<ien ; i++ ) { cols.appendChild( _createNode( rels, 'col', { attr: { min: i+1, max: i+1, width: _excelColWidth( data, i ), customWidth: 1 } } ) ); } // Let the developer customise the document if they want to if ( config.customize ) { config.customize( xlsx ); } var zip = new jsZip(); var zipConfig = { type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }; _addToZip( zip, xlsx ); if ( zip.generateAsync ) { // JSZip 3+ zip .generateAsync( zipConfig ) .then( function ( blob ) { _saveAs( blob, _filename( config ) ); } ); } else { // JSZip 2.5 _saveAs( zip.generate( zipConfig ), _filename( config ) ); } }, filename: '*', extension: '.xlsx', exportOptions: {}, header: true, footer: false }; // // PDF export - using pdfMake - http://pdfmake.org // DataTable.ext.buttons.pdfHtml5 = { className: 'buttons-pdf buttons-html5', available: function () { return window.FileReader !== undefined && pdfMake; }, text: function ( dt ) { return dt.i18n( 'buttons.pdf', 'PDF' ); }, action: function ( e, dt, button, config ) { var newLine = _newLine( config ); var data = dt.buttons.exportData( config.exportOptions ); var rows = []; if ( config.header ) { rows.push( $.map( data.header, function ( d ) { return { text: typeof d === 'string' ? d : d+'', style: 'tableHeader' }; } ) ); } for ( var i=0, ien=data.body.length ; i<ien ; i++ ) { rows.push( $.map( data.body[i], function ( d ) { return { text: typeof d === 'string' ? d : d+'', style: i % 2 ? 'tableBodyEven' : 'tableBodyOdd' }; } ) ); } if ( config.footer && data.footer) { rows.push( $.map( data.footer, function ( d ) { return { text: typeof d === 'string' ? d : d+'', style: 'tableFooter' }; } ) ); } var doc = { pageSize: config.pageSize, pageOrientation: config.orientation, content: [ { table: { headerRows: 1, body: rows }, layout: 'noBorders' } ], styles: { tableHeader: { bold: true, fontSize: 11, color: 'white', fillColor: '#2d4154', alignment: 'center' }, tableBodyEven: {}, tableBodyOdd: { fillColor: '#f3f3f3' }, tableFooter: { bold: true, fontSize: 11, color: 'white', fillColor: '#2d4154' }, title: { alignment: 'center', fontSize: 15 }, message: {} }, defaultStyle: { fontSize: 10 } }; if ( config.message ) { doc.content.unshift( { text: config.message, style: 'message', margin: [ 0, 0, 0, 12 ] } ); } if ( config.title ) { doc.content.unshift( { text: _title( config, false ), style: 'title', margin: [ 0, 0, 0, 12 ] } ); } if ( config.customize ) { config.customize( doc, config ); } var pdf = pdfMake.createPdf( doc ); if ( config.download === 'open' && ! _isSafari() ) { pdf.open(); } else { pdf.getBuffer( function (buffer) { var blob = new Blob( [buffer], {type:'application/pdf'} ); _saveAs( blob, _filename( config ) ); } ); } }, title: '*', filename: '*', extension: '.pdf', exportOptions: {}, orientation: 'portrait', pageSize: 'A4', header: true, footer: false, message: null, customize: null, download: 'download' }; return DataTable.Buttons; }));
/*! * FileInput Ukrainian Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * @author CyanoFresh <cyanofresh@gmail.com> * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['uk'] = { fileSingle: 'файл', filePlural: 'файли', browseLabel: 'Обрати &hellip;', removeLabel: 'Видалити', removeTitle: 'Видалити вибрані файли', cancelLabel: 'Скасувати', cancelTitle: 'Скасувати поточне відвантаження', pauseLabel: 'Призупинити', pauseTitle: 'Призупинити поточне відвантаження', uploadLabel: 'Відвантажити', uploadTitle: 'Відвантажити обрані файли', msgNo: 'Немає', msgNoFilesSelected: '', msgPaused: 'Призупинено', msgCancelled: 'Скасовано', msgPlaceholder: 'Оберіть {files} ...', msgZoomModalHeading: 'Детальний перегляд', msgFileRequired: 'Ви повинні обрати файл для завантаження.', msgSizeTooSmall: 'Файл "{name}" (<b>{size} KB</b>) занадто малий і повинен бути більший, ніж <b>{minSize} KB</b>.', msgSizeTooLarge: 'Файл "{name}" (<b>{size} KB</b>) перевищує максимальний розмір <b>{maxSize} KB</b>.', msgFilesTooLess: 'Ви повинні обрати як мінімум <b>{n}</b> {files} для відвантаження.', msgFilesTooMany: 'Кількість обраних файлів <b>({n})</b> перевищує максимально допустиму кількість <b>{m}</b>.', msgTotalFilesTooMany: 'Ви можете відвантажити максимум <b>{m}</b> файл(ів) (<b>{n}</b> файл(ів) обрано).', msgFileNotFound: 'Файл "{name}" не знайдено!', msgFileSecured: 'Обмеження безпеки перешкоджають читанню файла "{name}".', msgFileNotReadable: 'Файл "{name}" неможливо прочитати.', msgFilePreviewAborted: 'Перегляд скасований для файла "{name}".', msgFilePreviewError: 'Сталася помилка під час читання файла "{name}".', msgInvalidFileName: 'Недійсні чи непідтримувані символи в імені файлу "{name}".', msgInvalidFileType: 'Заборонений тип файла для "{name}". Тільки "{types}" дозволені.', msgInvalidFileExtension: 'Заборонене розширення для файла "{name}". Тільки "{extensions}" дозволені.', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: 'Вивантаження файлу перервано', msgUploadThreshold: 'Обробка &hellip;', msgUploadBegin: 'Ініціалізація &hellip;', msgUploadEnd: 'Готово', msgUploadResume: 'Продовжити відвантаження &hellip;', msgUploadEmpty: 'Немає доступних даних для відвантаження.', msgUploadError: 'Помилка відвантаження', msgDeleteError: 'Помилка видалення', msgProgressError: 'Помилка', msgValidationError: 'Помилка перевірки', msgLoading: 'Відвантаження файла {index} із {files} &hellip;', msgProgress: 'Відвантаження файла {index} із {files} - {name} - {percent}% завершено.', msgSelected: '{n} {files} обрано', msgProcessing: 'Processing ...', msgFoldersNotAllowed: 'Дозволено перетягувати тільки файли! Пропущено {n} тек.', msgImageWidthSmall: 'Ширина зображення "{name}" повинна бути не менше {size} px.', msgImageHeightSmall: 'Висота зображення "{name}" повинна бути не менше {size} px.', msgImageWidthLarge: 'Ширина зображення "{name}" не може перевищувати {size} px.', msgImageHeightLarge: 'Висота зображення "{name}" не може перевищувати {size} px.', msgImageResizeError: 'Не вдалося отримати розміри зображення, щоб змінити розмір.', msgImageResizeException: 'Помилка при зміні розміру зображення.<pre>{errors}</pre>', msgAjaxError: 'Щось не так з операцією {operation}. Будь ласка, спробуйте пізніше!', msgAjaxProgressError: 'помилка {operation}', msgDuplicateFile: 'Файл "{name}" з розміром "{size} KB" вже був обраний раніше. Пропуск повторюваного вибору.', msgResumableUploadRetriesExceeded: 'Відвантаження перерване після <b>{max}</b> спроб для файлу <b>{file}</b>! Інформація про помилку: <pre>{error}</pre>', msgPendingTime: '{time} залишилося', msgCalculatingTime: 'розрахунок часу, який залишився', ajaxOperations: { deleteThumb: 'видалення файла', uploadThumb: 'відвантаження файла', uploadBatch: 'пакетне відвантаження файлів', uploadExtra: 'відвантаження даних з форми' }, dropZoneTitle: 'Перетягніть файли сюди &hellip;', dropZoneClickTitle: '<br>(або натисніть та оберіть {files})', fileActionSettings: { removeTitle: 'Видалити файл', uploadTitle: 'Відвантажити файл', uploadRetryTitle: 'Повторити відвантаження', downloadTitle: 'Завантажити файл', zoomTitle: 'Подивитися деталі', dragTitle: 'Перенести / Переставити', indicatorNewTitle: 'Ще не відвантажено', indicatorSuccessTitle: 'Відвантажено', indicatorErrorTitle: 'Помилка при відвантаженні', indicatorPausedTitle: 'Відвантаження призупинено', indicatorLoadingTitle: 'Завантаження &hellip;' }, previewZoomButtonTitles: { prev: 'Переглянути попередній файл', next: 'Переглянути наступний файл', toggleheader: 'Перемкнути заголовок', fullscreen: 'Перемкнути повноекранний режим', borderless: 'Перемкнути режим без полів', close: 'Закрити детальний перегляд' } }; })(window.jQuery);
import Ember from 'ember'; export default (Ember.Service || Ember.Object).extend({ token: null, getToken: function(billingInfo) { let self = this; return new Ember.RSVP.Promise(function(resolve, reject) { recurly.token(billingInfo, function(err, token) { if(err) { reject(err); } else { self.set('token', token); resolve(token); } }); }); }, getBankInfo: function(routingNumber) { let lookupData = { routingNumber: routingNumber.toString() } return new Ember.RSVP.Promise(function(resolve, reject) { recurly.bankAccount.bankInfo(lookupData, function(err, bankInfo) { if(err) { reject(err); } else { resolve(bankInfo) } }); }); }, payPal: function(opts) { let self = this; return new Ember.RSVP.Promise(function(resolve, reject) { recurly.paypal(opts, function(err, token) { if(err) { reject(err); } else { self.set('token', token); resolve(token); } }); }); } });
#!/usr/bin/env node 'use strict' var killport = require('../lib') var option = require('../lib/cli/parse').parse(process.argv) if (option.args.length === 0) option.help() killport(option)
function User () { } User.prototype.get = function() { // body... }; User.prototype.update = function() { // body... }; // fsdk:start(admin) User.prototype.delete = function(first_argument) { // body... }; // fsdk:end module.exports = User;
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.appendChild(g);return function(h){g.innerHTML='&shy;<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document);/*! Picturefill - Responsive Images that work today. (and mimic the proposed Picture element with span elements). Author: Scott Jehl, Filament Group, 2012 | License: MIT/GPLv2 */ (function( w ){ // Enable strict mode "use strict"; w.picturefill = function() { var ps = w.document.getElementsByTagName( "span" ); // Loop the pictures for( var i = 0, il = ps.length; i < il; i++ ){ if( ps[ i ].getAttribute( "data-picture" ) !== null ){ var sources = ps[ i ].getElementsByTagName( "span" ), matches = []; // See if which sources match for( var j = 0, jl = sources.length; j < jl; j++ ){ var media = sources[ j ].getAttribute( "data-media" ); // if there's no media specified, OR w.matchMedia is supported if( !media || ( w.matchMedia && w.matchMedia( media ).matches ) ){ matches.push( sources[ j ] ); } } // Find any existing img element in the picture element var picImg = ps[ i ].getElementsByTagName( "img" )[ 0 ]; if( matches.length ){ var matchedEl = matches.pop(); if( !picImg || picImg.parentNode.nodeName === "NOSCRIPT" ){ picImg = w.document.createElement( "img" ); var alt = ps[ i ].getAttribute( "data-alt" ); if (alt !== null) { picImg.alt = alt; } } else if( matchedEl === picImg.parentNode ){ // Skip further actions if the correct image is already in place continue; } picImg.src = matchedEl.getAttribute( "data-src" ); matchedEl.appendChild( picImg ); picImg.removeAttribute("width"); picImg.removeAttribute("height"); } else if( picImg ){ picImg.parentNode.removeChild( picImg ); } } } }; // Run on resize and domready (w.load as a fallback) if( w.addEventListener ){ w.addEventListener( "resize", w.picturefill, false ); w.addEventListener( "DOMContentLoaded", function(){ w.picturefill(); // Run once only w.removeEventListener( "load", w.picturefill, false ); }, false ); w.addEventListener( "load", w.picturefill, false ); } else if( w.attachEvent ){ w.attachEvent( "onload", w.picturefill ); } }( this ));
'use strict'; var Ticker = cc._Ticker; var Time = cc.Time; var EditorEngine = cc.Class({ name: 'EditorEngine', extends: cc.Playable, ctor: function () { var useDefaultMainLoop = arguments[0]; /** * We should use this id to cancel ticker, otherwise if the engine stop and replay immediately, * last ticker will not cancel correctly. * * @property _requestId * @type {number} * @private */ this._requestId = -1; this._useDefaultMainLoop = useDefaultMainLoop; this._isInitializing = false; this._isInitialized = false; // current scene this._loadingScene = ''; this._bindedTick = (CC_EDITOR || useDefaultMainLoop) && this._tick.bind(this); //this._isLockingScene = false; /** * The maximum value the Time.deltaTime in edit mode. * @property maxDeltaTimeInEM * @type {Number} * @private */ this.maxDeltaTimeInEM = 1 / 30; /** * Is playing animation in edit mode. * @property animatingInEditMode * @type {Boolean} * @private */ this.animatingInEditMode = false; this._shouldRepaintInEM = false; this._forceRepaintId = -1; // attached nodes and components used in getInstanceById this.attachedObjsForEditor = {}; this._designWidth = 0; this._designHeight = 0; }, properties: { /** * @property {boolean} isInitialized - Indicates whether the engine instance is initialized. * @readOnly */ isInitialized: { get: function () { return this._isInitialized; } }, /** * @property {boolean} loadingScene * @readOnly */ loadingScene: { get: function () { return this._loadingScene; } }, /** * The interval(ms) every time the engine force to repaint the scene in edit mode. * If don't need, set this to 0. * @property forceRepaintIntervalInEM * @type {Number} * @private */ forceRepaintIntervalInEM: { default: 500, notify: CC_EDITOR && function () { if (this._forceRepaintId !== -1) { clearInterval(this._forceRepaintId); } if (this.forceRepaintIntervalInEM > 0) { var self = this; this._forceRepaintId = setInterval(function () { self.repaintInEditMode(); }, this.forceRepaintIntervalInEM); } } } }, // PUBLIC /** * Initialize the engine. This method will be called by boot.js or editor. * @method init * @param {object} options * @param {number} options.width * @param {number} options.height * @param {string} options.rawUrl * @param {Canvas} [options.canvas] * @param {initCallback} callback */ init: function (options, callback) { if (this._isInitializing) { cc.error('Editor Engine already initialized'); return; } this._isInitializing = true; //if (options.rawUrl) { // cc.url.rawUrl = cc.path._setEndWithSep(options.rawUrl, true, '/'); //} //Resources._resBundle.init(options.resBundle); var self = this; this.createGame(options, function (err) { self._isInitialized = true; self._isInitializing = false; callback(err); if (CC_EDITOR) { // start main loop for editor after initialized self._tickStart(); // start timer to force repaint the scene in edit mode //noinspection SillyAssignmentJS self.forceRepaintIntervalInEM = self.forceRepaintIntervalInEM; } }); }, createGame: function (options, callback) { var config = { 'width' : options.width, 'height' : options.height, 'showFPS' : false, 'frameRate' : 60, 'id' : options.id, 'renderMode' : cc.isEditor ? 2 : options.renderMode, // 0: auto, 1:Canvas, 2:Webgl 'registerSystemEvent' : ! cc.isEditor, 'jsList' : [], 'noCache' : true, }; cc.game.run(config, function () { if (CC_EDITOR) { cc.view.enableRetina(false); cc.game.canvas.style.imageRendering = 'pixelated'; cc.director.setClearColor(cc.color(0,0,0,0)); } cc.view.setDesignResolutionSize(options.designWidth, options.designHeight, cc.ResolutionPolicy.SHOW_ALL); cc.view.setCanvasSize(config.width, config.height); var scene = new cc.EScene(); cc.director.runScene(scene); cc.game.pause(); if (CC_EDITOR) { // set cocos canvas tabindex to -1 in edit mode cc.game.canvas.setAttribute('tabindex', -1); cc.game.canvas.style.backgroundColor = ''; if (cc.imeDispatcher._domInputControl) cc.imeDispatcher._domInputControl.setAttribute('tabindex', -1); } if (callback) { callback(); } }); }, playInEditor: function () { if (CC_EDITOR) { cc.inputManager.registerSystemEvent(cc.game.canvas); // reset cocos tabindex in playing mode cc.game.canvas.setAttribute('tabindex', 99); cc.game.canvas.style.backgroundColor = 'black'; if (cc.imeDispatcher._domInputControl) cc.imeDispatcher._domInputControl.setAttribute('tabindex', 2); } cc.director.resume(); }, /** * This method will be invoke only if useDefaultMainLoop is true. * @method tick * @param {number} deltaTime * @param {boolean} updateAnimate */ tick: function (deltaTime, updateAnimate) { cc.director.mainLoop(deltaTime, updateAnimate); }, /** * This method will be invoked in edit mode even if useDefaultMainLoop is false. * @method tickInEditMode * @param {number} deltaTime * @param {boolean} updateAnimate */ tickInEditMode: function (deltaTime, updateAnimate) { if (CC_EDITOR) { cc.director.mainLoop(deltaTime, updateAnimate); } }, repaintInEditMode: function () { if (CC_EDITOR && !this._isUpdating) { this._shouldRepaintInEM = true; } }, /** * Returns the node by id. * @method getInstanceById * @param {String} uuid * @return {cc.ENode} */ getInstanceById: function (uuid) { return this.attachedObjsForEditor[uuid] || null; }, getIntersectionList: function (rect) { var scene = cc.director.getScene(); var list = []; function deepQueryChildren (root, cb) { function traversal (node, cb) { var children = node.children; for (var i = 0; i<children.length; i++) { var child = children[i]; if (!cb( child )) break; traversal(child, cb); } } traversal(root, cb); } function testNodeWithSize (node, size) { if (size.width === 0 || size.height === 0) return false; var bounds = node.getWorldBounds(size); // if intersect aabb success, then try intersect obb if (rect.intersects(bounds)) { bounds = node.getWorldOrientedBounds(size); var polygon = new Editor.Polygon(bounds); if (Editor.Intersection.rectPolygon(rect, polygon)) { return true; } } return false; } deepQueryChildren(scene, function (child) { if (testNodeWithSize(child, child.getContentSize())) { list.push(child); return true; } var components = child._components; for (var i = 0, l = components.length; i < l; i++) { var component = components[i]; var size = component.localSize; if (testNodeWithSize(child, size)) { list.push(child); break; } } return true; }); return list; }, // set the user defined desigin resolution for current scene setDesignResolutionSize: function (width, height, resolutionPolicy) { this._designWidth = width; this._designHeight = height; this.emit('design-resolution-changed'); }, // returns the desigin resolution set before getDesignResolutionSize: function () { return cc.size(this._designWidth, this._designHeight); }, // OVERRIDE onError: function (error) { if (CC_EDITOR) { switch (error) { case 'already-playing': cc.warn('Fireball is already playing'); break; } } }, onResume: function () { if (CC_EDITOR) { cc.Object._clearDeferredDestroyTimer(); } cc.game.resume(); if ((CC_EDITOR || CC_TEST) && !this._useDefaultMainLoop) { this._tickStop(); } }, onPause: function () { // if (CC_EDITOR) { // editorCallback.onEnginePaused(); // } cc.game.pause(); if (CC_EDITOR) { // start tick for edit mode this._tickStart(); } }, onPlay: function () { if (CC_EDITOR && ! this._isPaused) { cc.Object._clearDeferredDestroyTimer(); } this.playInEditor(); this._shouldRepaintInEM = false; if (this._useDefaultMainLoop) { // reset timer for default main loop var now = Ticker.now(); Time._restart(now); // this._tickStart(); } else if (CC_EDITOR) { // dont tick in play mode this._tickStop(); } //if (CC_EDITOR) { // editorCallback.onEnginePlayed(false); //} }, onStop: function () { //CCObject._deferredDestroy(); cc.game.pause(); // reset states this._loadingScene = ''; // TODO: what if loading scene ? if (CC_EDITOR) { // start tick for edit mode this.repaintInEditMode(); this._tickStart(); } //if (CC_EDITOR) { // editorCallback.onEngineStopped(); //} }, // PRIVATE /** * @method _tick * @private */ _tick: function () { this._requestId = Ticker.requestAnimationFrame(this._bindedTick); var now = Ticker.now(); if (this._isUpdating || this._stepOnce) { // play mode //if (sceneLoadingQueue) { // return; //} Time._update(now, false, this._stepOnce ? 1 / 60 : 0); this._stepOnce = false; //if (this._scene) { this.tick(Time.deltaTime, true); //} } else if (CC_EDITOR) { // edit mode Time._update(now, false, this.maxDeltaTimeInEM); if (this._shouldRepaintInEM || this.animatingInEditMode) { this.tickInEditMode(Time.deltaTime, this.animatingInEditMode); this._shouldRepaintInEM = false; } } }, _tickStart: function () { if (this._requestId === -1) { this._tick(); } }, _tickStop: function () { if (this._requestId !== -1) { Ticker.cancelAnimationFrame(this._requestId); this._requestId = -1; } }, // reset engine state reset: function () { cc.game._prepared = false; cc.game._prepareCalled = false; cc.game._rendererInitialized = false; cc.textureCache._clear(); cc.loader.releaseAll(); // cc.shaderCache._programs = {}; // cc.Director.firstUseDirector = true; // cc.EGLView._instance = null; // reset gl state // cc._currentProjectionMatrix = -1; cc._vertexAttribPosition = false; cc._vertexAttribColor = false; cc._vertexAttribTexCoords = false; // if (cc.ENABLE_GL_STATE_CACHE) { // cc._currentShaderProgram = -1; // for (var i = 0; i < cc.MAX_ACTIVETEXTURE; i++) { // cc._currentBoundTexture[i] = -1; // } // cc._blendingSource = -1; // cc._blendingDest = -1; // cc._GLServerState = 0; // } } }); cc.engine = new EditorEngine(false); module.exports = EditorEngine;
const createReactClass = require('create-react-class'); const MyComponent = createReactClass({ displayName: 'MyComponent', mixins: [ { componentWillMount() { // componentWillMount }, componentDidMount() { // componentDidMount }, componentWillUpdate(nextProps, nextState) { // componentWillUpdate }, componentDidUpdate(prevProps, prevState) { // componentDidUpdate }, componentWillReceiveProps(nextProps) { // componentWillReceiveProps }, componentWillUnmount() { // componentWillUnmount }, }, ], componentWillMount() { // componentWillMount }, componentDidMount() { // componentDidMount }, componentWillUpdate(nextProps, nextState) { // componentWillUpdate }, componentDidUpdate(prevProps, prevState) { // componentDidUpdate }, componentWillReceiveProps(nextProps) { // componentWillReceiveProps }, componentWillUnmount() { // componentWillUnmount }, render() { // render }, });
$(function () { $('#container').highcharts('StockChart', { rangeSelector: { selected: 1 }, plotOptions: { line: { gapSize: 2 } }, series: [{ name: 'USD to EUR', data: usdeur }] }); });
import React, { Component, PropTypes } from 'react'; import _ from 'lodash'; import { DragLayer } from 'react-dnd'; import ItemTypes from '../constants/ItemTypes'; import Connection from './Connection'; import DumbConnection from './CustomDragLayer/DumbConnection'; import SVGComponent from './SVGComponent'; import * as CoordinateUtils from '../utils/coordinate'; import getEndingConnectionLocation from '../utils/getEndingConnectionLocation'; const layerStyles = { position: 'absolute', pointerEvents: 'none', zIndex: 100, left: 0, top: 0, width: '100%', height: '100%', }; function getItemStyles(props) { const { item, currentOffset, initialOffset, viewport } = props; const scaledScene = CoordinateUtils.transformSceneToViewport(item, viewport); const xDelta = currentOffset.x - initialOffset.x; const yDelta = currentOffset.y - initialOffset.y; return { position: 'absolute', left: scaledScene.x + xDelta, top: scaledScene.y + yDelta, }; } function getModifiedScene(props, id) { const { currentSourceOffset, initialSourceOffset, item, scenes, viewport } = props; const scaledScene = CoordinateUtils.transformSceneToViewport(scenes[id], viewport); if (id === item.id) { return { ...scaledScene, x: currentSourceOffset.x, y: currentSourceOffset.y, }; } else { return { ...scaledScene } } } class CustomDragLayer extends Component { static propTypes = { connections: PropTypes.object, currentOffset: PropTypes.shape({ x: PropTypes.number.isRequired, y: PropTypes.number.isRequired, }), currentSourceOffset: PropTypes.shape({ x: PropTypes.number.isRequired, y: PropTypes.number.isRequired }), initalOffset: PropTypes.shape({ x: PropTypes.number.isRequired, y: PropTypes.number.isRequired, }), initialSourceOffset: PropTypes.shape({ x: PropTypes.number.isRequired, y: PropTypes.number.isRequired }), isDragging: PropTypes.bool.isRequired, item: PropTypes.object, itemType: PropTypes.string, renderScene: PropTypes.func.isRequired, renderSceneHeader: PropTypes.func.isRequired, scenes: PropTypes.object, showConnections: PropTypes.bool.isRequired, viewport: PropTypes.object.isRequired, }; static defaultProps = { connections: {}, item: {}, itemType: "", scenes: {}, }; getEndingVertOffset = (connection, toScene) => { const connsEndingHere = _.sortBy(_.map(_.filter(this.props.connections, (conn, id) => { return conn.to === toScene.id; }), 'id')); return (1 / (connsEndingHere.length + 1)) * (connsEndingHere.indexOf(connection.id) + 1); } renderConnection(connection) { const { currentSourceOffset, initialSourceOffset, item, viewport } = this.props; const scaledConnection = CoordinateUtils.transformConnectionToViewport(connection, viewport) const fromScene = getModifiedScene(this.props, connection.from); const toScene = getModifiedScene(this.props, connection.to); const itemIsTarget = item.id === toScene.id; const xDelta = currentSourceOffset.x - initialSourceOffset.x; const yDelta = currentSourceOffset.y - initialSourceOffset.y; const startX = itemIsTarget ? scaledConnection.startX : scaledConnection.startX + xDelta; const startY = itemIsTarget ? scaledConnection.startY : scaledConnection.startY + yDelta; const endingVertOffset = this.getEndingVertOffset(scaledConnection, toScene); const endLocation = getEndingConnectionLocation(toScene, fromScene.x < toScene.x, endingVertOffset); return <DumbConnection key={connection.id} startX={startX} startY={startY} endX={endLocation.x} endY={endLocation.y} /> } renderNewConnectionBeingDragged = () => { const { currentOffset, initialOffset } = this.props; return ( <DumbConnection startX={initialOffset.x} startY={initialOffset.y} endX={currentOffset.x} endY={currentOffset.y} /> ); } renderExistingConnectionBeingDragged = (isStart) => { const { currentOffset, initialOffset, item, scenes, viewport } = this.props; const endScene = CoordinateUtils.transformSceneToViewport(scenes[item.to], viewport); const startingLoc = isStart ? currentOffset : {x: item.startX, y: item.startY} const endingVertOffset = this.getEndingVertOffset(item, endScene); const endingLoc = isStart ? getEndingConnectionLocation(endScene, initialOffset.x < endScene.x, endingVertOffset) : currentOffset; return ( <DumbConnection startX={startingLoc.x} startY={startingLoc.y} endX={endingLoc.x} endY={endingLoc.y} /> ); } render() { const { connections, currentSourceOffset, isDragging, initialSourceOffset, item, itemType, renderScene, renderSceneHeader, showConnections, viewport, } = this.props; if (!isDragging || !currentSourceOffset || !initialSourceOffset) { return null; } if(itemType === ItemTypes.NEW_CONNECTION) { return this.renderNewConnectionBeingDragged(); } else if (itemType === ItemTypes.CONNECTION_START) { return this.renderExistingConnectionBeingDragged(true); } else if (itemType === ItemTypes.CONNECTION_END) { return this.renderExistingConnectionBeingDragged(false); } const connectionsInMotion = _.filter(connections, (connection) => { return [connection.from, connection.to].includes(item.id); }); const itemStyle = getItemStyles(this.props); const renderData = {id: item.id, scale: viewport.scale}; return ( <div style={layerStyles}> <div style={itemStyle}> {renderSceneHeader(renderData)} {renderScene(renderData)} </div> {showConnections && Object.keys(connectionsInMotion) .map(key => this.renderConnection(connectionsInMotion[key])) } </div> ); } } export default DragLayer(monitor => ({ item: monitor.getItem(), itemType: monitor.getItemType(), initialOffset: monitor.getInitialClientOffset(), initialSourceOffset: monitor.getInitialSourceClientOffset(), currentOffset: monitor.getClientOffset(), currentSourceOffset: monitor.getSourceClientOffset(), isDragging: monitor.isDragging() }))(CustomDragLayer)
'use strict' const clc = require('cli-color') const colors = [196, 202, 208, 214, 220, 226, 190, 154, 118, 82, 46, 47, 48, 49, 50, 51, 45, 39, 33, 27, 21, 57, 93, 129, 165, 201] module.exports = i => clc.bgXterm(i === undefined ? 0 : colors[i % colors.length])(' ')
/** * Created by zhang on 16/5/10. */ //数据的封装 (function() { var n = "xianqiang" //这个外部是不能引用的 //函数当做类使用 function People(name) { this._name = name; } //添加方法 People.prototype.say = function() { alert("p-hello" + this._name) }; window.People = People; }()); // 这个地方执行了!!! (function(){ //就是这么来继承的 这只是其中一个方法 function Student(name) { this._name = name; } // 这个地方原来写成了 Student() 这是不能用括号的. 然而还没有提示 (ˉ▽ ̄~) 切~~ Student.prototype = new People(); var superSay = Student.prototype.say; Student.prototype.say = function() { //重写方法 superSay.call(this) alert("stu-hello" + this._name) }; window.Student = Student; }()); var s = new Student('zhangxianqiang'); //var p = new People('handabao') s.say();
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var punycode = require('../punycode/punycode'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a puny coded representation of "domain". // It only converts the part of the domain name that // has non ASCII characters. I.e. it dosent matter if // you call it with a domain that already is in ASCII. var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); Object.keys(this).forEach(function(k) { result[k] = this[k]; }, this); // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative Object.keys(relative).forEach(function(k) { if (k !== 'protocol') result[k] = relative[k]; }); //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { Object.keys(relative).forEach(function(k) { result[k] = relative[k]; }); result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last == '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especialy happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; function isString(arg) { return typeof arg === "string"; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; }
(function() { angular.module('app') .controller('CardsController', CardsController); CardsController.$inject = ['cardsService']; function CardsController(cardsService) { var vm = this; vm.cards = []; vm.shuffle = shuffle; vm.slices = []; init(); function shuffle() { vm.cards = cardsService.getShuffledCards(); slice(); } function init() { vm.cards = cardsService.getCards(); slice(); } function slice() { vm.slices=[ vm.cards.slice(0,8), vm.cards.slice(8,16), vm.cards.slice(16,24), vm.cards.slice(24)]; } } })();
import React from 'react'; import PropTypes from 'prop-types'; const TreeView = ({ children }) => ( <div className="TreeView" style={{ width: '180px' }}> {children} </div> ); TreeView.propTypes = { children: PropTypes.node }; TreeView.defaultProps = { children: [] }; export default TreeView;