code
stringlengths 2
1.05M
|
---|
var axios = require('axios')
module.exports = function (app) {
app.get('/context_all.jsonld', function (req, res) {
axios.get(app.API_URL + 'context_all.jsonld')
.then(function (response) {
res.type('application/ld+json')
res.status(200).send(JSON.stringify(response.data, null, 2))
})
.catch(function (response) {
res.type('application/ld+json')
res.status(500).send('{}')
})
return
})
// other routes..
}
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from '@angular/core';
import { SettingsService } from "../../shared/service/settings.service";
import { DataService } from "../../shared/service/data.service";
var SettingsComponent = (function () {
function SettingsComponent(settingsService, dataService) {
this.settingsService = settingsService;
this.dataService = dataService;
// Do stuff
}
SettingsComponent.prototype.save = function () {
this.settingsService.save();
this.dataService.getParameterNames();
};
return SettingsComponent;
}());
SettingsComponent = __decorate([
Component({
selector: 'my-home',
templateUrl: 'settings.component.html',
styleUrls: ['settings.component.scss']
}),
__metadata("design:paramtypes", [SettingsService, DataService])
], SettingsComponent);
export { SettingsComponent };
//# sourceMappingURL=settings.component.js.map |
'use strict';
import React from 'react-native'
import {
AppRegistry,
Component,
Navigator,
ToolbarAndroid,
View,
} from 'react-native';
import globalStyle, { colors } from './globalStyle';
class NavBar extends Component {
onClickBackToHome() {
this.props.navigator.push({
name: 'home',
sceneConfig: Navigator.SceneConfigs.FloatFromLeft,
});
}
getToolbarActions(route) {
const actionsByRoute = {
'home': [],
'boop-view': [{
title: 'Back',
show: 'always'
}],
}
if (actionsByRoute[route.name]) {
return actionsByRoute[route.name];
}
return [];
}
render() {
const { navigator } = this.props;
const currentRoute = navigator.getCurrentRoutes()[navigator.getCurrentRoutes().length - 1];
const toolbarActions = this.getToolbarActions(currentRoute);
return (
<ToolbarAndroid
style={globalStyle.toolbar}
title='boop'
titleColor={colors.darkTheme.text1}
actions={toolbarActions}
onActionSelected={this.onClickBackToHome.bind(this)}
/>
);
}
};
AppRegistry.registerComponent('NavBar', () => NavBar);
export default NavBar;
|
import React, { Component, PropTypes } from 'react';
import ItemTypes from './ItemTypes';
import { DragSource, DropTarget } from 'react-dnd';
import flow from 'lodash.flow';
function isNullOrUndefined(o) {
return o == null;
}
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: props.index,
originalIndex: props.index
};
},
endDrag(props, monitor) {
if (props.noDropOutside) {
const { id, index, originalIndex } = monitor.getItem();
const didDrop = monitor.didDrop();
if (!didDrop) {
props.moveCard(isNullOrUndefined(id) ? index : id, originalIndex);
}
}
if (props.endDrag) {
props.endDrag();
}
}
};
const cardTarget = {
hover(props, monitor) {
const { id: dragId, index: dragIndex } = monitor.getItem();
const { id: hoverId, index: hoverIndex } = props;
if (!isNullOrUndefined(dragId)) {
// use id
if (dragId !== hoverId) {
props.moveCard(dragId, hoverIndex);
}
} else {
// use index
if (dragIndex !== hoverIndex) {
props.moveCard(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
}
}
}
};
const propTypes = {
index: PropTypes.number.isRequired,
source: PropTypes.any.isRequired,
createItem: PropTypes.func.isRequired,
moveCard: PropTypes.func.isRequired,
endDrag: PropTypes.func,
isDragging: PropTypes.bool.isRequired,
connectDragSource: PropTypes.func.isRequired,
connectDropTarget: PropTypes.func.isRequired,
noDropOutside: PropTypes.bool
};
class DndCard extends Component {
render() {
const {
id,
index,
source,
createItem,
noDropOutside, // remove from restProps
moveCard, // remove from restProps
endDrag, // remove from restProps
isDragging,
connectDragSource,
connectDropTarget,
...restProps
} = this.props;
if (id === null) {
console.warn('Warning: `id` is null. Set to undefined to get better performance.');
}
const item = createItem(source, isDragging, index);
if (typeof item === 'undefined') {
console.warn('Warning: `createItem` returns undefined. It should return a React element or null.');
}
const finalProps = Object.keys(restProps).reduce((result, k) => {
const prop = restProps[k];
result[k] = typeof prop === 'function' ? prop(isDragging) : prop;
return result;
}, {});
return connectDragSource(connectDropTarget(
<div {...finalProps}>
{item}
</div>
));
}
}
DndCard.propTypes = propTypes;
export default flow(
DropTarget(ItemTypes.DND_CARD, cardTarget, connect => ({
connectDropTarget: connect.dropTarget()
})),
DragSource(ItemTypes.DND_CARD, cardSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}))
)(DndCard);
|
// @license
// Redistribution and use in source and binary forms ...
// Copyright 2012 Carnegie Mellon University. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Carnegie Mellon University.
//
// Author:
// Randy Sargent ([email protected])
"use strict";
var org;
org = org || {};
org.gigapan = org.gigapan || {};
org.gigapan.timelapse = org.gigapan.timelapse || {};
org.gigapan.timelapse.MercatorProjection = function(west, north, east, south, width, height) {
function rawProjectLat(lat) {
return Math.log((1 + Math.sin(lat * Math.PI / 180)) / Math.cos(lat * Math.PI / 180));
}
function rawUnprojectLat(y) {
return (2 * Math.atan(Math.exp(y)) - Math.PI / 2) * 180 / Math.PI;
}
function interpolate(x, fromLow, fromHigh, toLow, toHigh) {
return (x - fromLow) / (fromHigh - fromLow) * (toHigh - toLow) + toLow;
}
this.latlngToPoint = function(latlng) {
var x = interpolate(latlng.lng, west, east, 0, width);
var y = interpolate(rawProjectLat(latlng.lat), rawProjectLat(north), rawProjectLat(south), 0, height);
return {
"x": x,
"y": y
};
};
this.pointToLatlng = function(point) {
var lng = interpolate(point.x, 0, width, west, east);
var lat = rawUnprojectLat(interpolate(point.y, 0, height, rawProjectLat(north), rawProjectLat(south)));
return {
"lat": lat,
"lng": lng
};
};
};
|
describe('gridClassFactory', function() {
var gridClassFactory;
beforeEach(module('ui.grid.ie'));
beforeEach(inject(function(_gridClassFactory_) {
gridClassFactory = _gridClassFactory_;
}));
describe('createGrid', function() {
var grid;
beforeEach( function() {
grid = gridClassFactory.createGrid();
});
it('creates a grid with default properties', function() {
expect(grid).toBeDefined();
expect(grid.id).toBeDefined();
expect(grid.id).not.toBeNull();
expect(grid.options).toBeDefined();
});
});
describe('defaultColumnBuilder', function () {
var grid;
var testSetup = {};
beforeEach(inject(function($rootScope, $templateCache) {
testSetup.$rootScope = $rootScope;
testSetup.$templateCache = $templateCache;
testSetup.col = {};
testSetup.colDef = {};
testSetup.gridOptions = {};
}));
it('column builder with no filters and template has no placeholders', function() {
testSetup.$templateCache.put('ui-grid/uiGridHeaderCell', '<div>a sample header template with no custom_filters</div>');
testSetup.$templateCache.put('ui-grid/uiGridCell', '<div>a sample cell template with no custom_filters</div>');
testSetup.$templateCache.put('ui-grid/uiGridFooterCell', '<div>a sample footer template with no custom_filters</div>');
gridClassFactory.defaultColumnBuilder( testSetup.colDef, testSetup.col, testSetup.gridOptions );
expect(testSetup.col.providedHeaderCellTemplate).toEqual('ui-grid/uiGridHeaderCell');
expect(testSetup.col.providedCellTemplate).toEqual('ui-grid/uiGridCell');
expect(testSetup.col.providedFooterCellTemplate).toEqual('ui-grid/uiGridFooterCell');
testSetup.$rootScope.$digest();
expect(testSetup.col.headerCellTemplate).toEqual('<div>a sample header template with no custom_filters</div>');
expect(testSetup.col.cellTemplate).toEqual('<div>a sample cell template with no custom_filters</div>');
expect(testSetup.col.footerCellTemplate).toEqual('<div>a sample footer template with no custom_filters</div>');
});
it('column builder with no filters and template has placeholders', function() {
testSetup.$templateCache.put('ui-grid/uiGridHeaderCell', '<div>a sample header template with CUSTOM_FILTERS</div>');
testSetup.$templateCache.put('ui-grid/uiGridCell', '<div>a sample cell template with CUSTOM_FILTERS</div>');
testSetup.$templateCache.put('ui-grid/uiGridFooterCell', '<div>a sample footer template with CUSTOM_FILTERS</div>');
gridClassFactory.defaultColumnBuilder( testSetup.colDef, testSetup.col, testSetup.gridOptions );
expect(testSetup.col.providedHeaderCellTemplate).toEqual('ui-grid/uiGridHeaderCell');
expect(testSetup.col.providedCellTemplate).toEqual('ui-grid/uiGridCell');
expect(testSetup.col.providedFooterCellTemplate).toEqual('ui-grid/uiGridFooterCell');
testSetup.$rootScope.$digest();
expect(testSetup.col.headerCellTemplate).toEqual('<div>a sample header template with </div>');
expect(testSetup.col.cellTemplate).toEqual('<div>a sample cell template with </div>');
expect(testSetup.col.footerCellTemplate).toEqual('<div>a sample footer template with </div>');
});
it('column builder with filters and template has placeholders', function() {
testSetup.$templateCache.put('ui-grid/uiGridHeaderCell', '<div>a sample header template with CUSTOM_FILTERS</div>');
testSetup.$templateCache.put('ui-grid/uiGridCell', '<div>a sample cell template with CUSTOM_FILTERS</div>');
testSetup.$templateCache.put('ui-grid/uiGridFooterCell', '<div>a sample footer template with CUSTOM_FILTERS</div>');
testSetup.col.cellFilter = 'customCellFilter';
testSetup.col.headerCellFilter = 'customHeaderCellFilter';
testSetup.col.footerCellFilter = 'customFooterCellFilter';
gridClassFactory.defaultColumnBuilder( testSetup.colDef, testSetup.col, testSetup.gridOptions );
expect(testSetup.col.providedHeaderCellTemplate).toEqual('ui-grid/uiGridHeaderCell');
expect(testSetup.col.providedCellTemplate).toEqual('ui-grid/uiGridCell');
expect(testSetup.col.providedFooterCellTemplate).toEqual('ui-grid/uiGridFooterCell');
testSetup.$rootScope.$digest();
expect(testSetup.col.headerCellTemplate).toEqual('<div>a sample header template with |customHeaderCellFilter</div>');
expect(testSetup.col.cellTemplate).toEqual('<div>a sample cell template with |customCellFilter</div>');
expect(testSetup.col.footerCellTemplate).toEqual('<div>a sample footer template with |customFooterCellFilter</div>');
});
it('column builder with filters and template has no placeholders', function() {
testSetup.$templateCache.put('ui-grid/uiGridHeaderCell', '<div>a sample header template with custom_filters</div>');
testSetup.$templateCache.put('ui-grid/uiGridCell', '<div>a sample cell template with custom_filters</div>');
testSetup.$templateCache.put('ui-grid/uiGridFooterCell', '<div>a sample footer template with custom_filters</div>');
testSetup.col.cellFilter = 'customCellFilter';
testSetup.col.headerCellFilter = 'customHeaderCellFilter';
testSetup.col.footerCellFilter = 'customFooterCellFilter';
gridClassFactory.defaultColumnBuilder( testSetup.colDef, testSetup.col, testSetup.gridOptions );
expect(testSetup.col.providedHeaderCellTemplate).toEqual('ui-grid/uiGridHeaderCell');
expect(testSetup.col.providedCellTemplate).toEqual('ui-grid/uiGridCell');
expect(testSetup.col.providedFooterCellTemplate).toEqual('ui-grid/uiGridFooterCell');
// the code appears to rely on cellTemplate being undefined until properly retrieved (i.e. we cannot
// just push 'ui-grid/uiGridCell' into here, then later replace it with the template body)
expect(testSetup.col.cellTemplate).toEqual(undefined);
testSetup.$rootScope.$digest();
expect(testSetup.col.headerCellTemplate).toEqual('<div>a sample header template with custom_filters</div>');
expect(testSetup.col.cellTemplate).toEqual('<div>a sample cell template with custom_filters</div>');
expect(testSetup.col.footerCellTemplate).toEqual('<div>a sample footer template with custom_filters</div>');
});
it('column builder passes double dollars as parameters to the filters correctly', function() {
testSetup.$templateCache.put('ui-grid/uiGridHeaderCell', '<div>a sample header template with CUSTOM_FILTERS</div>');
testSetup.$templateCache.put('ui-grid/uiGridCell', '<div>a sample cell template with CUSTOM_FILTERS</div>');
testSetup.$templateCache.put('ui-grid/uiGridFooterCell', '<div>a sample footer template with CUSTOM_FILTERS</div>');
testSetup.col.cellFilter = 'customCellFilter:row.entity.$$internalValue';
testSetup.col.headerCellFilter = 'customHeaderCellFilter:row.entity.$$internalValue';
testSetup.col.footerCellFilter = 'customFooterCellFilter:row.entity.$$internalValue';
gridClassFactory.defaultColumnBuilder( testSetup.colDef, testSetup.col, testSetup.gridOptions );
expect(testSetup.col.providedHeaderCellTemplate).toEqual('ui-grid/uiGridHeaderCell');
expect(testSetup.col.providedCellTemplate).toEqual('ui-grid/uiGridCell');
expect(testSetup.col.providedFooterCellTemplate).toEqual('ui-grid/uiGridFooterCell');
testSetup.$rootScope.$digest();
expect(testSetup.col.headerCellTemplate).toEqual('<div>a sample header template with |customHeaderCellFilter:row.entity.$$internalValue</div>');
expect(testSetup.col.cellTemplate).toEqual('<div>a sample cell template with |customCellFilter:row.entity.$$internalValue</div>');
expect(testSetup.col.footerCellTemplate).toEqual('<div>a sample footer template with |customFooterCellFilter:row.entity.$$internalValue</div>');
});
});
}); |
var searchData=
[
['setdebugflags',['setDebugFlags',['../dwarfDbgDebugInfo_8c.html#ab42dd1f5e0f83cb14eed0902aa036a95',1,'dwarfDbgDebugInfo.c']]],
['showchildren',['showChildren',['../dwarfDbgDieInfo_8c.html#a7e7301f838fc67cbb4555c6c250c2dc0',1,'dwarfDbgDieInfo.c']]],
['showcontents',['showContents',['../dwarfDbgLocationInfo_8c.html#af177f930f13d0122065173a8bfbd0317',1,'dwarfDbgLocationInfo.c']]],
['showdieentries',['showDieEntries',['../dwarfDbgDieInfo_8c.html#a01c1ab81a588e24d9d82a9aa8ace1a09',1,'dwarfDbgDieInfo.c']]],
['showsiblings',['showSiblings',['../dwarfDbgDieInfo_8c.html#a6d210b422753428ebf1edc2694a5563f',1,'dwarfDbgDieInfo.c']]]
];
|
import 'reflect-metadata';
import 'rxjs/Rx';
import 'zone.js';
import AppComponent from './components/AppComponent.js';
import { bootstrap } from 'angular2/platform/browser';
bootstrap(AppComponent);
|
/**
* Returns an Express Router with bindings for the Admin UI static resources,
* i.e files, less and browserified scripts.
*
* Should be included before other middleware (e.g. session management,
* logging, etc) for reduced overhead.
*/
var browserify = require('../middleware/browserify');
var express = require('express');
var less = require('less-middleware');
var path = require('path');
module.exports = function createStaticRouter (keystone) {
var router = express.Router();
/* Prepare browserify bundles */
var bundles = {
fields: browserify('utils/fields.js', 'FieldTypes'),
signin: browserify('Signin/index.js'),
index: browserify('index.js'),
};
// prebuild static resources on the next tick
// improves first-request performance
process.nextTick(function () {
bundles.fields.build();
bundles.signin.build();
bundles.index.build();
});
/* Prepare LESS options */
var elementalPath = path.join(path.dirname(require.resolve('elemental')), '..');
var reactSelectPath = path.join(path.dirname(require.resolve('react-select')), '..');
var customStylesPath = keystone.getPath('adminui custom styles') || '';
var lessOptions = {
render: {
modifyVars: {
elementalPath: JSON.stringify(elementalPath),
reactSelectPath: JSON.stringify(reactSelectPath),
customStylesPath: JSON.stringify(customStylesPath),
adminPath: JSON.stringify(keystone.get('admin path')),
},
},
};
/* Configure router */
router.use('/styles', less(path.resolve(__dirname + '/../../public/styles'), lessOptions));
router.use('/styles/fonts', express.static(path.resolve(__dirname + '/../../public/js/lib/tinymce/skins/keystone/fonts')));
router.get('/js/fields.js', bundles.fields.serve);
router.get('/js/signin.js', bundles.signin.serve);
router.get('/js/index.js', bundles.index.serve);
router.use(express.static(path.resolve(__dirname + '/../../public')));
return router;
};
|
'use strict'
const isPlainObject = require('lodash.isplainobject')
const getPath = require('lodash.get')
const StaticComponent = require('./StaticComponent')
const DynamicComponent = require('./DynamicComponent')
const LinkedComponent = require('./LinkedComponent')
const ContainerComponent = require('./ContainerComponent')
const MissingComponent = require('./MissingComponent')
module.exports = {
coerce,
value: makeStaticComponent,
factory: makeDynamicComponent,
link: makeLinkedComponent,
container: makeContainerComponent,
missing: makeMissingComponent
}
function makeStaticComponent(value) {
return new StaticComponent(value)
}
makeDynamicComponent.predefinedFrom = PredefinedComponentBuilder
function makeDynamicComponent(factory, context) {
return new DynamicComponent(factory, context)
}
function PredefinedComponentBuilder(implementations) {
return function PredefinedComponent(implementationName, context) {
let implementation = getPath(implementations, implementationName)
return makeDynamicComponent(implementation, context)
}
}
makeLinkedComponent.boundTo = BoundLinkBuilder
function makeLinkedComponent(context, targetKey) {
return new LinkedComponent(context, targetKey)
}
function BoundLinkBuilder(container) {
return function BoundLink(targetKey) {
return makeLinkedComponent(container, targetKey)
}
}
function makeContainerComponent(container) {
return new ContainerComponent(container)
}
function makeMissingComponent(key) {
return new MissingComponent(key)
}
function coerce(component) {
switch (true) {
case _isComponent(component):
return component
case isPlainObject(component):
return makeContainerComponent(component)
default:
return makeStaticComponent(component)
}
}
function _isComponent(component) {
return component && component.instantiate && component.unwrap && true
}
|
'use strict';
var program = require('commander');
var Q = require('q');
var fs = require('fs');
var resolve = require('path').resolve;
var stat = Q.denodeify(fs.stat);
var readFile = Q.denodeify(fs.readFile);
var writeFile = Q.denodeify(fs.writeFile);
var assign = require('./util/assign');
program
.option('--get', 'Gets configuration property')
.option('--set', 'Sets a configuration value: Ex: "hello=world". If no value is set, then the property is unset from the config file');
program.parse(process.argv);
var args = program.args;
var opts = program.opts();
// Remove options that are not set in the same order as described above
var selectedOpt = Object.keys(opts).reduce(function (arr, next) {
if (opts[next]) {
arr.push(next);
}
return arr;
}, [])[0];
if (!args.length) {
process.exit(1);
}
args = [];
args.push(program.args[0].replace(/=.*$/, ''));
args.push(program.args[0].replace(new RegExp(args[0] + '=?'), ''));
if (args[1] === '') {
args[1] = undefined;
}
stat(resolve('./fxc.json'))
.then(function (stat) {
if (stat.isFile()) {
return readFile(resolve('./fxc.json'));
}
})
.catch(function () {
return Q.when(null);
})
.then(function (fileContent) {
fileContent = assign({}, fileContent && JSON.parse(fileContent.toString('utf8')));
if (selectedOpt === 'get') {
return fileContent[args[0]];
}
if (typeof args[1] !== 'undefined') {
fileContent[args[0]] = args[1];
} else {
delete fileContent[args[0]];
}
return writeFile(resolve('./fxc.json'), JSON.stringify(fileContent));
})
.then(function (output) {
if (output) {
console.log(output);
} else {
console.log('Property "' + args[0] + '" ' + (args[1] ? ('set to "' + args[1] + '"') : 'removed'));
}
process.exit();
});
|
import qambi, {
getMIDIInputs
} from 'qambi'
document.addEventListener('DOMContentLoaded', function(){
console.time('loading and parsing assets took')
qambi.init({
song: {
type: 'Song',
url: '../data/minute_waltz.mid'
},
piano: {
type: 'Instrument',
url: '../../instruments/heartbeat/city-piano-light-concat.json'
}
})
.then(main)
})
function main(data){
console.timeEnd('loading and parsing assets took')
let {song, piano} = data
song.getTracks().forEach(track => {
track.setInstrument(piano)
track.monitor = true
track.connectMIDIInputs(...getMIDIInputs())
})
let btnPlay = document.getElementById('play')
let btnPause = document.getElementById('pause')
let btnStop = document.getElementById('stop')
let divLoading = document.getElementById('loading')
divLoading.innerHTML = ''
btnPlay.disabled = false
btnPause.disabled = false
btnStop.disabled = false
btnPlay.addEventListener('click', function(){
song.play()
})
btnPause.addEventListener('click', function(){
song.pause()
})
btnStop.addEventListener('click', function(){
song.stop()
})
}
|
export default function widget(widget=null, action) {
switch (action.type) {
case 'widget.edit':
return action.widget;
case 'widget.edit.close':
return null;
default:
return widget;
}
}
|
'use strict';
var MemoryStats = require('../../src/models/memory_stats')
, SQliteAdapter = require('../../src/models/sqlite_adapter')
, chai = require('chai')
, expect = chai.expect
, chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
describe('MemoryStats', function() {
describe('.constructor', function() {
it('returns an instantiated memory stats and its schema attributes', function() {
expect(MemoryStats().schemaAttrs).to.include.members(['container_name', 'timestamp_day']);
});
it('returns an instantiated memory stats and its table name', function() {
expect(MemoryStats().tableName).to.eql('memory_stats');
});
});
after(function() {
return SQliteAdapter.deleteDB()
.then(null)
.catch(function(err) {
console.log(err.stack);
});
});
});
|
module.exports = {
resolve: {
alias: {
'vue': 'vue/dist/vue.js'
}
}
}
|
/**
* Created by kalle on 12.5.2014.
*/
/// <reference path="jquery.d.ts" />
var TheBall;
(function (TheBall) {
(function (Interface) {
(function (UI) {
var ResourceLocatedObject = (function () {
function ResourceLocatedObject(isJSONUrl, urlKey, onUpdate, boundToElements, boundToObjects, dataSourceObjects) {
this.isJSONUrl = isJSONUrl;
this.urlKey = urlKey;
this.onUpdate = onUpdate;
this.boundToElements = boundToElements;
this.boundToObjects = boundToObjects;
this.dataSourceObjects = dataSourceObjects;
// Initialize to empty arrays if not given
this.onUpdate = onUpdate || [];
this.boundToElements = boundToElements || [];
this.boundToObjects = boundToObjects || [];
this.dataSourceObjects = dataSourceObjects || [];
}
return ResourceLocatedObject;
})();
UI.ResourceLocatedObject = ResourceLocatedObject;
var UpdatingDataGetter = (function () {
function UpdatingDataGetter() {
this.TrackedURLDictionary = {};
}
UpdatingDataGetter.prototype.registerSourceUrls = function (sourceUrls) {
var _this = this;
sourceUrls.forEach(function (sourceUrl) {
if (!_this.TrackedURLDictionary[sourceUrl]) {
var sourceIsJson = _this.isJSONUrl(sourceUrl);
if (!sourceIsJson)
throw "Local source URL needs to be defined before using as source";
var source = new ResourceLocatedObject(sourceIsJson, sourceUrl);
_this.TrackedURLDictionary[sourceUrl] = source;
}
});
};
UpdatingDataGetter.prototype.isJSONUrl = function (url) {
return url.indexOf("/") != -1;
};
UpdatingDataGetter.prototype.getOrRegisterUrl = function (url) {
var rlObj = this.TrackedURLDictionary[url];
if (!rlObj) {
var sourceIsJson = this.isJSONUrl(url);
rlObj = new ResourceLocatedObject(sourceIsJson, url);
this.TrackedURLDictionary[url] = rlObj;
}
return rlObj;
};
UpdatingDataGetter.prototype.RegisterAndBindDataToElements = function (boundToElements, url, onUpdate, sourceUrls) {
var _this = this;
if (sourceUrls)
this.registerSourceUrls(sourceUrls);
var rlObj = this.getOrRegisterUrl(url);
if (sourceUrls) {
rlObj.dataSourceObjects = sourceUrls.map(function (sourceUrl) {
return _this.TrackedURLDictionary[sourceUrl];
});
}
};
UpdatingDataGetter.prototype.RegisterDataURL = function (url, onUpdate, sourceUrls) {
if (sourceUrls)
this.registerSourceUrls(sourceUrls);
var rlObj = this.getOrRegisterUrl(url);
};
UpdatingDataGetter.prototype.UnregisterDataUrl = function (url) {
if (this.TrackedURLDictionary[url])
delete this.TrackedURLDictionary[url];
};
UpdatingDataGetter.prototype.GetData = function (url, callback) {
var rlObj = this.TrackedURLDictionary[url];
if (!rlObj)
throw "Data URL needs to be registered before GetData: " + url;
if (rlObj.isJSONUrl) {
$.getJSON(url, function (content) {
callback(content);
});
}
};
return UpdatingDataGetter;
})();
UI.UpdatingDataGetter = UpdatingDataGetter;
})(Interface.UI || (Interface.UI = {}));
var UI = Interface.UI;
})(TheBall.Interface || (TheBall.Interface = {}));
var Interface = TheBall.Interface;
})(TheBall || (TheBall = {}));
//# sourceMappingURL=UpdatingDataGetter.js.map
|
module.exports = { prefix: 'far', iconName: 'road', icon: [576, 512, [], "f018", "M246.7 435.2l7.2-104c.4-6.3 5.7-11.2 12-11.2h44.9c6.3 0 11.5 4.9 12 11.2l7.2 104c.5 6.9-5 12.8-12 12.8h-59.3c-6.9 0-12.4-5.9-12-12.8zM267.6 288h41.5c5.8 0 10.4-4.9 10-10.7l-5.2-76c-.4-5.2-4.7-9.3-10-9.3h-31c-5.3 0-9.6 4.1-10 9.3l-5.2 76c-.5 5.8 4.1 10.7 9.9 10.7zm6.2-120H303c4.6 0 8.3-3.9 8-8.6l-2.8-40c-.3-4.2-3.8-7.4-8-7.4h-23.7c-4.2 0-7.7 3.3-8 7.4l-2.8 40c-.2 4.7 3.4 8.6 8.1 8.6zm2.8-72h23.5c3.5 0 6.2-2.9 6-6.4l-1.4-20c-.2-3.1-2.8-5.6-6-5.6H278c-3.2 0-5.8 2.4-6 5.6l-1.4 20c-.2 3.5 2.5 6.4 6 6.4zM12 448h65c5.4 0 10.2-3.6 11.6-8.9l99.5-367.6c1-3.8-1.8-7.6-5.8-7.6h-28.1c-2.4 0-4.6 1.5-5.6 3.7L.9 431.5C-2.3 439.4 3.5 448 12 448zm487.7 0h65c8.5 0 14.3-8.6 11.1-16.5L428 67.7c-.9-2.3-3.1-3.7-5.6-3.7h-28.1c-4 0-6.8 3.8-5.8 7.6L488 439.2c1.5 5.2 6.3 8.8 11.7 8.8z"] }; |
'use strict';
module.exports = function(config) {
config.set({
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-coverage'
],
preprocessors: {
'src/**/*.js': ['coverage']
},
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'lcov',
dir: 'reports',
subdir: 'coverage'
},
colors: true
});
};
|
import traverse from "../lib";
import assert from "assert";
import { parse } from "babylon";
import * as t from "babel-types";
function getPath(code) {
const ast = parse(code, { plugins: ["flow", "asyncGenerators"] });
let path;
traverse(ast, {
Program: function (_path) {
path = _path;
_path.stop();
},
});
return path;
}
describe("inference", function () {
describe("baseTypeStrictlyMatches", function () {
it("it should work with null", function () {
const path = getPath("var x = null; x === null").get("body")[1].get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(strictMatch, "null should be equal to null");
});
it("it should work with numbers", function () {
const path = getPath("var x = 1; x === 2").get("body")[1].get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(strictMatch, "number should be equal to number");
});
it("it should bail when type changes", function () {
const path = getPath("var x = 1; if (foo) x = null;else x = 3; x === 2")
.get("body")[2].get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(!strictMatch, "type might change in if statement");
});
it("it should differentiate between null and undefined", function () {
const path = getPath("var x; x === null").get("body")[1].get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
assert.ok(!strictMatch, "null should not match undefined");
});
});
describe("getTypeAnnotation", function () {
it("should infer from type cast", function () {
const path = getPath("(x: number)").get("body")[0].get("expression");
assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number");
});
it("should infer string from template literal", function () {
const path = getPath("`hey`").get("body")[0].get("expression");
assert.ok(t.isStringTypeAnnotation(path.getTypeAnnotation()), "should be string");
});
it("should infer number from +x", function () {
const path = getPath("+x").get("body")[0].get("expression");
assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number");
});
it("should infer T from new T", function () {
const path = getPath("new T").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "T", "should be T");
});
it("should infer number from ++x", function () {
const path = getPath("++x").get("body")[0].get("expression");
assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number");
});
it("should infer number from --x", function () {
const path = getPath("--x").get("body")[0].get("expression");
assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number");
});
it("should infer void from void x", function () {
const path = getPath("void x").get("body")[0].get("expression");
assert.ok(t.isVoidTypeAnnotation(path.getTypeAnnotation()), "should be void");
});
it("should infer string from typeof x", function () {
const path = getPath("typeof x").get("body")[0].get("expression");
assert.ok(t.isStringTypeAnnotation(path.getTypeAnnotation()), "should be string");
});
it("should infer boolean from !x", function () {
const path = getPath("!x").get("body")[0].get("expression");
assert.ok(t.isBooleanTypeAnnotation(path.getTypeAnnotation()), "should be boolean");
});
it("should infer type of sequence expression", function () {
const path = getPath("a,1").get("body")[0].get("expression");
assert.ok(t.isNumberTypeAnnotation(path.getTypeAnnotation()), "should be number");
});
it("should infer type of logical expression", function () {
const path = getPath("'a' && 1").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isUnionTypeAnnotation(type), "should be a union");
assert.ok(t.isStringTypeAnnotation(type.types[0]), "first type in union should be string");
assert.ok(t.isNumberTypeAnnotation(type.types[1]), "second type in union should be number");
});
it("should infer type of conditional expression", function () {
const path = getPath("q ? true : 0").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isUnionTypeAnnotation(type), "should be a union");
assert.ok(t.isBooleanTypeAnnotation(type.types[0]), "first type in union should be boolean");
assert.ok(t.isNumberTypeAnnotation(type.types[1]), "second type in union should be number");
});
it("should infer RegExp from RegExp literal", function () {
const path = getPath("/.+/").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", "should be RegExp");
});
it("should infer Object from object expression", function () {
const path = getPath("({ a: 5 })").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Object", "should be Object");
});
it("should infer Array from array expression", function () {
const path = getPath("[ 5 ]").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Array", "should be Array");
});
it("should infer Function from function", function () {
const path = getPath("(function (): string {})").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Function", "should be Function");
});
it("should infer call return type using function", function () {
const path = getPath("(function (): string {})()").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isStringTypeAnnotation(type), "should be string");
});
it("should infer call return type using async function", function () {
const path = getPath("(async function (): string {})()").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "Promise", "should be Promise");
});
it("should infer call return type using async generator function", function () {
const path = getPath("(async function * (): string {})()").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "AsyncIterator",
"should be AsyncIterator");
});
it("should infer number from x/y", function () {
const path = getPath("x/y").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be number");
});
it("should infer boolean from x instanceof y", function () {
const path = getPath("x instanceof y").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isBooleanTypeAnnotation(type), "should be boolean");
});
it("should infer number from 1 + 2", function () {
const path = getPath("1 + 2").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isNumberTypeAnnotation(type), "should be number");
});
it("should infer string|number from x + y", function () {
const path = getPath("x + y").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isUnionTypeAnnotation(type), "should be a union");
assert.ok(t.isStringTypeAnnotation(type.types[0]), "first type in union should be string");
assert.ok(t.isNumberTypeAnnotation(type.types[1]), "second type in union should be number");
});
it("should infer type of tagged template literal", function () {
const path = getPath("(function (): RegExp {}) `hey`").get("body")[0].get("expression");
const type = path.getTypeAnnotation();
assert.ok(t.isGenericTypeAnnotation(type) && type.id.name === "RegExp", "should be RegExp");
});
});
});
|
var Chartist = require('chartist');
module.exports = makePluginInstance;
makePluginInstance.calculateScaleFactor = calculateScaleFactor;
makePluginInstance.scaleValue = scaleValue;
function makePluginInstance(userOptions) {
var defaultOptions = {
dot: {
min: 8,
max: 10,
unit: 'px'
},
line: {
min: 2,
max: 4,
unit: 'px'
},
svgWidth: {
min: 360,
max: 1000
}
};
var options = Chartist.extend({}, defaultOptions, userOptions);
return function scaleLinesAndDotsInstance(chart) {
var actualSvgWidth;
chart.on('draw', function(data) {
if (data.type === 'point') {
setStrokeWidth(data, options.dot, options.svgWidth);
} else if (data.type === 'line') {
setStrokeWidth(data, options.line, options.svgWidth);
}
});
/**
* Set stroke-width of the element of a 'data' object, based on chart width.
*
* @param {Object} data - Object passed to 'draw' event listener
* @param {Object} widthRange - Specifies min/max stroke-width and unit.
* @param {Object} thresholds - Specifies chart width to base scaling on.
*/
function setStrokeWidth(data, widthRange, thresholds) {
var scaleFactor = calculateScaleFactor(thresholds.min, thresholds.max, getActualSvgWidth(data));
var strokeWidth = scaleValue(widthRange.min, widthRange.max, scaleFactor);
data.element.attr({
style: 'stroke-width: ' + strokeWidth + widthRange.unit
});
}
/**
* @param {Object} data - Object passed to 'draw' event listener
*/
function getActualSvgWidth(data) {
return data.element.root().width();
}
};
}
function calculateScaleFactor(min, max, value) {
if (max <= min) {
throw new Error('max must be > min');
}
var delta = max - min;
var scaleFactor = (value - min) / delta;
scaleFactor = Math.min(scaleFactor, 1);
scaleFactor = Math.max(scaleFactor, 0);
return scaleFactor;
}
function scaleValue(min, max, scaleFactor) {
if (scaleFactor > 1) throw new Error('scaleFactor cannot be > 1');
if (scaleFactor < 0) throw new Error('scaleFactor cannot be < 0');
if (max < min) throw new Error('max cannot be < min');
var delta = max - min;
return (delta * scaleFactor) + min;
}
|
exports.BattleStatuses = {
brn: {
effectType: 'Status',
onStart: function (target, source, sourceEffect) {
if (sourceEffect && sourceEffect.id === 'flameorb') {
this.add('-status', target, 'brn', '[from] item: Flame Orb');
return;
}
this.add('-status', target, 'brn');
},
onBasePower: function (basePower, attacker, defender, move) {
if (move && move.category === 'Physical' && attacker && attacker.ability !== 'guts' && move.id !== 'facade') {
return this.chainModify(0.5); // This should really take place directly in the damage function but it's here for now
}
},
onResidualOrder: 9,
onResidual: function (pokemon) {
this.damage(pokemon.maxhp / 8);
}
},
par: {
effectType: 'Status',
onStart: function (target) {
this.add('-status', target, 'par');
},
onModifySpe: function (speMod, pokemon) {
if (pokemon.ability !== 'quickfeet') {
return this.chain(speMod, 0.25);
}
},
onBeforeMovePriority: 2,
onBeforeMove: function (pokemon) {
if (this.random(4) === 0) {
this.add('cant', pokemon, 'par');
return false;
}
}
},
slp: {
effectType: 'Status',
onStart: function (target) {
this.add('-status', target, 'slp');
// 1-3 turns
this.effectData.startTime = this.random(2, 5);
this.effectData.time = this.effectData.startTime;
},
onBeforeMovePriority: 2,
onBeforeMove: function (pokemon, target, move) {
if (pokemon.getAbility().isHalfSleep) {
pokemon.statusData.time--;
}
pokemon.statusData.time--;
if (pokemon.statusData.time <= 0) {
pokemon.cureStatus();
return;
}
this.add('cant', pokemon, 'slp');
if (move.sleepUsable) {
return;
}
return false;
}
},
frz: {
effectType: 'Status',
onStart: function (target) {
this.add('-status', target, 'frz');
if (target.species === 'Shaymin-Sky' && target.baseTemplate.species === target.species) {
var template = this.getTemplate('Shaymin');
target.formeChange(template);
target.baseTemplate = template;
target.setAbility(template.abilities['0']);
target.baseAbility = target.ability;
target.details = template.species + (target.level === 100 ? '' : ', L' + target.level) + (target.gender === '' ? '' : ', ' + target.gender) + (target.set.shiny ? ', shiny' : '');
this.add('detailschange', target, target.details);
this.add('message', target.species + " has reverted to Land Forme! (placeholder)");
}
},
onBeforeMovePriority: 2,
onBeforeMove: function (pokemon, target, move) {
if (move.thawsUser || this.random(5) === 0) {
pokemon.cureStatus();
return;
}
this.add('cant', pokemon, 'frz');
return false;
},
onHit: function (target, source, move) {
if (move.type === 'Fire' && move.category !== 'Status') {
target.cureStatus();
}
}
},
psn: {
effectType: 'Status',
onStart: function (target) {
this.add('-status', target, 'psn');
},
onResidualOrder: 9,
onResidual: function (pokemon) {
this.damage(pokemon.maxhp / 8);
}
},
tox: {
effectType: 'Status',
onStart: function (target, source, sourceEffect) {
this.effectData.stage = 0;
if (sourceEffect && sourceEffect.id === 'toxicorb') {
this.add('-status', target, 'tox', '[from] item: Toxic Orb');
return;
}
this.add('-status', target, 'tox');
},
onSwitchIn: function () {
this.effectData.stage = 0;
},
onResidualOrder: 9,
onResidual: function (pokemon) {
if (this.effectData.stage < 15) {
this.effectData.stage++;
}
this.damage(this.clampIntRange(pokemon.maxhp / 16, 1) * this.effectData.stage);
}
},
confusion: {
// this is a volatile status
onStart: function (target, source, sourceEffect) {
var result = this.runEvent('TryConfusion', target, source, sourceEffect);
if (!result) return result;
this.add('-start', target, 'confusion');
this.effectData.time = this.random(2, 6);
},
onEnd: function (target) {
this.add('-end', target, 'confusion');
},
onBeforeMove: function (pokemon) {
pokemon.volatiles.confusion.time--;
if (!pokemon.volatiles.confusion.time) {
pokemon.removeVolatile('confusion');
return;
}
this.add('-activate', pokemon, 'confusion');
if (this.random(2) === 0) {
return;
}
this.directDamage(this.getDamage(pokemon, pokemon, 40));
return false;
}
},
flinch: {
duration: 1,
onBeforeMovePriority: 1,
onBeforeMove: function (pokemon) {
if (!this.runEvent('Flinch', pokemon)) {
return;
}
this.add('cant', pokemon, 'flinch');
return false;
}
},
trapped: {
noCopy: true,
onModifyPokemon: function (pokemon) {
if (!this.effectData.source || !this.effectData.source.isActive) {
delete pokemon.volatiles['trapped'];
return;
}
pokemon.tryTrap();
},
onStart: function (target) {
this.add('-activate', target, 'trapped');
}
},
partiallytrapped: {
duration: 5,
durationCallback: function (target, source) {
if (source.item === 'gripclaw') return 8;
return this.random(5, 7);
},
onStart: function (pokemon, source) {
this.add('-activate', pokemon, 'move: ' +this.effectData.sourceEffect, '[of] ' + source);
},
onResidualOrder: 11,
onResidual: function (pokemon) {
if (this.effectData.source && (!this.effectData.source.isActive || this.effectData.source.hp <= 0)) {
pokemon.removeVolatile('partiallytrapped');
return;
}
if (this.effectData.source.item === 'bindingband') {
this.damage(pokemon.maxhp / 6);
} else {
this.damage(pokemon.maxhp / 8);
}
},
onEnd: function (pokemon) {
this.add('-end', pokemon, this.effectData.sourceEffect, '[partiallytrapped]');
},
onModifyPokemon: function (pokemon) {
pokemon.tryTrap();
}
},
lockedmove: {
// Outrage, Thrash, Petal Dance...
duration: 2,
onResidual: function (target) {
if (target.status === 'slp') {
// don't lock, and bypass confusion for calming
delete target.volatiles['lockedmove'];
}
this.effectData.trueDuration--;
},
onStart: function (target, source, effect) {
this.effectData.trueDuration = this.random(2, 4);
this.effectData.move = effect.id;
},
onRestart: function () {
if (this.effectData.trueDuration >= 2) {
this.effectData.duration = 2;
}
},
onEnd: function (target) {
if (this.effectData.trueDuration > 1) return;
this.add('-end', target, 'rampage');
target.addVolatile('confusion');
},
onLockMove: function (pokemon) {
return this.effectData.move;
}
},
twoturnmove: {
// Skull Bash, SolarBeam, Sky Drop...
duration: 2,
onStart: function (target, source, effect) {
this.effectData.move = effect.id;
// source and target are reversed since the event target is the
// pokemon using the two-turn move
this.effectData.targetLoc = this.getTargetLoc(source, target);
target.addVolatile(effect.id, source);
},
onEnd: function (target) {
target.removeVolatile(this.effectData.move);
},
onLockMove: function () {
return this.effectData.move;
},
onLockMoveTarget: function () {
return this.effectData.targetLoc;
}
},
choicelock: {
onStart: function (pokemon) {
this.effectData.move = this.activeMove.id;
if (!this.effectData.move) return false;
},
onModifyPokemon: function (pokemon) {
if (!pokemon.getItem().isChoice || !pokemon.hasMove(this.effectData.move)) {
pokemon.removeVolatile('choicelock');
return;
}
if (pokemon.ignore['Item']) {
return;
}
var moves = pokemon.moveset;
for (var i = 0; i < moves.length; i++) {
if (moves[i].id !== this.effectData.move) {
moves[i].disabled = true;
}
}
}
},
mustrecharge: {
duration: 2,
onBeforeMove: function (pokemon) {
this.add('cant', pokemon, 'recharge');
pokemon.removeVolatile('mustrecharge');
return false;
},
onLockMove: 'recharge'
},
futuremove: {
// this is a side condition
onStart: function (side) {
this.effectData.positions = [];
for (var i = 0; i < side.active.length; i++) {
this.effectData.positions[i] = null;
}
},
onResidualOrder: 3,
onResidual: function (side) {
var finished = true;
for (var i = 0; i < side.active.length; i++) {
var posData = this.effectData.positions[i];
if (!posData) continue;
posData.duration--;
if (posData.duration > 0) {
finished = false;
continue;
}
// time's up; time to hit! :D
var target = side.foe.active[posData.targetPosition];
var move = this.getMove(posData.move);
if (target.fainted) {
this.add('-hint', '' + move.name + ' did not hit because the target is fainted.');
this.effectData.positions[i] = null;
continue;
}
this.add('-message', '' + move.name + ' hit! (placeholder)');
target.removeVolatile('Protect');
target.removeVolatile('Endure');
if (typeof posData.moveData.affectedByImmunities === 'undefined') {
posData.moveData.affectedByImmunities = true;
}
this.moveHit(target, posData.source, move, posData.moveData);
this.effectData.positions[i] = null;
}
if (finished) {
side.removeSideCondition('futuremove');
}
}
},
stall: {
// Protect, Detect, Endure counter
duration: 2,
counterMax: 256,
onStart: function () {
this.effectData.counter = 3;
},
onStallMove: function () {
// this.effectData.counter should never be undefined here.
// However, just in case, use 1 if it is undefined.
var counter = this.effectData.counter || 1;
this.debug("Success chance: " + Math.round(100 / counter) + "%");
return (this.random(counter) === 0);
},
onRestart: function () {
if (this.effectData.counter < this.effect.counterMax) {
this.effectData.counter *= 3;
}
this.effectData.duration = 2;
}
},
gem: {
duration: 1,
affectsFainted: true,
onBasePower: function (basePower, user, target, move) {
this.debug('Gem Boost');
return this.chainModify([0x14CD, 0x1000]);
}
},
// weather
// weather is implemented here since it's so important to the game
raindance: {
effectType: 'Weather',
duration: 5,
durationCallback: function (source, effect) {
if (source && source.item === 'damprock') {
return 8;
}
return 5;
},
onBasePower: function (basePower, attacker, defender, move) {
if (move.type === 'Water') {
this.debug('rain water boost');
return this.chainModify(1.5);
}
if (move.type === 'Fire') {
this.debug('rain fire suppress');
return this.chainModify(0.5);
}
},
onStart: function (battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'RainDance', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'RainDance');
}
},
onResidualOrder: 1,
onResidual: function () {
this.add('-weather', 'RainDance', '[upkeep]');
this.eachEvent('Weather');
},
onEnd: function () {
this.add('-weather', 'none');
}
},
sunnyday: {
effectType: 'Weather',
duration: 5,
durationCallback: function (source, effect) {
if (source && source.item === 'heatrock') {
return 8;
}
return 5;
},
onBasePower: function (basePower, attacker, defender, move) {
if (move.type === 'Fire') {
this.debug('Sunny Day fire boost');
return this.chainModify(1.5);
}
if (move.type === 'Water') {
this.debug('Sunny Day water suppress');
return this.chainModify(0.5);
}
},
onStart: function (battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'SunnyDay', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'SunnyDay');
}
},
onImmunity: function (type) {
if (type === 'frz') return false;
},
onResidualOrder: 1,
onResidual: function () {
this.add('-weather', 'SunnyDay', '[upkeep]');
this.eachEvent('Weather');
},
onEnd: function () {
this.add('-weather', 'none');
}
},
sandstorm: {
effectType: 'Weather',
duration: 5,
durationCallback: function (source, effect) {
if (source && source.item === 'smoothrock') {
return 8;
}
return 5;
},
// This should be applied directly to the stat before any of the other modifiers are chained
// So we give it increased priority.
onModifySpDPriority: 10,
onModifySpD: function (spd, pokemon) {
if (pokemon.hasType('Rock') && this.isWeather('sandstorm')) {
return this.modify(spd, 1.5);
}
},
onStart: function (battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'Sandstorm', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'Sandstorm');
}
},
onResidualOrder: 1,
onResidual: function () {
this.add('-weather', 'Sandstorm', '[upkeep]');
if (this.isWeather('sandstorm')) this.eachEvent('Weather');
},
onWeather: function (target) {
this.damage(target.maxhp / 16);
},
onEnd: function () {
this.add('-weather', 'none');
}
},
hail: {
effectType: 'Weather',
duration: 5,
durationCallback: function (source, effect) {
if (source && source.item === 'icyrock') {
return 8;
}
return 5;
},
onStart: function (battle, source, effect) {
if (effect && effect.effectType === 'Ability' && this.gen <= 5) {
this.effectData.duration = 0;
this.add('-weather', 'Hail', '[from] ability: ' + effect, '[of] ' + source);
} else {
this.add('-weather', 'Hail');
}
},
onResidualOrder: 1,
onResidual: function () {
this.add('-weather', 'Hail', '[upkeep]');
if (this.isWeather('hail')) this.eachEvent('Weather');
},
onWeather: function (target) {
this.damage(target.maxhp / 16);
},
onEnd: function () {
this.add('-weather', 'none');
}
},
arceus: {
// Arceus's actual typing is implemented here
// Arceus's true typing for all its formes is Normal, and it's only
// Multitype that changes its type, but its formes are specified to
// be their corresponding type in the Pokedex, so that needs to be
// overridden. This is mainly relevant for Hackmons and Balanced
// Hackmons.
onSwitchInPriority: 101,
onSwitchIn: function (pokemon) {
var type = 'Normal';
if (pokemon.ability === 'multitype') {
type = this.runEvent('Plate', pokemon);
if (!type || type === true) {
type = 'Normal';
}
}
pokemon.setType(type, true);
}
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:5a4f668a21f7ea9a0b8ab69c0e5fec6461ab0f73f7836acd640fe43ea9919fcf
size 89408
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({widgetLabel:"\u56fe\u5c42\u5217\u8868",noItemsToDisplay:"\u5f53\u524d\u6ca1\u6709\u8981\u663e\u793a\u7684\u9879\u76ee\u3002",layerInvisibleAtScale:"\u5728\u5f53\u524d\u6bd4\u4f8b\u4e0b\u4e0d\u53ef\u89c1",layerError:"\u52a0\u8f7d\u6b64\u56fe\u5c42\u65f6\u51fa\u9519",untitledLayer:"\u65e0\u6807\u9898\u56fe\u5c42"}); |
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
$.ui = $.ui || {};
return $.ui.version = "1.12.1";
} ) );
/*!
* jQuery UI Widget 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;
$.cleanData = ( function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// Http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
} )( $.cleanData );
$.widget = function( name, base, prototype ) {
var existingConstructor, constructor, basePrototype;
// ProxiedPrototype allows the provided prototype to remain unmodified
// so that it can be used as a mixin for multiple widgets (#8876)
var proxiedPrototype = {};
var namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
var fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
if ( $.isArray( prototype ) ) {
prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
}
// Create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// Allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// Allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// Extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// Copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// Track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
} );
basePrototype = new base();
// We need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( !$.isFunction( value ) ) {
proxiedPrototype[ prop ] = value;
return;
}
proxiedPrototype[ prop ] = ( function() {
function _super() {
return base.prototype[ prop ].apply( this, arguments );
}
function _superApply( args ) {
return base.prototype[ prop ].apply( this, args );
}
return function() {
var __super = this._super;
var __superApply = this._superApply;
var returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
} )();
} );
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
}, proxiedPrototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
} );
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// Redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
child._proto );
} );
// Remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
return constructor;
};
$.widget.extend = function( target ) {
var input = widgetSlice.call( arguments, 1 );
var inputIndex = 0;
var inputLength = input.length;
var key;
var value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string";
var args = widgetSlice.call( arguments, 1 );
var returnValue = this;
if ( isMethodCall ) {
// If this is an empty collection, we need to have the instance method
// return undefined instead of the jQuery instance
if ( !this.length && options === "instance" ) {
returnValue = undefined;
} else {
this.each( function() {
var methodValue;
var instance = $.data( this, fullName );
if ( options === "instance" ) {
returnValue = instance;
return false;
}
if ( !instance ) {
return $.error( "cannot call methods on " + name +
" prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name +
" widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
} );
}
} else {
// Allow multiple hashes to be passed on init
if ( args.length ) {
options = $.widget.extend.apply( null, [ options ].concat( args ) );
}
this.each( function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} );
if ( instance._init ) {
instance._init();
}
} else {
$.data( this, fullName, new object( options, this ) );
}
} );
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
classes: {},
disabled: false,
// Callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = widgetUuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.bindings = $();
this.hoverable = $();
this.focusable = $();
this.classesElementLookup = {};
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
} );
this.document = $( element.style ?
// Element within the document
element.ownerDocument :
// Element is window or document
element.document || element );
this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
}
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this._create();
if ( this.options.disabled ) {
this._setOptionDisabled( this.options.disabled );
}
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: function() {
return {};
},
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
var that = this;
this._destroy();
$.each( this.classesElementLookup, function( key, value ) {
that._removeClass( value, key );
} );
// We can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.off( this.eventNamespace )
.removeData( this.widgetFullName );
this.widget()
.off( this.eventNamespace )
.removeAttr( "aria-disabled" );
// Clean up events and states
this.bindings.off( this.eventNamespace );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key;
var parts;
var curOption;
var i;
if ( arguments.length === 0 ) {
// Don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( arguments.length === 1 ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( arguments.length === 1 ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
if ( key === "classes" ) {
this._setOptionClasses( value );
}
this.options[ key ] = value;
if ( key === "disabled" ) {
this._setOptionDisabled( value );
}
return this;
},
_setOptionClasses: function( value ) {
var classKey, elements, currentElements;
for ( classKey in value ) {
currentElements = this.classesElementLookup[ classKey ];
if ( value[ classKey ] === this.options.classes[ classKey ] ||
!currentElements ||
!currentElements.length ) {
continue;
}
// We are doing this to create a new jQuery object because the _removeClass() call
// on the next line is going to destroy the reference to the current elements being
// tracked. We need to save a copy of this collection so that we can add the new classes
// below.
elements = $( currentElements.get() );
this._removeClass( currentElements, classKey );
// We don't use _addClass() here, because that uses this.options.classes
// for generating the string of classes. We want to use the value passed in from
// _setOption(), this is the new value of the classes option which was passed to
// _setOption(). We pass this value directly to _classes().
elements.addClass( this._classes( {
element: elements,
keys: classKey,
classes: value,
add: true
} ) );
}
},
_setOptionDisabled: function( value ) {
this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );
// If the widget is becoming disabled, then nothing is interactive
if ( value ) {
this._removeClass( this.hoverable, null, "ui-state-hover" );
this._removeClass( this.focusable, null, "ui-state-focus" );
}
},
enable: function() {
return this._setOptions( { disabled: false } );
},
disable: function() {
return this._setOptions( { disabled: true } );
},
_classes: function( options ) {
var full = [];
var that = this;
options = $.extend( {
element: this.element,
classes: this.options.classes || {}
}, options );
function processClassString( classes, checkOption ) {
var current, i;
for ( i = 0; i < classes.length; i++ ) {
current = that.classesElementLookup[ classes[ i ] ] || $();
if ( options.add ) {
current = $( $.unique( current.get().concat( options.element.get() ) ) );
} else {
current = $( current.not( options.element ).get() );
}
that.classesElementLookup[ classes[ i ] ] = current;
full.push( classes[ i ] );
if ( checkOption && options.classes[ classes[ i ] ] ) {
full.push( options.classes[ classes[ i ] ] );
}
}
}
this._on( options.element, {
"remove": "_untrackClassesElement"
} );
if ( options.keys ) {
processClassString( options.keys.match( /\S+/g ) || [], true );
}
if ( options.extra ) {
processClassString( options.extra.match( /\S+/g ) || [] );
}
return full.join( " " );
},
_untrackClassesElement: function( event ) {
var that = this;
$.each( that.classesElementLookup, function( key, value ) {
if ( $.inArray( event.target, value ) !== -1 ) {
that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
}
} );
},
_removeClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, false );
},
_addClass: function( element, keys, extra ) {
return this._toggleClass( element, keys, extra, true );
},
_toggleClass: function( element, keys, extra, add ) {
add = ( typeof add === "boolean" ) ? add : extra;
var shift = ( typeof element === "string" || element === null ),
options = {
extra: shift ? keys : extra,
keys: shift ? element : keys,
element: shift ? this.element : element,
add: add
};
options.element.toggleClass( this._classes( options ), add );
return this;
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement;
var instance = this;
// No suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// No element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// Allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// Copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^([\w:-]*)\s*(.*)$/ );
var eventName = match[ 1 ] + instance.eventNamespace;
var selector = match[ 2 ];
if ( selector ) {
delegateElement.on( eventName, selector, handlerProxy );
} else {
element.on( eventName, handlerProxy );
}
} );
},
_off: function( element, eventName ) {
eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
this.eventNamespace;
element.off( eventName ).off( eventName );
// Clear the stack to avoid memory leaks (#10056)
this.bindings = $( this.bindings.not( element ).get() );
this.focusable = $( this.focusable.not( element ).get() );
this.hoverable = $( this.hoverable.not( element ).get() );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
},
mouseleave: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
}
} );
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
},
focusout: function( event ) {
this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
}
} );
},
_trigger: function( type, event, data ) {
var prop, orig;
var callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// The original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// Copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions;
var effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue( function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
} );
}
};
} );
return $.widget;
} ) );
/*!
* jQuery UI Controlgroup 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Controlgroup
//>>group: Widgets
//>>description: Visually groups form control widgets
//>>docs: http://api.jqueryui.com/controlgroup/
//>>demos: http://jqueryui.com/controlgroup/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/controlgroup.css
//>>css.theme: ../../themes/base/theme.css
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [
"jquery",
"../widget"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
var controlgroupCornerRegex = /ui-corner-([a-z]){2,6}/g;
return $.widget( "ui.controlgroup", {
version: "1.12.1",
defaultElement: "<div>",
options: {
direction: "horizontal",
disabled: null,
onlyVisible: true,
items: {
"button": "input[type=button], input[type=submit], input[type=reset], button, a",
"controlgroupLabel": ".ui-controlgroup-label",
"checkboxradio": "input[type='checkbox'], input[type='radio']",
"selectmenu": "select",
"spinner": ".ui-spinner-input"
}
},
_create: function() {
this._enhance();
},
// To support the enhanced option in jQuery Mobile, we isolate DOM manipulation
_enhance: function() {
this.element.attr( "role", "toolbar" );
this.refresh();
},
_destroy: function() {
this._callChildMethod( "destroy" );
this.childWidgets.removeData( "ui-controlgroup-data" );
this.element.removeAttr( "role" );
if ( this.options.items.controlgroupLabel ) {
this.element
.find( this.options.items.controlgroupLabel )
.find( ".ui-controlgroup-label-contents" )
.contents().unwrap();
}
},
_initWidgets: function() {
var that = this,
childWidgets = [];
// First we iterate over each of the items options
$.each( this.options.items, function( widget, selector ) {
var labels;
var options = {};
// Make sure the widget has a selector set
if ( !selector ) {
return;
}
if ( widget === "controlgroupLabel" ) {
labels = that.element.find( selector );
labels.each( function() {
var element = $( this );
if ( element.children( ".ui-controlgroup-label-contents" ).length ) {
return;
}
element.contents()
.wrapAll( "<span class='ui-controlgroup-label-contents'></span>" );
} );
that._addClass( labels, null, "ui-widget ui-widget-content ui-state-default" );
childWidgets = childWidgets.concat( labels.get() );
return;
}
// Make sure the widget actually exists
if ( !$.fn[ widget ] ) {
return;
}
// We assume everything is in the middle to start because we can't determine
// first / last elements until all enhancments are done.
if ( that[ "_" + widget + "Options" ] ) {
options = that[ "_" + widget + "Options" ]( "middle" );
} else {
options = { classes: {} };
}
// Find instances of this widget inside controlgroup and init them
that.element
.find( selector )
.each( function() {
var element = $( this );
var instance = element[ widget ]( "instance" );
// We need to clone the default options for this type of widget to avoid
// polluting the variable options which has a wider scope than a single widget.
var instanceOptions = $.widget.extend( {}, options );
// If the button is the child of a spinner ignore it
// TODO: Find a more generic solution
if ( widget === "button" && element.parent( ".ui-spinner" ).length ) {
return;
}
// Create the widget if it doesn't exist
if ( !instance ) {
instance = element[ widget ]()[ widget ]( "instance" );
}
if ( instance ) {
instanceOptions.classes =
that._resolveClassesValues( instanceOptions.classes, instance );
}
element[ widget ]( instanceOptions );
// Store an instance of the controlgroup to be able to reference
// from the outermost element for changing options and refresh
var widgetElement = element[ widget ]( "widget" );
$.data( widgetElement[ 0 ], "ui-controlgroup-data",
instance ? instance : element[ widget ]( "instance" ) );
childWidgets.push( widgetElement[ 0 ] );
} );
} );
this.childWidgets = $( $.unique( childWidgets ) );
this._addClass( this.childWidgets, "ui-controlgroup-item" );
},
_callChildMethod: function( method ) {
this.childWidgets.each( function() {
var element = $( this ),
data = element.data( "ui-controlgroup-data" );
if ( data && data[ method ] ) {
data[ method ]();
}
} );
},
_updateCornerClass: function( element, position ) {
var remove = "ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";
var add = this._buildSimpleOptions( position, "label" ).classes.label;
this._removeClass( element, null, remove );
this._addClass( element, null, add );
},
_buildSimpleOptions: function( position, key ) {
var direction = this.options.direction === "vertical";
var result = {
classes: {}
};
result.classes[ key ] = {
"middle": "",
"first": "ui-corner-" + ( direction ? "top" : "left" ),
"last": "ui-corner-" + ( direction ? "bottom" : "right" ),
"only": "ui-corner-all"
}[ position ];
return result;
},
_spinnerOptions: function( position ) {
var options = this._buildSimpleOptions( position, "ui-spinner" );
options.classes[ "ui-spinner-up" ] = "";
options.classes[ "ui-spinner-down" ] = "";
return options;
},
_buttonOptions: function( position ) {
return this._buildSimpleOptions( position, "ui-button" );
},
_checkboxradioOptions: function( position ) {
return this._buildSimpleOptions( position, "ui-checkboxradio-label" );
},
_selectmenuOptions: function( position ) {
var direction = this.options.direction === "vertical";
return {
width: direction ? "auto" : false,
classes: {
middle: {
"ui-selectmenu-button-open": "",
"ui-selectmenu-button-closed": ""
},
first: {
"ui-selectmenu-button-open": "ui-corner-" + ( direction ? "top" : "tl" ),
"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "top" : "left" )
},
last: {
"ui-selectmenu-button-open": direction ? "" : "ui-corner-tr",
"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "bottom" : "right" )
},
only: {
"ui-selectmenu-button-open": "ui-corner-top",
"ui-selectmenu-button-closed": "ui-corner-all"
}
}[ position ]
};
},
_resolveClassesValues: function( classes, instance ) {
var result = {};
$.each( classes, function( key ) {
var current = instance.options.classes[ key ] || "";
current = $.trim( current.replace( controlgroupCornerRegex, "" ) );
result[ key ] = ( current + " " + classes[ key ] ).replace( /\s+/g, " " );
} );
return result;
},
_setOption: function( key, value ) {
if ( key === "direction" ) {
this._removeClass( "ui-controlgroup-" + this.options.direction );
}
this._super( key, value );
if ( key === "disabled" ) {
this._callChildMethod( value ? "disable" : "enable" );
return;
}
this.refresh();
},
refresh: function() {
var children,
that = this;
this._addClass( "ui-controlgroup ui-controlgroup-" + this.options.direction );
if ( this.options.direction === "horizontal" ) {
this._addClass( null, "ui-helper-clearfix" );
}
this._initWidgets();
children = this.childWidgets;
// We filter here because we need to track all childWidgets not just the visible ones
if ( this.options.onlyVisible ) {
children = children.filter( ":visible" );
}
if ( children.length ) {
// We do this last because we need to make sure all enhancment is done
// before determining first and last
$.each( [ "first", "last" ], function( index, value ) {
var instance = children[ value ]().data( "ui-controlgroup-data" );
if ( instance && that[ "_" + instance.widgetName + "Options" ] ) {
var options = that[ "_" + instance.widgetName + "Options" ](
children.length === 1 ? "only" : value
);
options.classes = that._resolveClassesValues( options.classes, instance );
instance.element[ instance.widgetName ]( options );
} else {
that._updateCornerClass( children[ value ](), value );
}
} );
// Finally call the refresh method on each of the child widgets.
this._callChildMethod( "refresh" );
}
}
} );
} ) );
|
import * as types from '@/store/mutation-types';
export default {
namespaced: true,
state: {
type: 0,
catId: 0
},
getters: {
[types.STATE_INFO]: state => {
return state.type + 3;
}
}
}
|
document.observe('click', function(e, el) {
if (el = e.findElement('form a.add_nested_fields')) {
// Setup
var assoc = el.readAttribute('data-association'); // Name of child
var target = el.readAttribute('data-target');
var blueprint = $(el.readAttribute('data-blueprint-id'));
var content = blueprint.readAttribute('data-blueprint'); // Fields template
// Make the context correct by replacing <parents> with the generated ID
// of each of the parent objects
var context = (el.getOffsetParent('.fields').firstDescendant().readAttribute('name') || '').replace(/\[[a-z_]+\]$/, '');
// If the parent has no inputs we need to strip off the last pair
var current = content.match(new RegExp('\\[([a-z_]+)\\]\\[new_' + assoc + '\\]'));
if (current) {
context = context.replace(new RegExp('\\[' + current[1] + '\\]\\[(new_)?\\d+\\]$'), '');
}
// context will be something like this for a brand new form:
// project[tasks_attributes][1255929127459][assignments_attributes][1255929128105]
// or for an edit form:
// project[tasks_attributes][0][assignments_attributes][1]
if(context) {
var parent_names = context.match(/[a-z_]+_attributes(?=\]\[(new_)?\d+\])/g) || [];
var parent_ids = context.match(/[0-9]+/g) || [];
for(i = 0; i < parent_names.length; i++) {
if(parent_ids[i]) {
content = content.replace(
new RegExp('(_' + parent_names[i] + ')_.+?_', 'g'),
'$1_' + parent_ids[i] + '_');
content = content.replace(
new RegExp('(\\[' + parent_names[i] + '\\])\\[.+?\\]', 'g'),
'$1[' + parent_ids[i] + ']');
}
}
}
// Make a unique ID for the new child
var regexp = new RegExp('new_' + assoc, 'g');
var new_id = new Date().getTime();
content = content.replace(regexp, new_id);
var field;
if (target) {
field = $$(target)[0].insert(content);
} else {
field = el.insert({ before: content });
}
field.fire('nested:fieldAdded', {field: field, association: assoc});
field.fire('nested:fieldAdded:' + assoc, {field: field, association: assoc});
return false;
}
});
document.observe('click', function(e, el) {
if (el = e.findElement('form a.remove_nested_fields')) {
var hidden_field = el.previous(0),
assoc = el.readAttribute('data-association'); // Name of child to be removed
if(hidden_field) {
hidden_field.value = '1';
}
var field = el.up('.fields').hide();
field.fire('nested:fieldRemoved', {field: field, association: assoc});
field.fire('nested:fieldRemoved:' + assoc, {field: field, association: assoc});
return false;
}
});
|
import { Component } from 'vidom';
import { DocComponent, DocTabs, DocTab, DocAttrs, DocAttr, DocExample, DocChildren, DocText, DocInlineCode } from '../../Doc';
import SimpleExample from './examples/SimpleExample';
import simpleExampleCode from '!raw!./examples/SimpleExample.js';
export default function ModalDoc({ tab, onTabChange }) {
return (
<DocComponent title="Modal">
<DocTabs value={ tab } onTabChange={ onTabChange }>
<DocTab title="Examples" value="Examples">
<DocExample title="Simple" code={ simpleExampleCode }>
<SimpleExample/>
</DocExample>
</DocTab>
<DocTab title="API" value="api">
<DocAttrs>
<DocAttr name="autoclosable" type="Boolean" def="false">
Enables the modal to be hidden on pressing "Esc" or clicking somewhere outside its content.
</DocAttr>
<DocAttr name="onHide" type="Function">
The callback to handle hide event.
</DocAttr>
<DocAttr name="theme" type="String" required>
Sets the modal theme.
</DocAttr>
<DocAttr name="visible" type="Boolean" def="false">
Sets the visibility of the modal.
</DocAttr>
</DocAttrs>
<DocChildren>
<DocText>
Children with any valid type are allowed.
</DocText>
</DocChildren>
</DocTab>
</DocTabs>
</DocComponent>
);
}
|
// Copyright 2013-2022, University of Colorado Boulder
/**
* A DOM drawable (div element) that contains child blocks (and is placed in the main DOM tree when visible). It should
* use z-index for properly ordering its blocks in the correct stacking order.
*
* @author Jonathan Olson <[email protected]>
*/
import toSVGNumber from '../../../dot/js/toSVGNumber.js';
import cleanArray from '../../../phet-core/js/cleanArray.js';
import Poolable from '../../../phet-core/js/Poolable.js';
import { scenery, Utils, Drawable, GreedyStitcher, RebuildStitcher, Stitcher } from '../imports.js';
// constants
const useGreedyStitcher = true;
class BackboneDrawable extends Drawable {
/**
* @mixes Poolable
*
* @param {Display} display
* @param {Instance} backboneInstance
* @param {Instance} transformRootInstance
* @param {number} renderer
* @param {boolean} isDisplayRoot
*/
constructor( display, backboneInstance, transformRootInstance, renderer, isDisplayRoot ) {
super();
this.initialize( display, backboneInstance, transformRootInstance, renderer, isDisplayRoot );
}
/**
* @public
*
* @param {Display} display
* @param {Instance} backboneInstance
* @param {Instance} transformRootInstance
* @param {number} renderer
* @param {boolean} isDisplayRoot
*/
initialize( display, backboneInstance, transformRootInstance, renderer, isDisplayRoot ) {
super.initialize( renderer );
this.display = display;
// @public {Instance} - reference to the instance that controls this backbone
this.backboneInstance = backboneInstance;
// @public {Instance} - where is the transform root for our generated blocks?
this.transformRootInstance = transformRootInstance;
// @private {Instance} - where have filters been applied to up? our responsibility is to apply filters between this
// and our backboneInstance
this.filterRootAncestorInstance = backboneInstance.parent ? backboneInstance.parent.getFilterRootInstance() : backboneInstance;
// where have transforms been applied up to? our responsibility is to apply transforms between this and our backboneInstance
this.transformRootAncestorInstance = backboneInstance.parent ? backboneInstance.parent.getTransformRootInstance() : backboneInstance;
this.willApplyTransform = this.transformRootAncestorInstance !== this.transformRootInstance;
this.willApplyFilters = this.filterRootAncestorInstance !== this.backboneInstance;
this.transformListener = this.transformListener || this.markTransformDirty.bind( this );
if ( this.willApplyTransform ) {
this.backboneInstance.relativeTransform.addListener( this.transformListener ); // when our relative transform changes, notify us in the pre-repaint phase
this.backboneInstance.relativeTransform.addPrecompute(); // trigger precomputation of the relative transform, since we will always need it when it is updated
}
this.backboneVisibilityListener = this.backboneVisibilityListener || this.updateBackboneVisibility.bind( this );
this.backboneInstance.relativeVisibleEmitter.addListener( this.backboneVisibilityListener );
this.updateBackboneVisibility();
this.visibilityDirty = true;
this.renderer = renderer;
this.domElement = isDisplayRoot ? display.domElement : BackboneDrawable.createDivBackbone();
this.isDisplayRoot = isDisplayRoot;
this.dirtyDrawables = cleanArray( this.dirtyDrawables );
// Apply CSS needed for future CSS transforms to work properly.
Utils.prepareForTransform( this.domElement );
// Ff we need to, watch nodes below us (and including us) and apply their filters (opacity/visibility/clip) to the
// backbone. Order will be important, since we'll visit them in the order of filter application
this.watchedFilterNodes = cleanArray( this.watchedFilterNodes );
// @private {boolean}
this.filterDirty = true;
// @private {boolean}
this.clipDirty = true;
this.filterDirtyListener = this.filterDirtyListener || this.onFilterDirty.bind( this );
this.clipDirtyListener = this.clipDirtyListener || this.onClipDirty.bind( this );
if ( this.willApplyFilters ) {
assert && assert( this.filterRootAncestorInstance.trail.nodes.length < this.backboneInstance.trail.nodes.length,
'Our backboneInstance should be deeper if we are applying filters' );
// walk through to see which instances we'll need to watch for filter changes
// NOTE: order is important, so that the filters are applied in the correct order!
for ( let instance = this.backboneInstance; instance !== this.filterRootAncestorInstance; instance = instance.parent ) {
const node = instance.node;
this.watchedFilterNodes.push( node );
node.filterChangeEmitter.addListener( this.filterDirtyListener );
node.clipAreaProperty.lazyLink( this.clipDirtyListener );
}
}
this.lastZIndex = 0; // our last zIndex is stored, so that overlays can be added easily
this.blocks = this.blocks || []; // we are responsible for their disposal
// the first/last drawables for the last the this backbone was stitched
this.previousFirstDrawable = null;
this.previousLastDrawable = null;
// We track whether our drawables were marked for removal (in which case, they should all be removed by the time we dispose).
// If removedDrawables = false during disposal, it means we need to remove the drawables manually (this should only happen if an instance tree is removed)
this.removedDrawables = false;
this.stitcher = this.stitcher || ( useGreedyStitcher ? new GreedyStitcher() : new RebuildStitcher() );
sceneryLog && sceneryLog.BackboneDrawable && sceneryLog.BackboneDrawable( `initialized ${this.toString()}` );
}
/**
* Releases references
* @public
*/
dispose() {
sceneryLog && sceneryLog.BackboneDrawable && sceneryLog.BackboneDrawable( `dispose ${this.toString()}` );
sceneryLog && sceneryLog.BackboneDrawable && sceneryLog.push();
while ( this.watchedFilterNodes.length ) {
const node = this.watchedFilterNodes.pop();
node.filterChangeEmitter.removeListener( this.filterDirtyListener );
node.clipAreaProperty.unlink( this.clipDirtyListener );
}
this.backboneInstance.relativeVisibleEmitter.removeListener( this.backboneVisibilityListener );
// if we need to remove drawables from the blocks, do so
if ( !this.removedDrawables ) {
for ( let d = this.previousFirstDrawable; d !== null; d = d.nextDrawable ) {
d.parentDrawable.removeDrawable( d );
if ( d === this.previousLastDrawable ) { break; }
}
}
this.markBlocksForDisposal();
if ( this.willApplyTransform ) {
this.backboneInstance.relativeTransform.removeListener( this.transformListener );
this.backboneInstance.relativeTransform.removePrecompute();
}
this.backboneInstance = null;
this.transformRootInstance = null;
this.filterRootAncestorInstance = null;
this.transformRootAncestorInstance = null;
cleanArray( this.dirtyDrawables );
cleanArray( this.watchedFilterNodes );
this.previousFirstDrawable = null;
this.previousLastDrawable = null;
super.dispose();
sceneryLog && sceneryLog.BackboneDrawable && sceneryLog.pop();
}
/**
* Dispose all of the blocks while clearing our references to them
* @public
*/
markBlocksForDisposal() {
while ( this.blocks.length ) {
const block = this.blocks.pop();
sceneryLog && sceneryLog.BackboneDrawable && sceneryLog.BackboneDrawable( `${this.toString()} removing block: ${block.toString()}` );
//TODO: PERFORMANCE: does this cause reflows / style calculation
if ( block.domElement.parentNode === this.domElement ) {
// guarded, since we may have a (new) child drawable add it before we can remove it
this.domElement.removeChild( block.domElement );
}
block.markForDisposal( this.display );
}
}
/**
* @private
*/
updateBackboneVisibility() {
this.visible = this.backboneInstance.relativeVisible;
if ( !this.visibilityDirty ) {
this.visibilityDirty = true;
this.markDirty();
}
}
/**
* Marks this backbone for disposal.
* @public
* @override
*
* NOTE: Should be called during syncTree
*
* @param {Display} display
*/
markForDisposal( display ) {
for ( let d = this.previousFirstDrawable; d !== null; d = d.oldNextDrawable ) {
d.notePendingRemoval( this.display );
if ( d === this.previousLastDrawable ) { break; }
}
this.removedDrawables = true;
// super call
super.markForDisposal( display );
}
/**
* Marks a drawable as dirty.
* @public
*
* @param {Drawable} drawable
*/
markDirtyDrawable( drawable ) {
if ( assert ) {
// Catch infinite loops
this.display.ensureNotPainting();
}
this.dirtyDrawables.push( drawable );
this.markDirty();
}
/**
* Marks our transform as dirty.
* @public
*/
markTransformDirty() {
assert && assert( this.willApplyTransform, 'Sanity check for willApplyTransform' );
// relative matrix on backbone instance should be up to date, since we added the compute flags
Utils.applyPreparedTransform( this.backboneInstance.relativeTransform.matrix, this.domElement );
}
/**
* Marks our opacity as dirty.
* @private
*/
onFilterDirty() {
if ( !this.filterDirty ) {
this.filterDirty = true;
this.markDirty();
}
}
/**
* Marks our clip as dirty.
* @private
*/
onClipDirty() {
if ( !this.clipDirty ) {
this.clipDirty = true;
this.markDirty();
}
}
/**
* Updates the DOM appearance of this drawable (whether by preparing/calling draw calls, DOM element updates, etc.)
* @public
* @override
*
* @returns {boolean} - Whether the update should continue (if false, further updates in supertype steps should not
* be done).
*/
update() {
// See if we need to actually update things (will bail out if we are not dirty, or if we've been disposed)
if ( !super.update() ) {
return false;
}
while ( this.dirtyDrawables.length ) {
this.dirtyDrawables.pop().update();
}
if ( this.filterDirty ) {
this.filterDirty = false;
let filterString = '';
const len = this.watchedFilterNodes.length;
for ( let i = 0; i < len; i++ ) {
const node = this.watchedFilterNodes[ i ];
const opacity = node.getEffectiveOpacity();
for ( let j = 0; j < node._filters.length; j++ ) {
filterString += `${filterString ? ' ' : ''}${node._filters[ j ].getCSSFilterString()}`;
}
// Apply opacity after other effects
if ( opacity !== 1 ) {
filterString += `${filterString ? ' ' : ''}opacity(${toSVGNumber( opacity )})`;
}
}
this.domElement.style.filter = filterString;
}
if ( this.visibilityDirty ) {
this.visibilityDirty = false;
this.domElement.style.display = this.visible ? '' : 'none';
}
if ( this.clipDirty ) {
this.clipDirty = false;
// var clip = this.willApplyFilters ? this.getFilterClip() : '';
//OHTWO TODO: CSS clip-path/mask support here. see http://www.html5rocks.com/en/tutorials/masking/adobe/
// this.domElement.style.clipPath = clip; // yikes! temporary, since we already threw something?
}
return true;
}
/**
* Returns the combined visibility of nodes "above us" that will need to be taken into account for displaying this
* backbone.
* @public
*
* @returns {boolean}
*/
getFilterVisibility() {
const len = this.watchedFilterNodes.length;
for ( let i = 0; i < len; i++ ) {
if ( !this.watchedFilterNodes[ i ].isVisible() ) {
return false;
}
}
return true;
}
/**
* Returns the combined clipArea (string???) for nodes "above us".
* @public
*
* @returns {string}
*/
getFilterClip() {
const clip = '';
//OHTWO TODO: proper clipping support
// var len = this.watchedFilterNodes.length;
// for ( var i = 0; i < len; i++ ) {
// if ( this.watchedFilterNodes[i].clipArea ) {
// throw new Error( 'clip-path for backbones unimplemented, and with questionable browser support!' );
// }
// }
return clip;
}
/**
* Ensures that z-indices are strictly increasing, while trying to minimize the number of times we must change it
* @public
*/
reindexBlocks() {
// full-pass change for zindex.
let zIndex = 0; // don't start below 1 (we ensure > in loop)
for ( let k = 0; k < this.blocks.length; k++ ) {
const block = this.blocks[ k ];
if ( block.zIndex <= zIndex ) {
const newIndex = ( k + 1 < this.blocks.length && this.blocks[ k + 1 ].zIndex - 1 > zIndex ) ?
Math.ceil( ( zIndex + this.blocks[ k + 1 ].zIndex ) / 2 ) :
zIndex + 20;
// NOTE: this should give it its own stacking index (which is what we want)
block.domElement.style.zIndex = block.zIndex = newIndex;
}
zIndex = block.zIndex;
if ( assert ) {
assert( this.blocks[ k ].zIndex % 1 === 0, 'z-indices should be integers' );
assert( this.blocks[ k ].zIndex > 0, 'z-indices should be greater than zero for our needs (see spec)' );
if ( k > 0 ) {
assert( this.blocks[ k - 1 ].zIndex < this.blocks[ k ].zIndex, 'z-indices should be strictly increasing' );
}
}
}
// sanity check
this.lastZIndex = zIndex + 1;
}
/**
* Stitches multiple change intervals.
* @public
*
* @param {Drawable} firstDrawable
* @param {Drawable} lastDrawable
* @param {ChangeInterval} firstChangeInterval
* @param {ChangeInterval} lastChangeInterval
*/
stitch( firstDrawable, lastDrawable, firstChangeInterval, lastChangeInterval ) {
// no stitch necessary if there are no change intervals
if ( firstChangeInterval === null || lastChangeInterval === null ) {
assert && assert( firstChangeInterval === null );
assert && assert( lastChangeInterval === null );
return;
}
assert && assert( lastChangeInterval.nextChangeInterval === null, 'This allows us to have less checks in the loop' );
if ( sceneryLog && sceneryLog.Stitch ) {
sceneryLog.Stitch( `Stitch intervals before constricting: ${this.toString()}` );
sceneryLog.push();
Stitcher.debugIntervals( firstChangeInterval );
sceneryLog.pop();
}
// Make the intervals as small as possible by skipping areas without changes, and collapse the interval
// linked list
let lastNonemptyInterval = null;
let interval = firstChangeInterval;
let intervalsChanged = false;
while ( interval ) {
intervalsChanged = interval.constrict() || intervalsChanged;
if ( interval.isEmpty() ) {
assert && assert( intervalsChanged );
if ( lastNonemptyInterval ) {
// skip it, hook the correct reference
lastNonemptyInterval.nextChangeInterval = interval.nextChangeInterval;
}
}
else {
// our first non-empty interval will be our new firstChangeInterval
if ( !lastNonemptyInterval ) {
firstChangeInterval = interval;
}
lastNonemptyInterval = interval;
}
interval = interval.nextChangeInterval;
}
if ( !lastNonemptyInterval ) {
// eek, no nonempty change intervals. do nothing (good to catch here, but ideally there shouldn't be change
// intervals that all collapse).
return;
}
lastChangeInterval = lastNonemptyInterval;
lastChangeInterval.nextChangeInterval = null;
if ( sceneryLog && sceneryLog.Stitch && intervalsChanged ) {
sceneryLog.Stitch( `Stitch intervals after constricting: ${this.toString()}` );
sceneryLog.push();
Stitcher.debugIntervals( firstChangeInterval );
sceneryLog.pop();
}
if ( sceneryLog && scenery.isLoggingPerformance() ) {
this.display.perfStitchCount++;
let dInterval = firstChangeInterval;
while ( dInterval ) {
this.display.perfIntervalCount++;
this.display.perfDrawableOldIntervalCount += dInterval.getOldInternalDrawableCount( this.previousFirstDrawable, this.previousLastDrawable );
this.display.perfDrawableNewIntervalCount += dInterval.getNewInternalDrawableCount( firstDrawable, lastDrawable );
dInterval = dInterval.nextChangeInterval;
}
}
this.stitcher.stitch( this, firstDrawable, lastDrawable, this.previousFirstDrawable, this.previousLastDrawable, firstChangeInterval, lastChangeInterval );
}
/**
* Runs checks on the drawable, based on certain flags.
* @public
* @override
*
* @param {boolean} allowPendingBlock
* @param {boolean} allowPendingList
* @param {boolean} allowDirty
*/
audit( allowPendingBlock, allowPendingList, allowDirty ) {
if ( assertSlow ) {
super.audit( allowPendingBlock, allowPendingList, allowDirty );
assertSlow && assertSlow( this.backboneInstance.isBackbone, 'We should reference an instance that requires a backbone' );
assertSlow && assertSlow( this.transformRootInstance.isTransformed, 'Transform root should be transformed' );
for ( let i = 0; i < this.blocks.length; i++ ) {
this.blocks[ i ].audit( allowPendingBlock, allowPendingList, allowDirty );
}
}
}
/**
* Creates a base DOM element for a backbone.
* @public
*
* @returns {HTMLDivElement}
*/
static createDivBackbone() {
const div = document.createElement( 'div' );
div.style.position = 'absolute';
div.style.left = '0';
div.style.top = '0';
div.style.width = '0';
div.style.height = '0';
return div;
}
/**
* Given an external element, we apply the necessary style to make it compatible as a backbone DOM element.
* @public
*
* @param {HTMLElement} element
* @returns {HTMLElement} - For chaining
*/
static repurposeBackboneContainer( element ) {
if ( element.style.position !== 'relative' || element.style.position !== 'absolute' ) {
element.style.position = 'relative';
}
element.style.left = '0';
element.style.top = '0';
return element;
}
}
scenery.register( 'BackboneDrawable', BackboneDrawable );
Poolable.mixInto( BackboneDrawable );
export default BackboneDrawable; |
"use strict";
/**
* Broadcast updates to client when the model changes
*/
Object.defineProperty(exports, "__esModule", { value: true });
var product_events_1 = require("./product.events");
// Model events to emit
var events = ['save', 'remove'];
function register(socket) {
// Bind model events to socket events
for (var i = 0, eventsLength = events.length; i < eventsLength; i++) {
var event = events[i];
var listener = createListener('product:' + event, socket);
product_events_1.default.on(event, listener);
socket.on('disconnect', removeListener(event, listener));
}
}
exports.register = register;
function createListener(event, socket) {
return function (doc) {
socket.emit(event, doc);
};
}
function removeListener(event, listener) {
return function () {
product_events_1.default.removeListener(event, listener);
};
}
//# sourceMappingURL=product.socket.js.map |
/**
* vuex-mapstate-modelvalue-instrict- v0.0.4
* (c) 2017 fsy0718
* @license MIT
*/
'use strict';
var push = Array.prototype.push;
var pop = Array.prototype.pop;
var _mapStateModelValueInStrict = function (modelValue, stateName, type, opts, setWithPayload, copts) {
if ( opts === void 0 ) opts = {};
if ( copts === void 0 ) copts = {};
if (process.env.NODE_ENV === 'development' && (!modelValue || !stateName || !type)) {
throw new Error(("vuex-mapstate-modelvalue-instrict: the " + modelValue + " at least 3 parameters are required"))
}
var getFn = opts.getFn || copts.getFn;
var modulePath = opts.modulePath || copts.modulePath;
return {
get: function get () {
if (getFn) {
return getFn(this.$store.state, modelValue, stateName, modulePath)
}
if (modulePath) {
var paths = modulePath.split('/') || [];
var result;
try {
result = paths.reduce(function (r, c) {
return r[c]
}, this.$store.state);
result = result[stateName];
} catch (e) {
if (process.env.NODE_ENV === 'development') {
throw e
}
result = undefined;
}
return result
}
return this.$store.state[stateName]
},
set: function set (value) {
var mutation = setWithPayload ? ( obj = {}, obj[stateName] = value, obj ) : value;
var obj;
var _type = modulePath ? (modulePath + "/" + type) : type;
this.$store.commit(_type, mutation, modulePath ? opts.param || copts.param : undefined);
}
}
};
var _mapStateModelValuesInStrict = function () {
var args = arguments;
var setWithPayload = pop.call(args);
var result = {};
if (Array.isArray(args[0])) {
var opts = args[1];
args[0].forEach(function (item) {
result[item[0]] = _mapStateModelValueInStrict(item[0], item[1], item[2], item[3], setWithPayload, opts);
});
} else {
result[args[0]] = _mapStateModelValueInStrict(args[0], args[1], args[2], args[3], setWithPayload);
}
return result
};
// mapStateModelValuesInStrict(modelValue, stateName, type, {getFn, setWithPayload, modulePath}})
// mapStateModelValuesInStrict([[modelValue, stateName, type, {getFn1}], [modelValue, stateName, type]], {getFn, setWithPayload})
var mapStateModelValuesInStrictWithPayload = function () {
var args = arguments;
push.call(arguments, true);
return _mapStateModelValuesInStrict.apply(null, args)
};
var mapStateModelValuesInStrict = function () {
var args = arguments;
push.call(arguments, false);
return _mapStateModelValuesInStrict.apply(null, args)
};
var index = {
mapStateModelValuesInStrict: mapStateModelValuesInStrict,
mapStateModelValuesInStrictWithPayload: mapStateModelValuesInStrictWithPayload,
version: '0.0.4'
};
module.exports = index;
|
// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `angular-cli.json`.
// The file contents for the current environment will overwrite these during build.
export var environment = {
production: false
};
//# sourceMappingURL=C:/Old/Hadron/HadronClient/src/environments/environment.js.map |
var namespace_pathfinder_1_1_internal_1_1_g_u_i =
[
[ "ModExtensionsUI", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_extensions_u_i.html", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_extensions_u_i" ],
[ "ModList", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_list.html", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_list" ]
]; |
// Karma configuration
// Generated on Wed Jun 01 2016 16:04:37 GMT-0400 (EDT)
module.exports = function (config) {
config.set({
basePath: '',
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'browserify'],
// include only tests here; browserify will find the rest
files: [
'test/**/*-spec.+(js|jsx)'
],
exclude: [],
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/**/*-spec.+(js|jsx)': ['browserify']
},
browserify: {
debug: true,
transform: ['babelify'],
extensions: ['.js', '.jsx'],
// needed for enzyme
configure: function (bundle) {
bundle.on('prebundle', function () {
bundle.external('react/addons');
bundle.external('react/lib/ReactContext');
bundle.external('react/lib/ExecutionEnvironment');
});
}
},
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: false,
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// how many browser should be started simultaneous
concurrency: Infinity
})
};
|
import 'babel-polyfill';
import EdgeGrid from 'edgegrid';
import dotenv from 'dotenv';
import inquirer from 'inquirer';
import formatJson from 'format-json';
import fs from 'fs';
(async function() {
// load .env vars
dotenv.config();
let papiResponses = new Map();
const edgegrid = new EdgeGrid({
path: process.env.AKA_EDGERC,
section: 'default'
});
let contractId = await papiChoice(
'Select Akamai contract:',
'/papi/v1/contracts',
'contracts', 'contractId', 'contractTypeName'
);
let groupId = await papiChoice(
'Select Akamai property group:',
'/papi/v1/groups/?contractId=' + contractId,
'groups', 'groupId', 'groupName'
);
let propertyId = await papiChoice(
'Select Akamai property:',
'/papi/v1/properties/?contractId=' + contractId + '&groupId=' + groupId,
'properties', 'propertyId', 'propertyName'
);
let latestVersion = papiResponses.get('properties').properties.items.filter((property) => {
return property.propertyId === propertyId;
})[0].latestVersion;
// request property version
let version = await inquirer.prompt([
{
type: 'input',
name: 'version',
message: 'The latest property verions is ' + latestVersion + ', which would you like?',
default: latestVersion,
validate: (version) => {
if (parseInt(version) > 0 && parseInt(version) <= latestVersion) {
return true;
} else {
return 'Please enter a valid version number.';
}
}
}
]).then(function (answers) {
console.log('selected version = ' + answers.version);
return answers.version;
});
let propertyJson = await callPapi('property', '/papi/v1/properties/' +
propertyId + '/versions/' + version +
'/rules?contractId=' + contractId + '&groupId=' + groupId).then((data) => {
return data;
});
let propertyName = papiResponses.get('properties').properties.items.filter((property) => {
return property.propertyId === propertyId;
})[0].propertyName;
await inquirer.prompt([
{
type: 'confirm',
name: 'outputToFile',
message: 'Output property ' + propertyName + ' v' + version + ' json to file now?',
default: true,
}
]).then(function (answers) {
console.log('selected outputToFile = ' + answers.outputToFile);
if (answers.outputToFile) {
let outputDir = __dirname + '/../papiJson';
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
fs.writeFileSync(
outputDir + '/' + propertyName + '-v' + version + '.papi.json',
formatJson.plain(propertyJson), 'utf8'
);
console.log('\npapi json written to: ./papiJson/' + propertyName + '-v' + version + '.papi.json');
}
});
console.log(
'\n# ---------------------------------------------------------\n' +
'# place the following in .env or set as shell/node env vars\n' +
'# if you would like to use these parameters to configure nginx directly\n' +
'# from api calls - otherwise point at the generated papi json.\n' +
'# refer to start.js and start-local.js\n' +
'AKA_CONTRACT_ID=' + contractId + '\n' +
'AKA_GROUP_ID=' + groupId + '\n' +
'AKA_PROPERTY_ID=' + propertyId + '\n' +
'AKA_PROPERTY_VERSION=' + version + '\n'
);
async function papiChoice(message, papiUrl, containerField, valueField, nameField) {
let choices = await callPapi(containerField, papiUrl).then((data) => {
return data[containerField].items.map((item) => {
let choice = {};
choice.name = item[valueField] + ' ' + item[nameField];
choice.value = item[valueField];
return choice;
});
});
return await inquirer.prompt([
{
type: 'list',
name: valueField,
message: message,
paginated: true,
choices: choices
}
]).then(function (answers) {
console.log('selected ' + valueField + ' = ' + answers[valueField]);
return answers[valueField];
});
}
async function callPapi(type, papiUrl) {
return new Promise(
(resolve, reject) => {
console.log('calling papi url: ' + papiUrl + '\n');
edgegrid.auth({
path: papiUrl,
method: 'GET'
}).send((error, response, body) => {
if (error) {
return reject(error);
}
let jsonResult = JSON.parse(body);
papiResponses.set(type, jsonResult);
return resolve(jsonResult);
});
});
}
})(); |
export default {
Control : require('./Control'),
Delete : require('./Delete'),
Detail : require('./Detail'),
Head : require('./Head'),
Quit : require('./Quit'),
}; |
$(function() {
// column select
dw.backend.on('sync-option:base-color', sync);
function sync(args) {
var chart = args.chart,
vis = args.vis,
theme_id = chart.get('theme'),
labels = getLabels(),
$el = $('#'+args.key),
$picker = $('.base-color-picker', $el);
if (dw.theme(theme_id)) themesAreReady();
else dw.backend.one('theme-loaded', themesAreReady);
function themesAreReady() {
var theme = dw.theme(theme_id);
if (!args.option.hideBaseColorPicker) initBaseColorPicker();
if (!args.option.hideCustomColorSelector) initCustomColorSelector();
/*
* initializes the base color dropdown
*/
function initBaseColorPicker() {
var curColor = chart.get('metadata.visualize.'+args.key, 0);
if (!_.isString(curColor)) curColor = theme.colors.palette[curColor];
// update base color picker
$picker
.css('background', curColor)
.click(function() {
$picker.colorselector({
color: curColor,
palette: [].concat(theme.colors.palette, theme.colors.secondary),
change: baseColorChanged
});
});
function baseColorChanged(color) {
$picker.css('background', color);
var palIndex = theme.colors.palette.join(',')
.toLowerCase()
.split(',')
.indexOf(color);
chart.set(
'metadata.visualize.'+args.key,
palIndex < 0 ? color : palIndex
);
curColor = color;
}
}
/*
* initializes the custom color dialog
*/
function initCustomColorSelector() {
var labels = getLabels(),
sel = chart.get('metadata.visualize.custom-colors', {}),
$head = $('.custom-color-selector-head', $el),
$body = $('.custom-color-selector-body', $el),
$customColorBtn = $('.custom', $head),
$labelUl = $('.dataseries', $body),
$resetAll = $('.reset-all-colors', $body);
if (_.isEmpty(labels)) {
$head.hide();
return;
}
$head.show();
$customColorBtn.click(function(e) {
e.preventDefault();
$body.toggle();
$customColorBtn.toggleClass('active');
});
$resetAll.click(resetAllColors);
// populate custom color selector
$.each(labels, addLabelToList);
$('.select-all', $body).click(function() {
$('li', $labelUl).addClass('selected');
customColorSelectSeries();
});
$('.select-none', $body).click(function() {
$('li', $labelUl).removeClass('selected');
customColorSelectSeries();
});
$('.select-invert', $body).click(function() {
$('li', $labelUl).toggleClass('selected');
customColorSelectSeries();
});
function addLabelToList(i, lbl) {
var s = lbl;
if (_.isArray(lbl)) {
s = lbl[0];
lbl = lbl[1];
}
var li = $('<li data-series="'+s+'"></li>')
.append('<div class="color">×</div><label>'+lbl+'</label>')
.appendTo($labelUl)
.click(click);
if (sel[s]) {
$('.color', li).html('').css('background', sel[s]);
li.data('color', sel[s]);
}
function click(e) {
if (!e.shiftKey) $('li', $labelUl).removeClass('selected');
if (e.shiftKey && li.hasClass('selected')) li.removeClass('selected');
else li.addClass('selected');
customColorSelectSeries();
if (e.shiftKey) { // clear selection
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
}
}
}
// called whenever the user selects a new series
function customColorSelectSeries() {
var li = $('li.selected', $labelUl),
$colPicker = $('.color-picker', $body),
$reset = $('.reset-color', $body);
if (li.length > 0) {
$('.info', $body).hide();
$('.select', $body).show();
$colPicker.click(function() {
$colPicker.colorselector({
color: li.data('color'),
palette: [].concat(theme.colors.palette, theme.colors.secondary),
change: function(color) {
$colPicker.css('background', color);
update(color);
}
});
}).css('background', li.data('color') || '#fff');
$reset.off('click').on('click', reset);
} else {
$('.info', $body).show();
$('.select', $body).hide();
}
// set a new color and save
function update(color) {
var sel = $.extend({}, chart.get('metadata.visualize.custom-colors', {}));
$('.color', li)
.css('background', color)
.html('');
li.data('color', color);
li.each(function(i, el) {
sel[$(el).data('series')] = color;
});
chart.set('metadata.visualize.custom-colors', sel);
}
// reset selected colors and save
function reset() {
var sel = $.extend({}, chart.get('metadata.visualize.custom-colors', {}));
li.data('color', undefined);
$('.color', li)
.css('background', '')
.html('×');
li.each(function(i, li) {
sel[$(li).data('series')] = '';
});
chart.set('metadata.visualize.custom-colors', sel);
$colPicker.css('background', '#fff');
}
}
function resetAllColors() {
$('li .color', $labelUl).html('×').css('background', '');
$('li', $labelUl).data('color', undefined);
$('.color-picker', $body).css('background', '#fff');
chart.set('metadata.visualize.custom-colors', {});
}
}
}
function getLabels() {
return args.option.axis && vis.axes(true)[args.option.axis] ?
_.unique(vis.axes(true)[args.option.axis].values()) :
(vis.colorKeys ? vis.colorKeys() : vis.keys());
}
}
});
|
import Game from '../models/game'
class Store {
constructor() {
const game = new Game({
onTick: () => {
this.ui.game.update()
}
})
const { snake, map } = game
this.snake = snake
this.map = map
this.game = game
game.start()
this.ui = {}
this.data = {
map,
paused: false
}
}
turnUp = () => {
this.snake.turnUp()
}
turnRight = () => {
this.snake.turnRight()
}
turnDown = () => {
this.snake.turnDown()
}
turnLeft = () => {
this.snake.turnLeft()
}
pauseOrPlay = () => {
if (this.game.paused) {
this.game.play()
this.data.paused = false
} else {
this.game.pause()
this.data.paused = true
}
this.ui.index.updateSelf()
}
reset = () => {
this.game.reset()
}
toggleSpeed = () => {
this.game.toggleSpeed()
}
}
export default new Store |
(function () {
'use strict';
angular.module('app.layout', ['app.core', 'ui.bootstrap.collapse']);
})();
|
/**
* @class Oskari.mapframework.bundle.layerselector2.view.PublishedLayersTab
*
*/
Oskari.clazz.define("Oskari.mapframework.bundle.layerselector2.view.PublishedLayersTab",
/**
* @method create called automatically on construction
* @static
*/
function (instance, title) {
//"use strict";
this.instance = instance;
this.title = title;
this.layerGroups = [];
this.layerContainers = {};
this._createUI();
}, {
getTitle: function () {
//"use strict";
return this.title;
},
getTabPanel: function () {
//"use strict";
return this.tabPanel;
},
getState: function () {
//"use strict";
var state = {
tab: this.getTitle(),
filter: this.filterField.getValue(),
groups: []
};
// TODO: groups listing
/*
var layerGroups = jQuery(this.container).find('div.layerList div.layerGroup.open');
for(var i=0; i < layerGroups.length; ++i) {
var group = layerGroups[i];
state.groups.push(jQuery(group).find('.groupName').text());
}*/
return state;
},
setState: function (state) {
//"use strict";
if (!state) {
return;
}
if (!state.filter) {
this.filterField.setValue(state.filter);
this.filterLayers(state.filter);
}
/* TODO: should open panels in this.accordion where groups[i] == panel.title
if (state.groups && state.groups.length > 0) {
}
*/
},
_createUI: function () {
//"use strict";
var me = this;
me.tabPanel = Oskari.clazz.create('Oskari.userinterface.component.TabPanel');
me.tabPanel.setTitle(this.title);
me.tabPanel.setSelectionHandler(function (wasSelected) {
if (wasSelected) {
me.tabSelected();
} else {
me.tabUnselected();
}
});
me.tabPanel.getContainer().append(this.getFilterField().getField());
me.accordion = Oskari.clazz.create('Oskari.userinterface.component.Accordion');
me.accordion.insertTo(this.tabPanel.getContainer());
},
getFilterField: function () {
//"use strict";
if (this.filterField) {
return this.filterField;
}
var me = this,
field = Oskari.clazz.create('Oskari.userinterface.component.FormInput');
field.setPlaceholder(me.instance.getLocalization('filter').text);
field.addClearButton();
field.bindChange(function (event) {
me._searchTrigger(field.getValue());
}, true);
field.bindEnterKey(function (event) {
me._relatedSearchTrigger(field.getValue());
});
this.filterField = field;
return field;
},
_searchTrigger: function (keyword) {
//"use strict";
var me = this;
// clear any previous search if search field changes
if (me.searchTimer) {
clearTimeout(me.searchTimer);
}
// if field is was cleared -> do immediately
if (!keyword || keyword.length === 0) {
me._search(keyword);
} else {
// else use a small timeout to see if user is typing more
me.searchTimer = setTimeout(function () {
me._search(keyword);
me.searchTimer = undefined;
}, 500);
}
},
_relatedSearchTrigger: function (keyword) {
//"use strict";
var me = this;
// clear any previous search if search field changes
if (me.searchTimer) {
clearTimeout(me.searchTimer);
}
// if field is was cleared -> do immediately
/* TODO!
if (!keyword || keyword.length === 0) {
me._search(keyword);
}*/
},
tabSelected: function () {
//"use strict";
// update data if now done so yet
if (this.layerGroups.length === 0) {
this.accordion.showMessage(this.instance.getLocalization('loading'));
var me = this,
ajaxUrl = this.instance.sandbox.getAjaxUrl();
jQuery.ajax({
type: "GET",
dataType: 'json',
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
url: ajaxUrl + 'action_route=GetPublishedMyPlaceLayers',
success: function (pResp) {
me._populateLayerGroups(pResp);
me.showLayerGroups(me.layerGroups);
},
error: function (jqXHR, textStatus) {
var loc = me.instance.getLocalization('errors');
me.accordion.showMessage(loc.generic);
}
});
}
},
tabUnselected: function () {
//"use strict";
},
/**
* @method _getLayerGroups
* @private
*/
_populateLayerGroups: function (jsonResponse) {
//"use strict";
var me = this,
sandbox = me.instance.getSandbox(),
mapLayerService = sandbox.getService('Oskari.mapframework.service.MapLayerService'),
userUuid = sandbox.getUser().getUuid(),
group = null,
n,
groupJSON,
i,
layerJson,
layer;
this.layerGroups = [];
for (n = 0; n < jsonResponse.length; n += 1) {
groupJSON = jsonResponse[n];
if (!group || group.getTitle() !== groupJSON.name) {
group = Oskari.clazz.create("Oskari.mapframework.bundle.layerselector2.model.LayerGroup", groupJSON.name);
this.layerGroups.push(group);
}
for (i = 0; i < groupJSON.layers.length; i += 1) {
layerJson = groupJSON.layers[i];
layer = this._getPublishedLayer(layerJson, mapLayerService, userUuid === groupJSON.id);
layer.setDescription(groupJSON.name); // user name as "subtitle"
group.addLayer(layer);
}
}
},
/**
* @method _getPublishedLayer
* Populates the category based data to the base maplayer json
* @private
* @return maplayer json for the category
*/
_getPublishedLayer: function (jsonResponse, mapLayerService, usersOwnLayer) {
//"use strict";
var baseJson = this._getMapLayerJsonBase(),
layer;
baseJson.wmsUrl = "/karttatiili/myplaces?myCat=" + jsonResponse.id + "&"; // this.instance.conf.wmsUrl
//baseJson.wmsUrl = "/karttatiili/myplaces?myCat=" + categoryModel.getId() + "&";
baseJson.name = jsonResponse.name;
baseJson.id = 'myplaces_' + jsonResponse.id;
if (usersOwnLayer) {
baseJson.permissions = {
"publish": "publication_permission_ok"
};
} else {
baseJson.permissions = {
"publish": "no_publication_permission"
};
}
layer = mapLayerService.createMapLayer(baseJson);
if (!usersOwnLayer) {
// catch exception if the layer is already added to maplayer service
// reloading published layers will crash otherwise
// myplaces bundle will add users own layers so we dont even have to try it
try {
mapLayerService.addLayer(layer);
} catch (ignore) {
// layer already added, ignore
}
}
return layer;
},
/**
* @method _getMapLayerJsonBase
* Returns a base model for maplayer json to create my places map layer
* @private
* @return {Object}
*/
_getMapLayerJsonBase: function () {
//"use strict";
var catLoc = this.instance.getLocalization('published'),
json = {
wmsName: 'ows:my_places_categories',
type: "wmslayer",
isQueryable: true,
opacity: 50,
metaType: 'published',
orgName: catLoc.organization,
inspire: catLoc.inspire
};
return json;
},
showLayerGroups: function (groups) {
//"use strict";
var me = this,
i,
group,
layers,
groupContainer,
groupPanel,
n,
layer,
layerWrapper,
layerContainer,
loc,
selectedLayers;
me.accordion.removeAllPanels();
me.layerContainers = undefined;
me.layerContainers = {};
me.layerGroups = groups;
for (i = 0; i < groups.length; i += 1) {
group = groups[i];
layers = group.getLayers();
groupPanel = Oskari.clazz.create('Oskari.userinterface.component.AccordionPanel');
groupPanel.setTitle(group.getTitle() + ' (' + layers.length + ')');
group.layerListPanel = groupPanel;
groupContainer = groupPanel.getContainer();
for (n = 0; n < layers.length; n += 1) {
layer = layers[n];
layerWrapper =
Oskari.clazz.create('Oskari.mapframework.bundle.layerselector2.view.Layer',
layer, me.instance.sandbox, me.instance.getLocalization());
layerContainer = layerWrapper.getContainer();
groupContainer.append(layerContainer);
me.layerContainers[layer.getId()] = layerWrapper;
}
me.accordion.addPanel(groupPanel);
}
if (me.layerGroups.length === 0) {
// empty result
loc = me.instance.getLocalization('errors');
me.accordion.showMessage(loc.noResults);
} else {
selectedLayers = me.instance.sandbox.findAllSelectedMapLayers();
for (i = 0; i < selectedLayers.length; i += 1) {
me.setLayerSelected(selectedLayers[i].getId(), true);
}
}
},
/**
* @method _search
* @private
* @param {String} keyword
* keyword to filter layers by
* Shows and hides layers by comparing the given keyword to the text in layer containers layer-keywords div.
* Also checks if all layers in a group is hidden and hides the group as well.
*/
_search: function (keyword) {
//"use strict";
var me = this;
if (!keyword || keyword.length === 0) {
// show all
me.updateLayerContent();
return;
}
// empty previous
me.showLayerGroups([]);
me.accordion.showMessage(this.instance.getLocalization('loading'));
// search
jQuery.ajax({
type: "GET",
dataType: 'json',
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
data: {
searchKey: keyword
},
url: ajaxUrl + 'action_route=FreeFindFromMyPlaceLayers',
success: function (pResp) {
me._populateLayerGroups(pResp);
me.showLayerGroups(me.layerGroups);
},
error: function (jqXHR, textStatus) {
var loc = me.instance.getLocalization('errors');
me.accordion.showMessage(loc.generic);
}
});
// TODO: check if there are no groups visible -> show 'no matches'
// notification?
},
setLayerSelected: function (layerId, isSelected) {
//"use strict";
var layerCont = this.layerContainers[layerId];
if (layerCont) {
layerCont.setSelected(isSelected);
}
},
updateLayerContent: function (layerId, layer) {
//"use strict";
// empty the listing to trigger refresh when this tab is selected again
this.accordion.removeMessage();
this.showLayerGroups([]);
this.tabSelected();
}
}); |
'use strict'; // eslint-disable-line
const { default: ImageminPlugin } = require('imagemin-webpack-plugin');
const imageminMozjpeg = require('imagemin-mozjpeg');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const config = require('./config');
module.exports = {
plugins: [
new ImageminPlugin({
optipng: { optimizationLevel: 7 },
gifsicle: { optimizationLevel: 3 },
pngquant: { quality: '65-90', speed: 4 },
svgo: {
plugins: [
{ removeUnknownsAndDefaults: false },
{ cleanupIDs: false },
{ removeViewBox: false },
],
},
plugins: [imageminMozjpeg({ quality: 75 })],
disable: (config.enabled.watcher),
}),
new UglifyJsPlugin({
uglifyOptions: {
ecma: 8,
compress: {
warnings: true,
drop_console: true,
},
},
}),
],
};
|
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
through = require('through'),
filesize = require('file-size');
function browserify(file, options) {
var source = [];
function write(data) {
source.push(data);
};
function end(file, options) {
var renderTemplate = function(options, stats) {
var si = options.size.representation === 'si',
computedSize = filesize(stats.size, {
fixed: options.size.decimals,
spacer: options.size.spacer
}),
jsonOptions = JSON.stringify(options),
jsonStats = JSON.stringify(stats),
prettySize = (options.size.unit === 'human') ?
computedSize.human({ si: si }) :
computedSize.to(options.size.unit, si),
template = options.output.file.template;
return template.replace('%file%', path.basename(file))
.replace('%fullname%', file)
.replace('%size%', prettySize)
.replace('%stats%', jsonStats)
.replace('%atime%', stats.atime)
.replace('%mtime%', stats.mtime)
.replace('%unit%', options.size.unit)
.replace('%decimals%', options.size.decimals)
.replace('%options%', jsonOptions);
};
var fileStat = function(err, stats) {
if (err) {
console.error('Failure to extract file stats', file, err);
return;
}
if (options.output.file) {
var result = '',
prependHeader = renderTemplate(options, stats);
try {
result = [prependHeader, source.join('')].join('');
} catch (error) {
error.message += ' in "' + file + '"';
this.emit('error', error);
}
this.queue(result);
this.queue(null);
}
}.bind(this);
fs.stat(file, fileStat);
}
return (function transform(file, options) {
var options = _.extend({
size: {
unit: 'human',
decimals: '2',
spacer: ' ',
representation: 'si'
},
output: {
file: {
template: [
'',
'/* =========================== ',
' * > File: %file%',
' * > Size: %size%',
' * > Modified: %mtime%',
' * =========================== */',
''
].join('\n')
}
}
}, options);
return through(_.partial(write), _.partial(end, file, options));
})(file, options);
};
module.exports = {
browserify: browserify
};
|
"use strict";
var filters = require('./filters'),
uniq = require('uniq');
var doNgram = function doNgram (string, resultData, config) {
var ngramCount = string.length - config.n + 1,
ngram,
previousNgram = null,
ngramData,
i;
for (i = 0; i < ngramCount; i++) {
ngram = string.substr(i, config.n);
if (!resultData.elements[ngram]) {
ngramData = resultData.elements[ngram] = {
probabilityAsFirst: 0,
children: {},
lastChildren: {}
};
} else {
ngramData = resultData.elements[ngram];
}
if (i === 0) {
ngramData.probabilityAsFirst++;
}
if (previousNgram !== null) {
if (i === ngramCount - 1) {
if (!previousNgram.lastChildren[ngram]) {
previousNgram.lastChildren[ngram] = 1;
} else {
previousNgram.lastChildren[ngram]++;
}
} else {
if (!previousNgram.children[ngram]) {
previousNgram.children[ngram] = 1;
} else {
previousNgram.children[ngram]++;
}
}
}
previousNgram = ngramData;
}
};
var postProcessData = function postProcessData (resultData, compressFloat) {
var keys = Object.keys(resultData.elements),
childrenKeys,
validFirst = {},
sumFirst = 0,
sumChildren = 0,
key,
data,
i,
k;
for (i = 0; i < keys.length; i++) {
key = keys[i];
data = resultData.elements[key];
if (data.probabilityAsFirst > 0) {
if (!validFirst[key]) {
validFirst[key] = data.probabilityAsFirst;
sumFirst += data.probabilityAsFirst;
} else {
validFirst[key] += data.probabilityAsFirst;
sumFirst += data.probabilityAsFirst;
}
}
delete data.probabilityAsFirst;
childrenKeys = Object.keys(data.children);
sumChildren = 0;
for (k = 0; k < childrenKeys.length; k++) {
sumChildren += data.children[childrenKeys[k]];
}
for (k = 0; k < childrenKeys.length; k++) {
data.children[childrenKeys[k]] /= sumChildren;
data.children[childrenKeys[k]] = compressFloat(data.children[childrenKeys[k]]);
}
data.hasChildren = childrenKeys.length > 0;
childrenKeys = Object.keys(data.lastChildren);
sumChildren = 0;
for (k = 0; k < childrenKeys.length; k++) {
sumChildren += data.lastChildren[childrenKeys[k]];
}
for (k = 0; k < childrenKeys.length; k++) {
data.lastChildren[childrenKeys[k]] /= sumChildren;
data.lastChildren[childrenKeys[k]] = compressFloat(data.lastChildren[childrenKeys[k]]);
}
data.hasLastChildren = childrenKeys.length > 0;
}
keys = Object.keys(validFirst);
for (i = 0; i < keys.length; i++) {
key = keys[i];
validFirst[key] /= sumFirst;
validFirst[key] = compressFloat(validFirst[key]);
}
resultData.firstElements = validFirst;
return resultData;
};
var compact = function compact (resultData) {
var keys = Object.keys(resultData.elements),
ngramData,
ngramDesc,
i;
for (i = 0; i < keys.length; i++) {
ngramData = resultData.elements[keys[i]];
ngramDesc = [
ngramData.hasChildren ? ngramData.children : 0,
ngramData.hasLastChildren ? ngramData.lastChildren : 0
];
resultData.elements[keys[i]] = ngramDesc;
}
resultData.e = resultData.elements;
resultData.fe = resultData.firstElements;
delete resultData.elements;
delete resultData.firstElements;
};
var stringToRegExp = function stringToRegExp (string) {
var match = string.match(/^\/(.+)\/([igmuy]+)$/),
regex = null;
if (match !== null) {
regex = new RegExp(match[1], match[2]);
}
return regex;
};
var preProcessString = function preProcessString (string, config) {
string = string.toLowerCase();
if (config.filter) {
var filterRegex = null;
if (config.filter instanceof RegExp) {
filterRegex = config.filter
} else if (filters.hasOwnProperty(config.filter)) {
filterRegex = filters[config.filter];
} else {
filterRegex = stringToRegExp(config.filter);
}
if (filterRegex) {
string = string.replace(filterRegex, ' ');
}
}
var strings = string.split(/\s+/).filter(function (v) {
return v.length > 0;
});
if (config.minLength) {
strings = strings.filter(function (v) {
return v.length > config.minLength;
});
}
if (config.unique) {
uniq(strings);
}
return strings;
};
/**
* Generate an n-gram model based on a given text
* @param {string} data Text corpus as a single, preferably large, string
* @param {object} config Configuration options
* @param {string} [config.name] Name of the n-gram model, not directly used
* @param {int} [config.n=3] Order of the model (1: unigram, 2: bigram, 3: trigram, ...)
* @param {int} [config.minLength=n] Minimum length of the word considered in the generation of the model
* @param {bool} [config.unique=false] Avoid skewing the generation toward the most repeated words in the text corpus
* @param {bool} [config.compress=false] Reduce the size of the model file, making it slightly less accurate
* @param {bool} [config.excludeOriginal=false] Include the full list of the words considered in the generation so they can be blacklisted
* @param {string|RegExp} [config.filter='extended'] Character filtering option, either one the existing filters (none, alphabetical, numerical, alphaNumerical, extended, extendedNumerical, french, english, oldEnglish, chinese, japanese, noSymbols) or a RegExp object
* @returns {object} N-gram model built from the text corpus
*/
module.exports = function generateModel (data, config) {
config = config || {};
config.name = config.name || null;
config.filter = config.filter || 'extended';
config.n = parseInt(config.n, 10) || 3;
config.minLength = parseInt(config.minLength, 10) || config.n;
config.unique = !!config.unique;
config.excludeOriginal = !!config.excludeOriginal;
config.compress = !!config.compress;
if (config.minLength < config.n) {
throw new Error('N-gram error: The minLength value must be larger than or equal to n');
}
var resultConfig = {
name: config.name,
n: config.n,
minLength: config.minLength,
unique: config.unique ? 1 : 0,
excludeOriginal: config.excludeOriginal ? 1 : 0
};
var resultData = {
elements: {}
};
var excludeData = [];
var strings = preProcessString(data, config);
for (var i = 0; i < strings.length; i++) {
doNgram(strings[i], resultData, config);
if (config.excludeOriginal && excludeData.indexOf(strings[i]) === -1) {
excludeData.push(strings[i]);
}
}
var formatFloat = config.compress ? function compressFloat (float, precision) {
return parseFloat(float.toFixed(precision || 7));
} : function (v) { return v; };
compact(postProcessData(resultData, formatFloat));
return {
config: resultConfig,
data: resultData,
exclude: excludeData.length ? excludeData : 0
};
};
|
var Models = {};
module.exports = Models;
/**
* Creates a new instance of the Model class
* @constructor
*/
Models.Model = function(id, name, status, type, normalValue, wierdValue) {
/** @type {string} */
this._id = id || '';
/** @type {string} */
this.name = name || '';
/** @type {string} */
this.status = status || 'disable';
/** @type {string} */
this.type = type || 'normal';
/** @type {number} */
this.normalValue = normalValue || 0;
/** @type {number} */
this.wierdValue = wierdValue || 0;
};
/**
* Creates a new instance of a PublicModel
* @constructor
*/
Models.PublicModel = function(name, value) {
/** @type {string} */
this.name = name || '';
/** @type {number} */
this.value = value || 0;
}; |
/* =============================================================
* bootstrap-collapse.js v2.3.2
* http://getbootstrap.com/2.3.2/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);
|
angular.module('Eintrag').service('editarService', ['$http', function ($http) {
this.editarUsuario = function (data) {
return $http.post('http://localhost/Eintrag/www/server.php/editarUsuario', $.param(data));
};
}]);
|
appService.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'app/view/common/img/ben.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'app/view/common/img/max.png'
}, {
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
face: 'app/view/common/img/adam.jpg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'app/view/common/img/perry.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'app/view/common/img/mike.png'
}];
return {
all: function() {
return chats;
},
remove: function(chat) {
chats.splice(chats.indexOf(chat), 1);
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
}); |
import { AppRegistry } from "react-native";
import App from "./App";
AppRegistry.registerComponent("KeepTheBallGame", () => App);
|
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Tabs, { Tab } from 'material-ui/Tabs';
import PhoneIcon from '@material-ui/icons/Phone';
import FavoriteIcon from '@material-ui/icons/Favorite';
import PersonPinIcon from '@material-ui/icons/PersonPin';
import HelpIcon from '@material-ui/icons/Help';
import ShoppingBasket from '@material-ui/icons/ShoppingBasket';
import ThumbDown from '@material-ui/icons/ThumbDown';
import ThumbUp from '@material-ui/icons/ThumbUp';
import Typography from 'material-ui/Typography';
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 8 * 3 }}>
{props.children}
</Typography>
);
}
TabContainer.propTypes = {
children: PropTypes.node.isRequired,
};
const styles = theme => ({
root: {
flexGrow: 1,
width: '100%',
backgroundColor: theme.palette.background.paper,
},
});
class ScrollableTabsButtonPrevent extends React.Component {
state = {
value: 0,
};
handleChange = (event, value) => {
this.setState({ value });
};
render() {
const { classes } = this.props;
const { value } = this.state;
return (
<div className={classes.root}>
<AppBar position="static">
<Tabs value={value} onChange={this.handleChange} scrollable scrollButtons="off">
<Tab icon={<PhoneIcon />} />
<Tab icon={<FavoriteIcon />} />
<Tab icon={<PersonPinIcon />} />
<Tab icon={<HelpIcon />} />
<Tab icon={<ShoppingBasket />} />
<Tab icon={<ThumbDown />} />
<Tab icon={<ThumbUp />} />
</Tabs>
</AppBar>
{value === 0 && <TabContainer>Item One</TabContainer>}
{value === 1 && <TabContainer>Item Two</TabContainer>}
{value === 2 && <TabContainer>Item Three</TabContainer>}
{value === 3 && <TabContainer>Item Four</TabContainer>}
{value === 4 && <TabContainer>Item Five</TabContainer>}
{value === 5 && <TabContainer>Item Six</TabContainer>}
{value === 6 && <TabContainer>Item Seven</TabContainer>}
</div>
);
}
}
ScrollableTabsButtonPrevent.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ScrollableTabsButtonPrevent);
|
// Actions
export const ADD_NOTIFICATION = 'notifications/ADD_NOTIFICATION'
export const DISMISS_NOTIFICATION = 'notifications/DISMISS_NOTIFICATION'
export const CLEAR_NOTIFICATIONS = 'notifications/CLEAR_NOTIFICATIONS'
// Reducer
export const initialState = []
export default function reducer(state = initialState, action) {
const { payload, type } = action
switch (type) {
case ADD_NOTIFICATION:
return [...state, payload]
case DISMISS_NOTIFICATION:
return state.filter(notification => notification.id !== payload)
case CLEAR_NOTIFICATIONS:
return [state]
default:
return state
}
}
// Action Creators
export function addNotification(notification) {
const { id, dismissAfter } = notification
if (!id) {
notification.id = new Date().getTime()
}
return (dispatch, getState) => {
dispatch({ type: ADD_NOTIFICATION, payload: notification })
if (dismissAfter) {
setTimeout(() => {
const { notifications } = getState()
const found = notifications.find(lookup => {
return lookup.id === notification.id
})
if (found) {
dispatch({ type: DISMISS_NOTIFICATION, payload: notification.id })
}
}, dismissAfter)
}
}
}
export function dismissNotification(id) {
return { type: DISMISS_NOTIFICATION, payload: id }
}
export function clearNotifications(id) {
return { type: CLEAR_NOTIFICATIONS, payload: id }
}
|
var rarities = {
'Common': {
name: 'Common',
level_prop: 'MultiplierQ1'
},
'Rare': {
name: 'Rare',
level_prop: 'MultiplierQ2'
},
'Epic': {
name: 'Epic',
level_prop: 'MultiplierQ3'
},
'Legendary': {
name: 'Legendary',
level_prop: 'MultiplierQ4'
},
'Mythic': {
name: 'Mythic',
level_prop: 'MultiplierQ5'
}
};
var base_hero_stats = {
"Abomination" : {
"name" : "Abomination",
"hero_type" : "Melee",
"melee" : 2,
"ranged" : 6,
"mystic" : 7,
"total" : 15,
"health" : 150,
"dmg" : 22.7123890987738,
"armor" : 20
},
"Assassin" : {
"name" : "Assassin",
"hero_type" : "Ranged",
"melee" : 5,
"ranged" : 3,
"mystic" : 2,
"total" : 10,
"health" : 100,
"dmg" : 32.5,
"armor" : 50
},
"Berzerker" : {
"name" : "Berzerker",
"hero_type" : "Melee",
"melee" : 3,
"ranged" : 4,
"mystic" : 3,
"total" : 10,
"health" : 150,
"dmg" : 13.679744,
"armor" : 45
},
"Carnifex" : {
"name" : "Carnifex",
"hero_type" : "Melee",
"melee" : 3,
"ranged" : 4,
"mystic" : 4,
"total" : 11,
"health" : 100,
"dmg" : 32.29285,
"armor" : 5
},
"Demon" : {
"name" : "Demon",
"hero_type" : "Mystic",
"melee" : 6,
"ranged" : 1,
"mystic" : 2,
"total" : 9,
"health" : 250,
"dmg" : 12.5,
"armor" : 2
},
"Frostmage" : {
"name" : "Frostmage",
"hero_type" : "Ranged",
"melee" : 5,
"ranged" : 2,
"mystic" : 5,
"total" : 12,
"health" : 135,
"dmg" : 8,
"armor" : 10
},
"Ghoul" : {
"name" : "Ghoul",
"hero_type" : "Melee",
"melee" : 3,
"ranged" : 4,
"mystic" : 4,
"total" : 11,
"health" : 120,
"dmg" : 12.5,
"armor" : 10
},
"Gladiator" : {
"name" : "Gladiator",
"hero_type" : "Melee",
"melee" : 5,
"ranged" : 4,
"mystic" : 3,
"total" : 12,
"health" : 130,
"dmg" : 20,
"armor" : 30
},
"Gnoll Brute" : {
"name" : "Gnoll Brute",
"hero_type" : "Melee",
"melee" : 6,
"ranged" : 2,
"mystic" : 1,
"total" : 9,
"health" : 145,
"dmg" : 15,
"armor" : 40
},
"Gnoll Marksman" : {
"name" : "Gnoll Marksman",
"hero_type" : "Ranged",
"melee" : 5,
"ranged" : 4,
"mystic" : 5,
"total" : 14,
"health" : 110,
"dmg" : 48,
"armor" : 15
},
"Grim Warrior" : {
"name" : "Grim Warrior",
"hero_type" : "Melee",
"melee" : 5,
"ranged" : 3,
"mystic" : 5,
"total" : 13,
"health" : 180,
"dmg" : 19.5,
"armor" : 25
},
"Guardian" : {
"name" : "Guardian",
"hero_type" : "Melee",
"melee" : 2,
"ranged" : 7,
"mystic" : 1,
"total" : 10,
"health" : 145,
"dmg" : 22.684415,
"armor" : 160
},
"Huntress" : {
"name" : "Huntress",
"hero_type" : "Ranged",
"melee" : 3,
"ranged" : 4,
"mystic" : 7,
"total" : 14,
"health" : 110,
"dmg" : 27.26496,
"armor" : 20
},
"Marauder" : {
"name" : "Marauder",
"hero_type" : "Melee",
"melee" : 4,
"ranged" : 3,
"mystic" : 6,
"total" : 13,
"health" : 125,
"dmg" : 40,
"armor" : 10
},
"Monk" : {
"name" : "Monk",
"hero_type" : "Mystic",
"melee" : 4,
"ranged" : 6,
"mystic" : 2,
"total" : 12,
"health" : 110,
"dmg" : 20.336064,
"armor" : 4
},
"Necromancer" : {
"name" : "Necromancer",
"hero_type" : "Mystic",
"melee" : 3,
"ranged" : 3,
"mystic" : 3,
"total" : 9,
"health" : 90,
"dmg" : 6,
"armor" : 10
},
"Ogre" : {
"name" : "Ogre",
"hero_type" : "Melee",
"melee" : 6,
"ranged" : 2,
"mystic" : 2,
"total" : 10,
"health" : 350,
"dmg" : 45.64432,
"armor" : 25
},
"Paladin" : {
"name" : "Paladin",
"hero_type" : "Melee",
"melee" : 5,
"ranged" : 3,
"mystic" : 2,
"total" : 10,
"health" : 220,
"dmg" : 11,
"armor" : 100
},
"Rogue" : {
"name" : "Rogue",
"hero_type" : "Mystic",
"melee" : 4,
"ranged" : 7,
"mystic" : 4,
"total" : 15,
"health" : 125,
"dmg" : 26.6664,
"armor" : 50
},
"Sasquatch" : {
"name" : "Sasquatch",
"hero_type" : "Mystic",
"melee" : 2,
"ranged" : 3,
"mystic" : 7,
"total" : 12,
"health" : 180,
"dmg" : 13.6797,
"armor" : 20
},
"Shambler" : {
"name" : "Shambler",
"hero_type" : "Melee",
"melee" : 4,
"ranged" : 3,
"mystic" : 3,
"total" : 10,
"health" : 400,
"dmg" : 8.5,
"armor" : 5
},
"Skirmisher" : {
"name" : "Skirmisher",
"hero_type" : "Ranged",
"melee" : 5,
"ranged" : 5,
"mystic" : 1,
"total" : 11,
"health" : 110,
"dmg" : 15,
"armor" : 30
},
"Sorceress" : {
"name" : "Sorceress",
"hero_type" : "Mystic",
"melee" : 3,
"ranged" : 3,
"mystic" : 4,
"total" : 10,
"health" : 110,
"dmg" : 5,
"armor" : 10
},
"Valkyrie" : {
"name" : "Valkyrie",
"hero_type" : "Melee",
"melee" : 6,
"ranged" : 5,
"mystic" : 1,
"total" : 12,
"health" : 200,
"dmg" : 10,
"armor" : 257
},
"Warlock" : {
"name" : "Warlock",
"hero_type" : "Mystic",
"melee" : 1,
"ranged" : 5,
"mystic" : 4,
"total" : 10,
"health" : 120,
"dmg" : 17.5,
"armor" : 5
},
"Wraith" : {
"name" : "Wraith",
"hero_type" : "Mystic",
"melee" : 1,
"ranged" : 4,
"mystic" : 6,
"total" : 11,
"health" : 105,
"dmg" : 15,
"armor" : 10
}
};
var hero_levels = [
{"Id":"0","Evolution":0,"NextLevelXp":100,"XpPerFight":100,"DamageMultiplier":"4096","HealthMultiplier":"4096","ArmorMultiplier":"4096","ActiveSkillLevel":0,"MultiplierQ1":"4096","MultiplierQ2":"4792","MultiplierQ3":"5693","MultiplierQ4":"7332","MultiplierQ5":"9380","PassiveSkill1Level":0,"PassiveSkill2Level":0,"SacrificeCost":140,"LootGold":50,"LootResources":1,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"1","Evolution":0,"NextLevelXp":200,"XpPerFight":100,"DamageMultiplier":"4710","HealthMultiplier":"4710","ArmorMultiplier":"4710","ActiveSkillLevel":0,"MultiplierQ1":"4096","MultiplierQ2":"4833","MultiplierQ3":"5816","MultiplierQ4":"7496","MultiplierQ5":"9667","PassiveSkill1Level":0,"PassiveSkill2Level":0,"SacrificeCost":240,"LootGold":55,"LootResources":1,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"2","Evolution":0,"NextLevelXp":320,"XpPerFight":100,"DamageMultiplier":"5325","HealthMultiplier":"5325","ArmorMultiplier":"5325","ActiveSkillLevel":1,"MultiplierQ1":"4096","MultiplierQ2":"4915","MultiplierQ3":"5939","MultiplierQ4":"7700","MultiplierQ5":"9953","PassiveSkill1Level":0,"PassiveSkill2Level":0,"SacrificeCost":380,"LootGold":60,"LootResources":1,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"3","Evolution":0,"NextLevelXp":470,"XpPerFight":100,"DamageMultiplier":"5734","HealthMultiplier":"5734","ArmorMultiplier":"5734","ActiveSkillLevel":1,"MultiplierQ1":"4096","MultiplierQ2":"4956","MultiplierQ3":"6062","MultiplierQ4":"7864","MultiplierQ5":"10240","PassiveSkill1Level":0,"PassiveSkill2Level":0,"SacrificeCost":520,"LootGold":65,"LootResources":1,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"4","Evolution":0,"NextLevelXp":650,"XpPerFight":100,"DamageMultiplier":"6349","HealthMultiplier":"6349","ArmorMultiplier":"6349","ActiveSkillLevel":1,"MultiplierQ1":"4096","MultiplierQ2":"5038","MultiplierQ3":"6226","MultiplierQ4":"8069","MultiplierQ5":"10568","PassiveSkill1Level":1,"PassiveSkill2Level":0,"SacrificeCost":760,"LootGold":70,"LootResources":1,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"5","Evolution":0,"NextLevelXp":850,"XpPerFight":100,"DamageMultiplier":"6963","HealthMultiplier":"6963","ArmorMultiplier":"6963","ActiveSkillLevel":1,"MultiplierQ1":"4096","MultiplierQ2":"5120","MultiplierQ3":"6349","MultiplierQ4":"8274","MultiplierQ5":"10854","PassiveSkill1Level":1,"PassiveSkill2Level":0,"SacrificeCost":940,"LootGold":74,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"6","Evolution":0,"NextLevelXp":1000,"XpPerFight":100,"DamageMultiplier":"8192","HealthMultiplier":"8192","ArmorMultiplier":"8192","ActiveSkillLevel":1,"MultiplierQ1":"4096","MultiplierQ2":"5202","MultiplierQ3":"6472","MultiplierQ4":"8479","MultiplierQ5":"11182","PassiveSkill1Level":1,"PassiveSkill2Level":1,"SacrificeCost":1160,"LootGold":78,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"7","Evolution":0,"NextLevelXp":1150,"XpPerFight":100,"DamageMultiplier":"9011","HealthMultiplier":"9011","ArmorMultiplier":"9011","ActiveSkillLevel":1,"MultiplierQ1":"4096","MultiplierQ2":"5243","MultiplierQ3":"6595","MultiplierQ4":"8684","MultiplierQ5":"11510","PassiveSkill1Level":1,"PassiveSkill2Level":1,"SacrificeCost":1400,"LootGold":81,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"8","Evolution":0,"NextLevelXp":1270,"XpPerFight":100,"DamageMultiplier":"9994","HealthMultiplier":"9994","ArmorMultiplier":"9994","ActiveSkillLevel":2,"MultiplierQ1":"4096","MultiplierQ2":"5325","MultiplierQ3":"6758","MultiplierQ4":"8888","MultiplierQ5":"11878","PassiveSkill1Level":1,"PassiveSkill2Level":1,"SacrificeCost":1700,"LootGold":83,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"9","Evolution":1,"NextLevelXp":1380,"XpPerFight":100,"DamageMultiplier":"11469","HealthMultiplier":"11469","ArmorMultiplier":"11469","ActiveSkillLevel":2,"MultiplierQ1":"4096","MultiplierQ2":"5407","MultiplierQ3":"6881","MultiplierQ4":"9093","MultiplierQ5":"12247","PassiveSkill1Level":1,"PassiveSkill2Level":1,"SacrificeCost":2000,"LootGold":85,"LootResources":2,"EvolutionRequirementsQ1":"quantity:1;","EvolutionRequirementsQ2":"quantity:2;","EvolutionRequirementsQ3":"quantity:1;quality:1;","EvolutionRequirementsQ4":"quantity:1;quality:2;","EvolutionRequirementsQ5":"quantity:2;quality:2;"},
{"Id":"10","Evolution":1,"NextLevelXp":1594,"XpPerFight":100,"DamageMultiplier":"12698","HealthMultiplier":"12698","ArmorMultiplier":"12698","ActiveSkillLevel":2,"MultiplierQ1":"4096","MultiplierQ2":"5489","MultiplierQ3":"7045","MultiplierQ4":"9339","MultiplierQ5":"12575","PassiveSkill1Level":2,"PassiveSkill2Level":1,"SacrificeCost":2400,"LootGold":87,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"11","Evolution":1,"NextLevelXp":1689,"XpPerFight":100,"DamageMultiplier":"13312","HealthMultiplier":"13312","ArmorMultiplier":"13312","ActiveSkillLevel":2,"MultiplierQ1":"4096","MultiplierQ2":"5571","MultiplierQ3":"7168","MultiplierQ4":"9544","MultiplierQ5":"12984","PassiveSkill1Level":2,"PassiveSkill2Level":1,"SacrificeCost":2900,"LootGold":89,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"12","Evolution":1,"NextLevelXp":1791,"XpPerFight":100,"DamageMultiplier":"13926","HealthMultiplier":"13926","ArmorMultiplier":"13926","ActiveSkillLevel":2,"MultiplierQ1":"4096","MultiplierQ2":"5652","MultiplierQ3":"7332","MultiplierQ4":"9789","MultiplierQ5":"13353","PassiveSkill1Level":2,"PassiveSkill2Level":2,"SacrificeCost":3400,"LootGold":91,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"13","Evolution":1,"NextLevelXp":1898,"XpPerFight":100,"DamageMultiplier":"14950","HealthMultiplier":"14950","ArmorMultiplier":"14950","ActiveSkillLevel":2,"MultiplierQ1":"4096","MultiplierQ2":"5734","MultiplierQ3":"7496","MultiplierQ4":"10035","MultiplierQ5":"13763","PassiveSkill1Level":2,"PassiveSkill2Level":2,"SacrificeCost":3800,"LootGold":93,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"14","Evolution":1,"NextLevelXp":2012,"XpPerFight":100,"DamageMultiplier":"15974","HealthMultiplier":"15974","ArmorMultiplier":"15974","ActiveSkillLevel":3,"MultiplierQ1":"4096","MultiplierQ2":"5816","MultiplierQ3":"7660","MultiplierQ4":"10281","MultiplierQ5":"14172","PassiveSkill1Level":2,"PassiveSkill2Level":2,"SacrificeCost":4400,"LootGold":94,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"15","Evolution":1,"NextLevelXp":2133,"XpPerFight":100,"DamageMultiplier":"16998","HealthMultiplier":"16998","ArmorMultiplier":"16998","ActiveSkillLevel":3,"MultiplierQ1":"4096","MultiplierQ2":"5898","MultiplierQ3":"7782","MultiplierQ4":"10527","MultiplierQ5":"14582","PassiveSkill1Level":2,"PassiveSkill2Level":2,"SacrificeCost":5200,"LootGold":95,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"16","Evolution":1,"NextLevelXp":2261,"XpPerFight":100,"DamageMultiplier":"18022","HealthMultiplier":"18022","ArmorMultiplier":"18022","ActiveSkillLevel":3,"MultiplierQ1":"4096","MultiplierQ2":"5980","MultiplierQ3":"7946","MultiplierQ4":"10772","MultiplierQ5":"15032","PassiveSkill1Level":3,"PassiveSkill2Level":2,"SacrificeCost":6000,"LootGold":96,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"17","Evolution":1,"NextLevelXp":2397,"XpPerFight":100,"DamageMultiplier":"19046","HealthMultiplier":"19046","ArmorMultiplier":"19046","ActiveSkillLevel":3,"MultiplierQ1":"4096","MultiplierQ2":"6062","MultiplierQ3":"8151","MultiplierQ4":"11059","MultiplierQ5":"15483","PassiveSkill1Level":3,"PassiveSkill2Level":2,"SacrificeCost":7000,"LootGold":97,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"18","Evolution":1,"NextLevelXp":2540,"XpPerFight":100,"DamageMultiplier":"20070","HealthMultiplier":"20070","ArmorMultiplier":"20070","ActiveSkillLevel":3,"MultiplierQ1":"4096","MultiplierQ2":"6144","MultiplierQ3":"8315","MultiplierQ4":"11305","MultiplierQ5":"15974","PassiveSkill1Level":3,"PassiveSkill2Level":3,"SacrificeCost":8400,"LootGold":98,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"19","Evolution":2,"NextLevelXp":2693,"XpPerFight":100,"DamageMultiplier":"21094","HealthMultiplier":"21094","ArmorMultiplier":"21094","ActiveSkillLevel":3,"MultiplierQ1":"4096","MultiplierQ2":"6226","MultiplierQ3":"8479","MultiplierQ4":"11592","MultiplierQ5":"16425","PassiveSkill1Level":3,"PassiveSkill2Level":3,"SacrificeCost":10000,"LootGold":99,"LootResources":2,"EvolutionRequirementsQ1":"quantity:1;level:4;","EvolutionRequirementsQ2":"quantity:2;level:4;","EvolutionRequirementsQ3":"quantity:1;quality:1;level:4;","EvolutionRequirementsQ4":"quantity:1;quality:2;level:4;","EvolutionRequirementsQ5":"quantity:2;quality:2;level:4;"},
{"Id":"20","Evolution":2,"NextLevelXp":2854,"XpPerFight":100,"DamageMultiplier":"22118","HealthMultiplier":"22118","ArmorMultiplier":"22118","ActiveSkillLevel":4,"MultiplierQ1":"4096","MultiplierQ2":"6308","MultiplierQ3":"8643","MultiplierQ4":"11878","MultiplierQ5":"16916","PassiveSkill1Level":3,"PassiveSkill2Level":3,"SacrificeCost":11600,"LootGold":100,"LootResources":2,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"21","Evolution":2,"NextLevelXp":3026,"XpPerFight":100,"DamageMultiplier":"23142","HealthMultiplier":"23142","ArmorMultiplier":"23142","ActiveSkillLevel":4,"MultiplierQ1":"4096","MultiplierQ2":"6390","MultiplierQ3":"8847","MultiplierQ4":"12165","MultiplierQ5":"17449","PassiveSkill1Level":3,"PassiveSkill2Level":3,"SacrificeCost":14000,"LootGold":101,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"22","Evolution":2,"NextLevelXp":3207,"XpPerFight":100,"DamageMultiplier":"24166","HealthMultiplier":"24166","ArmorMultiplier":"24166","ActiveSkillLevel":4,"MultiplierQ1":"4096","MultiplierQ2":"6472","MultiplierQ3":"9011","MultiplierQ4":"12452","MultiplierQ5":"17940","PassiveSkill1Level":4,"PassiveSkill2Level":3,"SacrificeCost":15800,"LootGold":102,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"23","Evolution":2,"NextLevelXp":3400,"XpPerFight":100,"DamageMultiplier":"25190","HealthMultiplier":"25190","ArmorMultiplier":"25190","ActiveSkillLevel":4,"MultiplierQ1":"4096","MultiplierQ2":"6554","MultiplierQ3":"9216","MultiplierQ4":"12780","MultiplierQ5":"18514","PassiveSkill1Level":4,"PassiveSkill2Level":3,"SacrificeCost":17600,"LootGold":103,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"24","Evolution":2,"NextLevelXp":3604,"XpPerFight":100,"DamageMultiplier":"26214","HealthMultiplier":"26214","ArmorMultiplier":"26214","ActiveSkillLevel":4,"MultiplierQ1":"4096","MultiplierQ2":"6676","MultiplierQ3":"9421","MultiplierQ4":"13107","MultiplierQ5":"19046","PassiveSkill1Level":4,"PassiveSkill2Level":4,"SacrificeCost":19000,"LootGold":104,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"25","Evolution":2,"NextLevelXp":3820,"XpPerFight":100,"DamageMultiplier":"27238","HealthMultiplier":"27238","ArmorMultiplier":"27238","ActiveSkillLevel":4,"MultiplierQ1":"4096","MultiplierQ2":"6758","MultiplierQ3":"9585","MultiplierQ4":"13394","MultiplierQ5":"19620","PassiveSkill1Level":4,"PassiveSkill2Level":4,"SacrificeCost":20000,"LootGold":105,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"26","Evolution":2,"NextLevelXp":4049,"XpPerFight":100,"DamageMultiplier":"28262","HealthMultiplier":"28262","ArmorMultiplier":"28262","ActiveSkillLevel":5,"MultiplierQ1":"4096","MultiplierQ2":"6840","MultiplierQ3":"9789","MultiplierQ4":"13722","MultiplierQ5":"20193","PassiveSkill1Level":4,"PassiveSkill2Level":4,"SacrificeCost":20800,"LootGold":106,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"27","Evolution":2,"NextLevelXp":4292,"XpPerFight":100,"DamageMultiplier":"29286","HealthMultiplier":"29286","ArmorMultiplier":"29286","ActiveSkillLevel":5,"MultiplierQ1":"4096","MultiplierQ2":"6963","MultiplierQ3":"9994","MultiplierQ4":"14090","MultiplierQ5":"20808","PassiveSkill1Level":4,"PassiveSkill2Level":4,"SacrificeCost":21600,"LootGold":107,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"28","Evolution":2,"NextLevelXp":4549,"XpPerFight":100,"DamageMultiplier":"30310","HealthMultiplier":"30310","ArmorMultiplier":"30310","ActiveSkillLevel":5,"MultiplierQ1":"4096","MultiplierQ2":"7045","MultiplierQ3":"10240","MultiplierQ4":"14418","MultiplierQ5":"21422","PassiveSkill1Level":5,"PassiveSkill2Level":4,"SacrificeCost":22400,"LootGold":108,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"29","Evolution":3,"NextLevelXp":4822,"XpPerFight":100,"DamageMultiplier":"31334","HealthMultiplier":"31334","ArmorMultiplier":"31334","ActiveSkillLevel":5,"MultiplierQ1":"4096","MultiplierQ2":"7127","MultiplierQ3":"10445","MultiplierQ4":"14787","MultiplierQ5":"22077","PassiveSkill1Level":5,"PassiveSkill2Level":4,"SacrificeCost":23200,"LootGold":109,"LootResources":3,"EvolutionRequirementsQ1":"quantity:2;level:8;","EvolutionRequirementsQ2":"quantity:2;level:8;","EvolutionRequirementsQ3":"quantity:2;quality:1;level:8;","EvolutionRequirementsQ4":"quantity:2;quality:2;level:8;","EvolutionRequirementsQ5":"quantity:2;quality:2;level:8;"},
{"Id":"30","Evolution":3,"NextLevelXp":5112,"XpPerFight":100,"DamageMultiplier":"32358","HealthMultiplier":"32358","ArmorMultiplier":"32358","ActiveSkillLevel":5,"MultiplierQ1":"4096","MultiplierQ2":"7250","MultiplierQ3":"10650","MultiplierQ4":"15155","MultiplierQ5":"22733","PassiveSkill1Level":5,"PassiveSkill2Level":5,"SacrificeCost":23800,"LootGold":110,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"31","Evolution":3,"NextLevelXp":5418,"XpPerFight":100,"DamageMultiplier":"33382","HealthMultiplier":"33382","ArmorMultiplier":"33382","ActiveSkillLevel":5,"MultiplierQ1":"4096","MultiplierQ2":"7332","MultiplierQ3":"10895","MultiplierQ4":"15524","MultiplierQ5":"23429","PassiveSkill1Level":5,"PassiveSkill2Level":5,"SacrificeCost":24200,"LootGold":111,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"32","Evolution":3,"NextLevelXp":5743,"XpPerFight":100,"DamageMultiplier":"34406","HealthMultiplier":"34406","ArmorMultiplier":"34406","ActiveSkillLevel":6,"MultiplierQ1":"4096","MultiplierQ2":"7455","MultiplierQ3":"11100","MultiplierQ4":"15892","MultiplierQ5":"24125","PassiveSkill1Level":5,"PassiveSkill2Level":5,"SacrificeCost":24600,"LootGold":112,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"33","Evolution":3,"NextLevelXp":6088,"XpPerFight":100,"DamageMultiplier":"35430","HealthMultiplier":"35430","ArmorMultiplier":"35430","ActiveSkillLevel":6,"MultiplierQ1":"4096","MultiplierQ2":"7537","MultiplierQ3":"11346","MultiplierQ4":"16261","MultiplierQ5":"24863","PassiveSkill1Level":5,"PassiveSkill2Level":5,"SacrificeCost":24900,"LootGold":113,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"34","Evolution":3,"NextLevelXp":6453,"XpPerFight":100,"DamageMultiplier":"36454","HealthMultiplier":"36454","ArmorMultiplier":"36454","ActiveSkillLevel":6,"MultiplierQ1":"4096","MultiplierQ2":"7660","MultiplierQ3":"11592","MultiplierQ4":"16671","MultiplierQ5":"25600","PassiveSkill1Level":6,"PassiveSkill2Level":5,"SacrificeCost":25200,"LootGold":114,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"35","Evolution":3,"NextLevelXp":6841,"XpPerFight":100,"DamageMultiplier":"37478","HealthMultiplier":"37478","ArmorMultiplier":"37478","ActiveSkillLevel":6,"MultiplierQ1":"4096","MultiplierQ2":"7782","MultiplierQ3":"11837","MultiplierQ4":"17080","MultiplierQ5":"26378","PassiveSkill1Level":6,"PassiveSkill2Level":5,"SacrificeCost":25400,"LootGold":115,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"36","Evolution":3,"NextLevelXp":7251,"XpPerFight":100,"DamageMultiplier":"38502","HealthMultiplier":"38502","ArmorMultiplier":"38502","ActiveSkillLevel":6,"MultiplierQ1":"4096","MultiplierQ2":"7864","MultiplierQ3":"12083","MultiplierQ4":"17490","MultiplierQ5":"27156","PassiveSkill1Level":6,"PassiveSkill2Level":6,"SacrificeCost":25600,"LootGold":116,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"37","Evolution":3,"NextLevelXp":7686,"XpPerFight":100,"DamageMultiplier":"39526","HealthMultiplier":"39526","ArmorMultiplier":"39526","ActiveSkillLevel":6,"MultiplierQ1":"4096","MultiplierQ2":"7987","MultiplierQ3":"12329","MultiplierQ4":"17940","MultiplierQ5":"27976","PassiveSkill1Level":6,"PassiveSkill2Level":6,"SacrificeCost":25740,"LootGold":117,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"38","Evolution":3,"NextLevelXp":8147,"XpPerFight":100,"DamageMultiplier":"40550","HealthMultiplier":"40550","ArmorMultiplier":"40550","ActiveSkillLevel":7,"MultiplierQ1":"4096","MultiplierQ2":"8110","MultiplierQ3":"12575","MultiplierQ4":"18350","MultiplierQ5":"28795","PassiveSkill1Level":6,"PassiveSkill2Level":6,"SacrificeCost":26000,"LootGold":118,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"39","Evolution":4,"NextLevelXp":8636,"XpPerFight":100,"DamageMultiplier":"41574","HealthMultiplier":"41574","ArmorMultiplier":"41574","ActiveSkillLevel":7,"MultiplierQ1":"4096","MultiplierQ2":"8192","MultiplierQ3":"12861","MultiplierQ4":"18801","MultiplierQ5":"29696","PassiveSkill1Level":6,"PassiveSkill2Level":6,"SacrificeCost":26400,"LootGold":119,"LootResources":3,"EvolutionRequirementsQ1":"quantity:3;level:8;","EvolutionRequirementsQ2":"quantity:3;level:8;","EvolutionRequirementsQ3":"quantity:3;quality:1;level:8;","EvolutionRequirementsQ4":"quantity:3;quality:2;level:18;","EvolutionRequirementsQ5":"quantity:3;quality:2;level:18;"},
{"Id":"40","Evolution":4,"NextLevelXp":9154,"XpPerFight":100,"DamageMultiplier":"42598","HealthMultiplier":"42598","ArmorMultiplier":"42598","ActiveSkillLevel":7,"MultiplierQ1":"4096","MultiplierQ2":"8315","MultiplierQ3":"13107","MultiplierQ4":"19292","MultiplierQ5":"30556","PassiveSkill1Level":7,"PassiveSkill2Level":6,"SacrificeCost":26800,"LootGold":120,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"41","Evolution":4,"NextLevelXp":9704,"XpPerFight":100,"DamageMultiplier":"43622","HealthMultiplier":"43622","ArmorMultiplier":"43622","ActiveSkillLevel":7,"MultiplierQ1":"4096","MultiplierQ2":"8438","MultiplierQ3":"13394","MultiplierQ4":"19743","MultiplierQ5":"31498","PassiveSkill1Level":7,"PassiveSkill2Level":6,"SacrificeCost":27200,"LootGold":121,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"42","Evolution":4,"NextLevelXp":10286,"XpPerFight":100,"DamageMultiplier":"44646","HealthMultiplier":"44646","ArmorMultiplier":"44646","ActiveSkillLevel":7,"MultiplierQ1":"4096","MultiplierQ2":"8561","MultiplierQ3":"13681","MultiplierQ4":"20234","MultiplierQ5":"32440","PassiveSkill1Level":7,"PassiveSkill2Level":7,"SacrificeCost":27600,"LootGold":122,"LootResources":3,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"43","Evolution":4,"NextLevelXp":10903,"XpPerFight":100,"DamageMultiplier":"45670","HealthMultiplier":"45670","ArmorMultiplier":"45670","ActiveSkillLevel":7,"MultiplierQ1":"4096","MultiplierQ2":"8684","MultiplierQ3":"13967","MultiplierQ4":"20726","MultiplierQ5":"33423","PassiveSkill1Level":7,"PassiveSkill2Level":7,"SacrificeCost":28000,"LootGold":123,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"44","Evolution":4,"NextLevelXp":11557,"XpPerFight":100,"DamageMultiplier":"46694","HealthMultiplier":"46694","ArmorMultiplier":"46694","ActiveSkillLevel":8,"MultiplierQ1":"4096","MultiplierQ2":"8806","MultiplierQ3":"14254","MultiplierQ4":"21258","MultiplierQ5":"34406","PassiveSkill1Level":7,"PassiveSkill2Level":7,"SacrificeCost":28400,"LootGold":124,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"45","Evolution":4,"NextLevelXp":12250,"XpPerFight":100,"DamageMultiplier":"47718","HealthMultiplier":"47718","ArmorMultiplier":"47718","ActiveSkillLevel":8,"MultiplierQ1":"4096","MultiplierQ2":"8929","MultiplierQ3":"14541","MultiplierQ4":"21750","MultiplierQ5":"35430","PassiveSkill1Level":7,"PassiveSkill2Level":7,"SacrificeCost":28800,"LootGold":125,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"46","Evolution":4,"NextLevelXp":12985,"XpPerFight":100,"DamageMultiplier":"48742","HealthMultiplier":"48742","ArmorMultiplier":"48742","ActiveSkillLevel":8,"MultiplierQ1":"4096","MultiplierQ2":"9052","MultiplierQ3":"14868","MultiplierQ4":"22282","MultiplierQ5":"36495","PassiveSkill1Level":8,"PassiveSkill2Level":7,"SacrificeCost":29200,"LootGold":126,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"47","Evolution":4,"NextLevelXp":13765,"XpPerFight":100,"DamageMultiplier":"49766","HealthMultiplier":"49766","ArmorMultiplier":"49766","ActiveSkillLevel":8,"MultiplierQ1":"4096","MultiplierQ2":"9175","MultiplierQ3":"15155","MultiplierQ4":"22856","MultiplierQ5":"37601","PassiveSkill1Level":8,"PassiveSkill2Level":7,"SacrificeCost":29600,"LootGold":127,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"48","Evolution":4,"NextLevelXp":14590,"XpPerFight":100,"DamageMultiplier":"50790","HealthMultiplier":"50790","ArmorMultiplier":"50790","ActiveSkillLevel":8,"MultiplierQ1":"4096","MultiplierQ2":"9298","MultiplierQ3":"15483","MultiplierQ4":"23388","MultiplierQ5":"38707","PassiveSkill1Level":8,"PassiveSkill2Level":8,"SacrificeCost":30000,"LootGold":128,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"49","Evolution":5,"NextLevelXp":15466,"XpPerFight":100,"DamageMultiplier":"51814","HealthMultiplier":"51814","ArmorMultiplier":"51814","ActiveSkillLevel":8,"MultiplierQ1":"4096","MultiplierQ2":"9421","MultiplierQ3":"15811","MultiplierQ4":"23962","MultiplierQ5":"39895","PassiveSkill1Level":8,"PassiveSkill2Level":8,"SacrificeCost":30400,"LootGold":129,"LootResources":4,"EvolutionRequirementsQ1":"quantity:4;level:8;","EvolutionRequirementsQ2":"quantity:4;level:8;","EvolutionRequirementsQ3":"quantity:4;quality:1;level:8;","EvolutionRequirementsQ4":"quantity:4;quality:2;level:18;","EvolutionRequirementsQ5":"quantity:4;quality:3;level:18;"},
{"Id":"50","Evolution":5,"NextLevelXp":16394,"XpPerFight":100,"DamageMultiplier":"52838","HealthMultiplier":"52838","ArmorMultiplier":"52838","ActiveSkillLevel":9,"MultiplierQ1":"4096","MultiplierQ2":"9585","MultiplierQ3":"16138","MultiplierQ4":"24576","MultiplierQ5":"41083","PassiveSkill1Level":8,"PassiveSkill2Level":8,"SacrificeCost":30800,"LootGold":130,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"51","Evolution":5,"NextLevelXp":17378,"XpPerFight":100,"DamageMultiplier":"53862","HealthMultiplier":"53862","ArmorMultiplier":"53862","ActiveSkillLevel":9,"MultiplierQ1":"4096","MultiplierQ2":"9708","MultiplierQ3":"16466","MultiplierQ4":"25149","MultiplierQ5":"42312","PassiveSkill1Level":8,"PassiveSkill2Level":8,"SacrificeCost":31200,"LootGold":131,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"52","Evolution":5,"NextLevelXp":18420,"XpPerFight":100,"DamageMultiplier":"54886","HealthMultiplier":"54886","ArmorMultiplier":"54886","ActiveSkillLevel":9,"MultiplierQ1":"4096","MultiplierQ2":"9830","MultiplierQ3":"16835","MultiplierQ4":"25764","MultiplierQ5":"43581","PassiveSkill1Level":9,"PassiveSkill2Level":8,"SacrificeCost":31600,"LootGold":132,"LootResources":4,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"53","Evolution":5,"NextLevelXp":19525,"XpPerFight":100,"DamageMultiplier":"55910","HealthMultiplier":"55910","ArmorMultiplier":"55910","ActiveSkillLevel":9,"MultiplierQ1":"4096","MultiplierQ2":"9953","MultiplierQ3":"17203","MultiplierQ4":"26419","MultiplierQ5":"44892","PassiveSkill1Level":9,"PassiveSkill2Level":8,"SacrificeCost":32000,"LootGold":133,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"54","Evolution":5,"NextLevelXp":20697,"XpPerFight":100,"DamageMultiplier":"56934","HealthMultiplier":"56934","ArmorMultiplier":"56934","ActiveSkillLevel":9,"MultiplierQ1":"4096","MultiplierQ2":"10117","MultiplierQ3":"17531","MultiplierQ4":"27075","MultiplierQ5":"46244","PassiveSkill1Level":9,"PassiveSkill2Level":9,"SacrificeCost":32400,"LootGold":134,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"55","Evolution":5,"NextLevelXp":21939,"XpPerFight":100,"DamageMultiplier":"57958","HealthMultiplier":"57958","ArmorMultiplier":"57958","ActiveSkillLevel":9,"MultiplierQ1":"4096","MultiplierQ2":"10240","MultiplierQ3":"17900","MultiplierQ4":"27730","MultiplierQ5":"47636","PassiveSkill1Level":9,"PassiveSkill2Level":9,"SacrificeCost":32800,"LootGold":135,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"56","Evolution":5,"NextLevelXp":23255,"XpPerFight":100,"DamageMultiplier":"58982","HealthMultiplier":"58982","ArmorMultiplier":"58982","ActiveSkillLevel":10,"MultiplierQ1":"4096","MultiplierQ2":"10404","MultiplierQ3":"18309","MultiplierQ4":"28385","MultiplierQ5":"49070","PassiveSkill1Level":9,"PassiveSkill2Level":9,"SacrificeCost":33200,"LootGold":136,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"57","Evolution":5,"NextLevelXp":24650,"XpPerFight":100,"DamageMultiplier":"60006","HealthMultiplier":"60006","ArmorMultiplier":"60006","ActiveSkillLevel":10,"MultiplierQ1":"4096","MultiplierQ2":"10527","MultiplierQ3":"18678","MultiplierQ4":"29082","MultiplierQ5":"50545","PassiveSkill1Level":9,"PassiveSkill2Level":9,"SacrificeCost":33600,"LootGold":137,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"58","Evolution":5,"NextLevelXp":26129,"XpPerFight":100,"DamageMultiplier":"61030","HealthMultiplier":"61030","ArmorMultiplier":"61030","ActiveSkillLevel":10,"MultiplierQ1":"4096","MultiplierQ2":"10691","MultiplierQ3":"19046","MultiplierQ4":"29819","MultiplierQ5":"52060","PassiveSkill1Level":10,"PassiveSkill2Level":9,"SacrificeCost":34000,"LootGold":138,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"59","Evolution":6,"NextLevelXp":27697,"XpPerFight":100,"DamageMultiplier":"62054","HealthMultiplier":"62054","ArmorMultiplier":"62054","ActiveSkillLevel":10,"MultiplierQ1":"4096","MultiplierQ2":"10854","MultiplierQ3":"19456","MultiplierQ4":"30556","MultiplierQ5":"53617","PassiveSkill1Level":10,"PassiveSkill2Level":9,"SacrificeCost":34400,"LootGold":139,"LootResources":5,"EvolutionRequirementsQ1":"quantity:4;level:14;","EvolutionRequirementsQ2":"quantity:4;level:8;quality:1;","EvolutionRequirementsQ3":"quantity:4;quality:2;level:18;","EvolutionRequirementsQ4":"quantity:4;quality:3;level:18;","EvolutionRequirementsQ5":"quantity:4;quality:4;level:18;"},
{"Id":"60","Evolution":6,"NextLevelXp":29359,"XpPerFight":100,"DamageMultiplier":"63078","HealthMultiplier":"63078","ArmorMultiplier":"63078","ActiveSkillLevel":10,"MultiplierQ1":"4096","MultiplierQ2":"10977","MultiplierQ3":"19866","MultiplierQ4":"31293","MultiplierQ5":"55214","PassiveSkill1Level":10,"PassiveSkill2Level":10,"SacrificeCost":34800,"LootGold":140,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"61","Evolution":6,"NextLevelXp":31120,"XpPerFight":100,"DamageMultiplier":"64102","HealthMultiplier":"64102","ArmorMultiplier":"64102","ActiveSkillLevel":10,"MultiplierQ1":"4096","MultiplierQ2":"11141","MultiplierQ3":"20275","MultiplierQ4":"32072","MultiplierQ5":"56852","PassiveSkill1Level":10,"PassiveSkill2Level":10,"SacrificeCost":35200,"LootGold":141,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"62","Evolution":6,"NextLevelXp":32988,"XpPerFight":100,"DamageMultiplier":"65126","HealthMultiplier":"65126","ArmorMultiplier":"65126","ActiveSkillLevel":11,"MultiplierQ1":"4096","MultiplierQ2":"11305","MultiplierQ3":"20726","MultiplierQ4":"32850","MultiplierQ5":"58573","PassiveSkill1Level":10,"PassiveSkill2Level":10,"SacrificeCost":35600,"LootGold":142,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"63","Evolution":6,"NextLevelXp":34967,"XpPerFight":100,"DamageMultiplier":"66150","HealthMultiplier":"66150","ArmorMultiplier":"66150","ActiveSkillLevel":11,"MultiplierQ1":"4096","MultiplierQ2":"11469","MultiplierQ3":"21135","MultiplierQ4":"33628","MultiplierQ5":"60334","PassiveSkill1Level":10,"PassiveSkill2Level":10,"SacrificeCost":36000,"LootGold":143,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"64","Evolution":6,"NextLevelXp":37065,"XpPerFight":100,"DamageMultiplier":"67174","HealthMultiplier":"67174","ArmorMultiplier":"67174","ActiveSkillLevel":11,"MultiplierQ1":"4096","MultiplierQ2":"11633","MultiplierQ3":"21586","MultiplierQ4":"34447","MultiplierQ5":"62136","PassiveSkill1Level":11,"PassiveSkill2Level":10,"SacrificeCost":36400,"LootGold":144,"LootResources":5,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"65","Evolution":6,"NextLevelXp":39289,"XpPerFight":100,"DamageMultiplier":"68198","HealthMultiplier":"68198","ArmorMultiplier":"68198","ActiveSkillLevel":11,"MultiplierQ1":"4096","MultiplierQ2":"11796","MultiplierQ3":"22036","MultiplierQ4":"35308","MultiplierQ5":"64020","PassiveSkill1Level":11,"PassiveSkill2Level":10,"SacrificeCost":36800,"LootGold":145,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"66","Evolution":6,"NextLevelXp":41646,"XpPerFight":100,"DamageMultiplier":"69222","HealthMultiplier":"69222","ArmorMultiplier":"69222","ActiveSkillLevel":11,"MultiplierQ1":"4096","MultiplierQ2":"11960","MultiplierQ3":"22528","MultiplierQ4":"36168","MultiplierQ5":"65946","PassiveSkill1Level":11,"PassiveSkill2Level":11,"SacrificeCost":37200,"LootGold":146,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"67","Evolution":6,"NextLevelXp":44145,"XpPerFight":100,"DamageMultiplier":"70246","HealthMultiplier":"70246","ArmorMultiplier":"70246","ActiveSkillLevel":11,"MultiplierQ1":"4096","MultiplierQ2":"12124","MultiplierQ3":"22979","MultiplierQ4":"37069","MultiplierQ5":"67912","PassiveSkill1Level":11,"PassiveSkill2Level":11,"SacrificeCost":37600,"LootGold":147,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"68","Evolution":6,"NextLevelXp":46794,"XpPerFight":100,"DamageMultiplier":"71270","HealthMultiplier":"71270","ArmorMultiplier":"71270","ActiveSkillLevel":12,"MultiplierQ1":"4096","MultiplierQ2":"12288","MultiplierQ3":"23470","MultiplierQ4":"37970","MultiplierQ5":"69960","PassiveSkill1Level":11,"PassiveSkill2Level":11,"SacrificeCost":38000,"LootGold":148,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"69","Evolution":7,"NextLevelXp":49601,"XpPerFight":100,"DamageMultiplier":"72294","HealthMultiplier":"72294","ArmorMultiplier":"72294","ActiveSkillLevel":12,"MultiplierQ1":"4096","MultiplierQ2":"12452","MultiplierQ3":"23962","MultiplierQ4":"38912","MultiplierQ5":"72049","PassiveSkill1Level":11,"PassiveSkill2Level":11,"SacrificeCost":38400,"LootGold":149,"LootResources":6,"EvolutionRequirementsQ1":"quantity:4;level:18;","EvolutionRequirementsQ2":"quantity:4;level:18;quality:1;","EvolutionRequirementsQ3":"quantity:4;quality:2;level:28;","EvolutionRequirementsQ4":"quantity:4;quality:3;level:28;","EvolutionRequirementsQ5":"quantity:4;quality:4;level:28;"},
{"Id":"70","Evolution":7,"NextLevelXp":52577,"XpPerFight":100,"DamageMultiplier":"73318","HealthMultiplier":"73318","ArmorMultiplier":"73318","ActiveSkillLevel":12,"MultiplierQ1":"4096","MultiplierQ2":"12616","MultiplierQ3":"24453","MultiplierQ4":"39854","MultiplierQ5":"74220","PassiveSkill1Level":12,"PassiveSkill2Level":11,"SacrificeCost":38800,"LootGold":150,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"71","Evolution":7,"NextLevelXp":55732,"XpPerFight":100,"DamageMultiplier":"74342","HealthMultiplier":"74342","ArmorMultiplier":"74342","ActiveSkillLevel":12,"MultiplierQ1":"4096","MultiplierQ2":"12820","MultiplierQ3":"24986","MultiplierQ4":"40837","MultiplierQ5":"76431","PassiveSkill1Level":12,"PassiveSkill2Level":11,"SacrificeCost":39200,"LootGold":151,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"72","Evolution":7,"NextLevelXp":59076,"XpPerFight":100,"DamageMultiplier":"75366","HealthMultiplier":"75366","ArmorMultiplier":"75366","ActiveSkillLevel":12,"MultiplierQ1":"4096","MultiplierQ2":"12984","MultiplierQ3":"25518","MultiplierQ4":"41820","MultiplierQ5":"78725","PassiveSkill1Level":12,"PassiveSkill2Level":12,"SacrificeCost":39600,"LootGold":152,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"73","Evolution":7,"NextLevelXp":62620,"XpPerFight":100,"DamageMultiplier":"76390","HealthMultiplier":"76390","ArmorMultiplier":"76390","ActiveSkillLevel":12,"MultiplierQ1":"4096","MultiplierQ2":"13189","MultiplierQ3":"26051","MultiplierQ4":"42844","MultiplierQ5":"81101","PassiveSkill1Level":12,"PassiveSkill2Level":12,"SacrificeCost":40000,"LootGold":153,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"74","Evolution":7,"NextLevelXp":66378,"XpPerFight":100,"DamageMultiplier":"77414","HealthMultiplier":"77414","ArmorMultiplier":"77414","ActiveSkillLevel":13,"MultiplierQ1":"4096","MultiplierQ2":"13353","MultiplierQ3":"26583","MultiplierQ4":"43909","MultiplierQ5":"83517","PassiveSkill1Level":12,"PassiveSkill2Level":12,"SacrificeCost":40400,"LootGold":154,"LootResources":8,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"75","Evolution":7,"NextLevelXp":70360,"XpPerFight":100,"DamageMultiplier":"78438","HealthMultiplier":"78438","ArmorMultiplier":"78438","ActiveSkillLevel":13,"MultiplierQ1":"4096","MultiplierQ2":"13558","MultiplierQ3":"27156","MultiplierQ4":"44974","MultiplierQ5":"86016","PassiveSkill1Level":12,"PassiveSkill2Level":12,"SacrificeCost":40800,"LootGold":155,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"76","Evolution":7,"NextLevelXp":74582,"XpPerFight":100,"DamageMultiplier":"79462","HealthMultiplier":"79462","ArmorMultiplier":"79462","ActiveSkillLevel":13,"MultiplierQ1":"4096","MultiplierQ2":"13722","MultiplierQ3":"27730","MultiplierQ4":"46080","MultiplierQ5":"88596","PassiveSkill1Level":13,"PassiveSkill2Level":12,"SacrificeCost":41200,"LootGold":156,"LootResources":6,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"77","Evolution":7,"NextLevelXp":79057,"XpPerFight":100,"DamageMultiplier":"80486","HealthMultiplier":"80486","ArmorMultiplier":"80486","ActiveSkillLevel":13,"MultiplierQ1":"4096","MultiplierQ2":"13926","MultiplierQ3":"28303","MultiplierQ4":"47227","MultiplierQ5":"91259","PassiveSkill1Level":13,"PassiveSkill2Level":12,"SacrificeCost":41600,"LootGold":157,"LootResources":7,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"78","Evolution":7,"NextLevelXp":83800,"XpPerFight":100,"DamageMultiplier":"81510","HealthMultiplier":"81510","ArmorMultiplier":"81510","ActiveSkillLevel":13,"MultiplierQ1":"4096","MultiplierQ2":"14131","MultiplierQ3":"28877","MultiplierQ4":"48374","MultiplierQ5":"94003","PassiveSkill1Level":13,"PassiveSkill2Level":13,"SacrificeCost":42000,"LootGold":158,"LootResources":7,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""},
{"Id":"79","Evolution":7,"NextLevelXp":88828,"XpPerFight":100,"DamageMultiplier":"82534","HealthMultiplier":"82534","ArmorMultiplier":"82534","ActiveSkillLevel":13,"MultiplierQ1":"4096","MultiplierQ2":"14295","MultiplierQ3":"29491","MultiplierQ4":"49562","MultiplierQ5":"96829","PassiveSkill1Level":13,"PassiveSkill2Level":13,"SacrificeCost":42400,"LootGold":159,"LootResources":7,"EvolutionRequirementsQ1":"","EvolutionRequirementsQ2":"","EvolutionRequirementsQ3":"","EvolutionRequirementsQ4":"","EvolutionRequirementsQ5":""}
]; |
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');
let fs = require('fs');
let path = require('path');
const directoryName = path.dirname(__filename);
const creds = {
tone: {
"username": "redacted",
"password": "redacted"
},
nlu: {
"username": "redacted",
"password": "redacted"
}
};
let toneAnalyzer = new ToneAnalyzerV3({
username: creds.tone.username,
password: creds.tone.password,
version: 'v3',
version_date: '2017-03-15'
});
var nlu = new NaturalLanguageUnderstandingV1({
username: creds.nlu.username,
password: creds.nlu.password,
version_date: NaturalLanguageUnderstandingV1.VERSION_DATE_2017_02_27
});
function generateToneAnalysis(title, poem) {
let toneParams = {
'text': poem,
'isHTML': false,
'sentences': false
};
let nluParams = {
'text': poem,
'features': {
'keywords': {
'emotion': true,
'sentiment': true,
'limit': 10
},
'sentiment': {}
}
}
toneAnalyzer.tone(toneParams, function(err, res1){
if (err) { console.log(err); }
else {
nlu.analyze(nluParams, function(err, res2){
if (err) { console.log(err); }
else {
var result = Object.assign({"title": title}, res1, res2);
prettyJson = JSON.stringify(result, null, 2);
fs.appendFileSync('./sentiments.json', prettyJson, {encoding: 'utf8'});
console.log(`Retrieved Watson Analysis for ${title}`);
}
});
}
});
}
function readFiles(dirname, onFileContent, onError) {
fs.readdir(dirname, function(err, filenames) {
if (err) {
onError(err);
return;
}
var index = filenames.indexOf(".DS_Store");
if (index >= 0) {
filenames.splice(index, 1 );
}
filenames.forEach(function(filename) {
fs.readFile(path.join(dirname,filename), 'utf8', function(err, content) {
if (err) {
onError(err);
return;
}
onFileContent(filename.substring(0, filename.length-4), content);
});
});
});
}
// fs.writeFileSync('./s.json', '', 'utf8');
// fs.readdir('./missing', function(err, files) {
// var index = files.indexOf(".DS_Store");
// if (index >= 0) {
// files.splice(index, 1 );
// }
// for (var i = 0; i<files.length; i++) {
// console.log(files[i]);
// file = fs.readFileSync(path.join(directoryName+'/missing', files[i]), {encoding: 'utf8'});
// generateToneAnalysis(files[i], file);
// }
// });
fs.readdir('./poems', function(err, folders){
if (err) {
console.log(err);
return;
}
var index = folders.indexOf(".DS_Store");
if (index >= 0) {
folders.splice(index, 1 );
}
for (var i = 0; i < folders.length; i++) {
let dirname = path.join('./poems', folders[i]);
readFiles(dirname, generateToneAnalysis, function(err) {
console.log(err);
});
}
});
|
var encodeDecode = function() {
var randomNum = function (min, max) { // helper function for random numbers
return Math.random() * (max - min) + min;
};
var insertBreak = function (counter) { //helper function to break lines @ 100 char
if (counter % 100 === 0) {
$('body').append("<br>");
}
};
var encode = function (s) { //encodes a string
var spl = s.split("");
var lineCounter = 0;
for (var i=0; i < spl.length; i++) {
$('body').append("<span class='encoded' hidden>" + spl[i] + "</span>");
var r = randomNum(20,30);
for (var j=0; j < r; j++) {
insertBreak(lineCounter);
lineCounter++;
var q = randomNum(33,126);
$('body').append("<span>" + String.fromCharCode(q) + "</span>");
}
}
};
var decode = function () { //decodes the page
var decodeString = "";
$('[hidden]').each(function() {
decodeString += $(this).text();
$(this).remove();
});
$('span, br').remove();
$('body').append("<span class='decoded'>" + decodeString + "</span>");
};
if ($('body').children('span.encoded').length > 0) {
decode();
} else if ($('body').children('span.decoded').length > 0) {
var s = $('span.decoded').text();
$('span.decoded').remove();
encode(s);
} else {
encode("The challenge was found by running: $('body').children().toggle(); Note that even the line breaks from the challenege were included in my script. We should grab lunch, don't you think? "); //starter string to encode / decode
}
};
$( document ).ready(function() {
encodeDecode();
});
|
import React, {
Fragment,
Children,
cloneElement,
useRef,
useEffect
} from 'react';
import { createPortal } from 'react-dom';
import PropTypes from 'prop-types';
import cx from 'classnames';
import idgen from './idgen';
import Button from './Button';
import { safeJSONStringify } from './utils';
const Modal = ({
actions,
bottomSheet,
children,
fixedFooter,
header,
className,
trigger,
options,
open,
root,
...props
}) => {
const _modalRoot = useRef(null);
const _modalInstance = useRef(null);
const _modalRef = useRef(null);
if (root === null) {
console.warn(
'React Materialize: root should be a valid node element to render a Modal'
);
}
useEffect(() => {
const modalRoot = _modalRoot.current;
if (!_modalInstance.current) {
_modalInstance.current = M.Modal.init(_modalRef.current, options);
}
return () => {
if (root.contains(modalRoot)) {
root.removeChild(modalRoot);
}
_modalInstance.current.destroy();
};
// deep comparing options object
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [safeJSONStringify(options), root]);
useEffect(() => {
if (open) {
showModal();
} else {
hideModal();
}
}, [open]);
const showModal = e => {
e && e.preventDefault();
_modalInstance.current && _modalInstance.current.open();
};
const hideModal = e => {
e && e.preventDefault();
_modalInstance.current && _modalInstance.current.close();
};
const classes = cx(
'modal',
{
'modal-fixed-footer': fixedFooter,
'bottom-sheet': bottomSheet
},
className
);
const renderModalPortal = () => {
if (!_modalRoot.current) {
_modalRoot.current = document.createElement('div');
root.appendChild(_modalRoot.current);
}
return createPortal(
<div className={classes} ref={_modalRef} {...props}>
<div className="modal-content">
<h4>{header}</h4>
{children}
</div>
<div className="modal-footer">{Children.toArray(actions)}</div>
</div>,
_modalRoot.current
);
};
return (
<Fragment>
{trigger && cloneElement(trigger, { onClick: showModal })}
{renderModalPortal()}
</Fragment>
);
};
Modal.propTypes = {
/**
* Options
* Object with options for modal
*/
options: PropTypes.shape({
/**
* Opacity of the modal overlay.
*/
opacity: PropTypes.number,
/**
* Transition in duration in milliseconds.
*/
inDuration: PropTypes.number,
/**
* Transition out duration in milliseconds.
*/
outDuration: PropTypes.number,
/**
* Callback function called before modal is opened.
*/
onOpenStart: PropTypes.func,
/**
* Callback function called after modal is opened.
*/
onOpenEnd: PropTypes.func,
/**
* Callback function called before modal is closed.
*/
onCloseStart: PropTypes.func,
/**
* Callback function called after modal is closed.
*/
onCloseEnd: PropTypes.func,
/**
* Prevent page from scrolling while modal is open.
*/
preventScrolling: PropTypes.bool,
/**
* Allow modal to be dismissed by keyboard or overlay click.
*/
dismissible: PropTypes.bool,
/**
* Starting top offset
*/
startingTop: PropTypes.string,
/**
* Ending top offset
*/
endingTop: PropTypes.string
}),
/**
* Extra class to added to the Modal
*/
className: PropTypes.string,
/**
* Modal is opened on mount
* @default false
*/
open: PropTypes.bool,
/**
* BottomSheet styled modal
* @default false
*/
bottomSheet: PropTypes.bool,
/**
* Component children
*/
children: PropTypes.node,
/**
* FixedFooter styled modal
* @default false
*/
fixedFooter: PropTypes.bool,
/**
* Text to shown in the header of the modal
*/
header: PropTypes.string,
/**
* The button to trigger the display of the modal
*/
trigger: PropTypes.node,
/**
* The buttons to show in the footer of the modal
* @default <Button>Close</Button>
*/
actions: PropTypes.node,
/**
* The ID to trigger the modal opening/closing
*/
id: PropTypes.string,
/**
* Root node where modal should be injected
* @default document.body
*/
root: PropTypes.any
};
Modal.defaultProps = {
get id() {
return `Modal-${idgen()}`;
},
root: typeof window !== 'undefined' ? document.body : null,
open: false,
options: {
opacity: 0.5,
inDuration: 250,
outDuration: 250,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null,
preventScrolling: true,
dismissible: true,
startingTop: '4%',
endingTop: '10%'
},
fixedFooter: false,
bottomSheet: false,
actions: [
<Button waves="green" modal="close" flat>
Close
</Button>
]
};
export default Modal;
|
class KonamiCodeManager {
constructor() {
this._pattern = "38384040373937396665";
this._keyCodeCache = '';
this._callback = () => {};
this._boundCheckKeyCodePattern = this._checkKeyCodePattern.bind(this);
}
attach(root, callback) {
if (root instanceof Element) {
root.removeEventListener('keydown', this._boundCheckKeyCodePattern);
root.addEventListener('keydown', this._boundCheckKeyCodePattern);
this._callback = callback;
}
}
_checkKeyCodePattern(e) {
if (e) {
this._keyCodeCache += e.keyCode;
if (this._keyCodeCache.length === this._pattern.length) {
if (this._keyCodeCache === this._pattern) {
console.log('KonamiCode passed, let\'s show some easter eggs :)');
this._callback();
}
this._keyCodeCache = '';
}
else if (!this._pattern.match(this._keyCodeCache)) {
this._keyCodeCache = '';
}
}
}
}
module.exports = new KonamiCodeManager();
|
'use strict';
describe('test search controller', function() {
beforeEach(module('mapTweetInfoApp'));
beforeEach(module('twitterSearchServices'));
beforeEach(module('latLngServices'));
describe('searchCtrl', function(){
var scope, ctrl, $httpBackend, $browser, $location;
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
// $httpBackend = _$httpBackend_;
// $httpBackend.expectGET('phones/phones.json').
// respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
scope = $rootScope.$new();
$location = scope.$service('$location');
$browser = scope.$service('$browser');
ctrl = $controller('searchCtrl', {$scope: scope});
}));
it('should have default variables set', function() {
// expect(scope.phones).toEqualData([]);
// $httpBackend.flush();
expect(scope.counts).toEqualData(
[{label: '25 Tweets', value: '25'},{label: '50 Tweets', value: '50'},{label: '75 Tweets', value: '75'},{label: '150 Tweets', value: '150'}]
);
});
// it('should set the default value of orderProp model', function() {
// expect(scope.orderProp).toBe('age');
// });
});
}); |
/**
*
* Trailing Zeroes
*
* @author: Corey Hart <http://www.codenothing.com>
* @description: Removes unecessary trailing zeroes from values
*
* @before:
* .example {
* width: 5.0px;
* }
*
* @after:
* .example {
* width: 5px;
* }
*
*/
var CSSCompressor = global.CSSCompressor,
rdecimal = /^(\+|\-)?(\d*\.[1-9]*0*)(\%|[a-z]{2})$/i,
rleadzero = /^\-?0/;
CSSCompressor.rule({
name: 'Trailing Zeroes',
type: CSSCompressor.RULE_TYPE_VALUE,
group: 'Numeric',
description: "Removes unecessary trailing zeroes from values",
callback: function( value, position, compressor ) {
var m = rdecimal.exec( value ),
before = value,
n;
if ( m ) {
// Remove possible leading zero that comes from parseFloat
n = parseFloat( m[ 2 ] );
if ( ( n > 0 && n < 1 ) || ( n > -1 && n < 0 ) ) {
n = ( n + '' ).replace( rleadzero, '' );
}
value = ( m[ 1 ] ? m[ 1 ] : '' ) + n + ( m[ 3 ] ? m[ 3 ] : '' );
compressor.log(
"Removing unecesary trailing zeroes '" + before + "' => '" + value + "'",
position
);
return value;
}
}
});
|
// 文件上传
jQuery(function() {
var $ = jQuery,
$list = $('#thelist'),
$btn = $('#ctlBtn'),
state = 'pending',
// 优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
uploader;
uploader = WebUploader.create({
// 单文件上传
multiple: false,
// 不压缩image
resize: false,
// swf文件路径
swf: '/webuploader/Uploader.swf',
// 文件接收服务端。
server: '/upload',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
// 只允许选择图片文件。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
var $li = $(
'<div id="' + file.id + '" class="file-item thumbnail">' +
'<img>' +
'<div class="info">' + file.name + '</div>' +
'</div>'
),
$img = $li.find('img');
$list.append( $li );
// 创建缩略图
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$img.replaceWith('<span>不能预览</span>');
return;
}
$img.attr( 'src', src );
}, thumbnailWidth, thumbnailHeight );
});
// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress .progress-bar');
// 避免重复创建
if ( !$percent.length ) {
$percent = $('<div class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" style="width: 0%">' +
'</div>' +
'</div>').appendTo( $li ).find('.progress-bar');
}
$li.find('p.state').text('上传中');
$percent.css( 'width', percentage * 100 + '%' );
});
uploader.on( 'uploadSuccess', function( file , data) {
$( '#'+file.id ).find('p.state').text('已上传');
$('#user_avatar').val(data.imageurl)
$('#avatar').attr("src",data.imageurl)
});
uploader.on( 'uploadError', function( file ) {
$( '#'+file.id ).find('p.state').text('上传出错');
});
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').fadeOut();
});
uploader.on( 'all', function( type ) {
if ( type === 'startUpload' ) {
state = 'uploading';
} else if ( type === 'stopUpload' ) {
state = 'paused';
} else if ( type === 'uploadFinished' ) {
state = 'done';
}
if ( state === 'uploading' ) {
$btn.text('暂停上传');
} else {
$btn.text('开始上传');
}
});
$btn.on( 'click', function() {
if ( state === 'uploading' ) {
uploader.stop();
} else {
uploader.upload();
}
});
}); |
'use strict';
module.exports = {
client: {
lib: {
// Load Angular-UI-Bootstrap module templates for these modules:
uibModuleTemplates: [
'modal',
'popover',
'progressbar',
'tabs',
'tooltip',
'typeahead'
],
css: [
'public/lib/fontello/css/animation.css',
'public/lib/medium-editor/dist/css/medium-editor.css',
'modules/core/client/fonts/fontello/css/tricons-codes.css',
'public/lib/angular-ui-bootstrap/src/position/position.css',
'public/lib/angular-ui-bootstrap/src/typeahead/typeahead.css',
'public/lib/angular-ui-bootstrap/src/tooltip/tooltip.css'
],
js: [
// Non minified versions
'public/lib/jquery/dist/jquery.js',
'public/lib/angular/angular.js',
'public/lib/angular-aria/angular-aria.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-message-format/angular-message-format.js',
'public/lib/angulartics/src/angulartics.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-bootstrap/src/buttons/buttons.js',
'public/lib/angular-ui-bootstrap/src/collapse/collapse.js',
'public/lib/angular-ui-bootstrap/src/dateparser/dateparser.js',
'public/lib/angular-ui-bootstrap/src/debounce/debounce.js',
'public/lib/angular-ui-bootstrap/src/dropdown/dropdown.js',
'public/lib/angular-ui-bootstrap/src/modal/modal.js',
'public/lib/angular-ui-bootstrap/src/popover/popover.js',
'public/lib/angular-ui-bootstrap/src/position/position.js',
'public/lib/angular-ui-bootstrap/src/progressbar/progressbar.js',
'public/lib/angular-ui-bootstrap/src/stackedMap/stackedMap.js',
'public/lib/angular-ui-bootstrap/src/tabs/tabs.js',
'public/lib/angular-ui-bootstrap/src/tooltip/tooltip.js',
'public/lib/angular-ui-bootstrap/src/typeahead/typeahead.js',
'public/lib/moment/moment.js',
'public/lib/angular-moment/angular-moment.js',
'public/lib/medium-editor/dist/js/medium-editor.js',
'public/lib/leaflet/dist/leaflet-src.js',
'public/lib/angular-simple-logger/dist/angular-simple-logger.js', // Required by angular-leaflet-directive
'public/lib/PruneCluster/dist/PruneCluster.js',
'public/lib/ui-leaflet/dist/ui-leaflet.js',
'public/lib/leaflet-active-area/src/leaflet.activearea.js',
'public/lib/angular-waypoints/dist/angular-waypoints.all.js',
'public/lib/ng-file-upload/ng-file-upload.js',
'public/lib/message-center/message-center.js',
'public/lib/chosen/chosen.jquery.js',
'public/lib/angular-chosen-localytics/dist/angular-chosen.js',
'public/lib/angular-loading-bar/build/loading-bar.js',
'public/lib/angular-trustpass/dist/tr-trustpass.js',
'public/lib/mailcheck/src/mailcheck.js',
'public/lib/angular-mailcheck/angular-mailcheck.js',
'public/lib/angular-locker/dist/angular-locker.js',
'public/lib/angular-confirm-modal/angular-confirm.js',
'public/lib/angulargrid/angulargrid.js'
],
less: [
'public/lib/angular-trustpass/src/tr-trustpass.less',
// Bootstrap
// ---------
// Bootstrap core variables
'public/lib/bootstrap/less/variables.less',
// Bootstrap utility mixins
// See the full list from 'public/lib/bootstrap/less/mixins.less'
// Utility mixins
'public/lib/bootstrap/less/mixins/hide-text.less',
'public/lib/bootstrap/less/mixins/opacity.less',
'public/lib/bootstrap/less/mixins/image.less',
'public/lib/bootstrap/less/mixins/labels.less',
'public/lib/bootstrap/less/mixins/reset-filter.less',
'public/lib/bootstrap/less/mixins/resize.less',
'public/lib/bootstrap/less/mixins/responsive-visibility.less',
'public/lib/bootstrap/less/mixins/size.less',
'public/lib/bootstrap/less/mixins/tab-focus.less',
'public/lib/bootstrap/less/mixins/reset-text.less',
'public/lib/bootstrap/less/mixins/text-emphasis.less',
'public/lib/bootstrap/less/mixins/text-overflow.less',
'public/lib/bootstrap/less/mixins/vendor-prefixes.less',
// Component mixins
'public/lib/bootstrap/less/mixins/alerts.less',
'public/lib/bootstrap/less/mixins/buttons.less',
'public/lib/bootstrap/less/mixins/panels.less',
'public/lib/bootstrap/less/mixins/pagination.less',
'public/lib/bootstrap/less/mixins/list-group.less',
'public/lib/bootstrap/less/mixins/nav-divider.less',
'public/lib/bootstrap/less/mixins/forms.less',
'public/lib/bootstrap/less/mixins/progress-bar.less',
'public/lib/bootstrap/less/mixins/table-row.less',
// Skin mixins
'public/lib/bootstrap/less/mixins/background-variant.less',
'public/lib/bootstrap/less/mixins/border-radius.less',
'public/lib/bootstrap/less/mixins/gradients.less',
// Layout mixins
'public/lib/bootstrap/less/mixins/clearfix.less',
'public/lib/bootstrap/less/mixins/center-block.less',
'public/lib/bootstrap/less/mixins/nav-vertical-align.less',
'public/lib/bootstrap/less/mixins/grid-framework.less',
'public/lib/bootstrap/less/mixins/grid.less',
// Reset and dependencies
'public/lib/bootstrap/less/normalize.less',
'public/lib/bootstrap/less/print.less',
// 'public/lib/bootstrap/less/glyphicons.less',
// Core CSS
'public/lib/bootstrap/less/scaffolding.less',
'public/lib/bootstrap/less/type.less',
// 'public/lib/bootstrap/less/code.less',
'public/lib/bootstrap/less/grid.less',
'public/lib/bootstrap/less/tables.less',
'public/lib/bootstrap/less/forms.less',
'public/lib/bootstrap/less/buttons.less',
// Components
'public/lib/bootstrap/less/component-animations.less',
'public/lib/bootstrap/less/dropdowns.less',
'public/lib/bootstrap/less/button-groups.less',
'public/lib/bootstrap/less/input-groups.less',
'public/lib/bootstrap/less/navs.less',
'public/lib/bootstrap/less/navbar.less',
// 'public/lib/bootstrap/less/breadcrumbs.less',
// 'public/lib/bootstrap/less/pagination.less',
// 'public/lib/bootstrap/less/pager.less',
'public/lib/bootstrap/less/labels.less',
'public/lib/bootstrap/less/badges.less',
// 'public/lib/bootstrap/less/jumbotron.less',
// 'public/lib/bootstrap/less/thumbnails.less',
'public/lib/bootstrap/less/alerts.less',
'public/lib/bootstrap/less/progress-bars.less',
'public/lib/bootstrap/less/media.less',
'public/lib/bootstrap/less/list-group.less',
'public/lib/bootstrap/less/panels.less',
// 'public/lib/bootstrap/less/responsive-embed.less',
// 'public/lib/bootstrap/less/wells.less',
'public/lib/bootstrap/less/close.less',
// Components w/ JavaScript
'public/lib/bootstrap/less/modals.less',
'public/lib/bootstrap/less/tooltip.less',
'public/lib/bootstrap/less/popovers.less',
// 'public/lib/bootstrap/less/carousel.less',
// Utility classes
'public/lib/bootstrap/less/utilities.less',
'public/lib/bootstrap/less/responsive-utilities.less'
],
tests: ['public/lib/angular-mocks/angular-mocks.js']
},
less: [
'modules/core/client/app/less/*.less',
'modules/core/client/less/**/*.less',
'modules/*/client/less/*.less'
],
js: [
'modules/core/client/app/config.js',
'modules/core/client/app/init.js',
'modules/*/client/*.js',
'modules/*/client/controllers/*.js',
'modules/*/client/**/*.js'
],
views: ['modules/*/client/views/**/*.html']
},
server: {
fontelloConfig: 'modules/core/client/fonts/fontello/config.json',
gulpConfig: 'gulpfile.js',
workerJS: ['worker.js', 'config/**/*.js'],
allJS: ['server.js', 'config/**/*.js', 'modules/*/server/**/*.js'],
models: 'modules/*/server/models/**/*.js',
routes: ['modules/!(core)/server/routes/**/*.js', 'modules/core/server/routes/**/*.js'],
config: 'modules/*/server/config/*.js',
policies: 'modules/*/server/policies/*.js',
views: 'modules/*/server/views/*.html'
}
};
|
(function (w) {
var $ = w.$,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
my = w.ilm,
contid = 0;
function fixCharts(width, fn) {
$(fn).css("width", width);
$(d).ready(function () {
var inner = $(fn).width();
setTimeout(function () {
$.each(w.ilm.charts, function (i, obj) {
obj.setSize($(fn).width() - 6, obj.containerHeight, false);
});
}, 500);
});
}
function setWidth() {
console.log(w.ilm.getWidth());
var inner = ((w.ilm.getWidth() < 1024) ? "100" : "50") + "%";
$('.float').each(function () {
fixCharts(inner, this);
});
}
w.ilm.popup="";
w.ilm.Options = function(state){
var t = this, f = $("#lingid"), g = $("#sl");
g.html("Seaded (klikk varjamiseks)");
my.settingTemplate(f);
return false;
};
w.ilm.Lingid = function (state) {
var t = this, f = $("#lingid"), g = $("#sl");
g.html("Lingid (klikk varjamiseks)");
f.html(w.ilm.lingid.process(w.ilm.lingid.JSON));
return false;
};
w.ilm.Popup = function(name, cb) {
var v = $("#popup");
if(!v) return false;
var b = $("#bghide"), hh = $('.navbar').height(), y = w.innerHeight || e.clientHeight || g.clientHeight,
act = v.attr("name"),swp = 0;
if (act) $("#ilm-" + act).parent().removeClass("active");
if(name && (!act || (act && act !== name))) {
b.css({height : $(d).height(), position : 'absolute', left : 0, top : 0}).show();
v.attr("name", name);
$("#ilm-" + name).parent().addClass("active");
if(cb) cb.call(this, name);
swp = ((y/2) - (v.height()/2)) + $(w).scrollTop();
v.css({top : (swp > 0 ? swp : hh)}).show();
}
else if(v.is(":visible")) {
v.hide();
b.hide();
v.attr("name", "");
}
return false;
};
$(d).ready(function () {
$("#pagelogo").html(ilm.logo);
//setWidth();
$("#ilm-viited").click(function(e){
//ilm.showLinks();
var b = $(e.target);
if(w.ilm.linksasmenu) {
b.attr({"data-toggle":"dropdown"});
b.addClass("dropdown-toggle");
var a = $(".ilm-viited-dropdown");
a.html(w.ilm.lingid.process(w.ilm.lingid.JSON));
a.height(w.innerHeight-(w.innerHeight/3));
} else {
b.removeClass("dropdown-toggle");
b.removeAttr("data-toggle");
w.ilm.Popup("viited",w.ilm.Lingid);
}
//return false;
});
$("#ilm-seaded").click(function(e){
my.settingTemplate("#ilm-seaded-dropdown");
//w.ilm.Popup("seaded",w.ilm.Options);
//return false;
});
$("#fctitle").on("click",function(){
w.ilm.setEstPlace(w.ilm.nextPlace());
//w.ilm.reloadest();
return false;
});
$("#datepicker").datepicker({
dateFormat: 'yy-mm-dd',
timezone: "+0"+(((my.addDst)?1:0)+2)+"00",
onSelect: function(dateText, inst) {
w.ilm.setDate(dateText);
//w.ilm.reload();
}
});
$("#curtime").on("click",function(){
$("#datepicker").datepicker('show');
});
$("#curplace").on("click",function(){
w.ilm.setCurPlace(w.ilm.nextCurPlace());
//w.ilm.reload();
return false;
});
w.ilm.loadBase();
w.ilm.loadInt(1000 * 60); // 1min
w.ilm.loadEstInt(1000 * 60 * 10); // 10min
$('#backgr').css({"display" : "block"});
$(w).on("keydown", function (e) {
//w.console.log("pressed" + e.keyCode);
var obj = $("#popup");
if(!obj) return;
if (e.keyCode === 27 || e.keyCode === 13 ) {
w.ilm.Popup("lingid", w.ilm.Lingid);
}
/*if (e.keyCode === 27 && obj.style.display === "block") {
w.ilm.showLinks();
}
else if (e.keyCode === 13 && obj.style.display === "none") {
w.ilm.showLinks();
}*/
});
$(w).on('hashchange', function() {
console.log("hash changed " + w.location.hash);
w.ilm.hash_data();
});
});
})(window);
|
import setupStore from 'dummy/tests/helpers/store';
import Ember from 'ember';
import {module, test} from 'qunit';
import DS from 'ember-data';
var env, store;
var attr = DS.attr;
var hasMany = DS.hasMany;
var belongsTo = DS.belongsTo;
var run = Ember.run;
var Post, Tag;
module("unit/many_array - DS.ManyArray", {
beforeEach() {
Post = DS.Model.extend({
title: attr('string'),
tags: hasMany('tag', { async: false })
});
Tag = DS.Model.extend({
name: attr('string'),
post: belongsTo('post', { async: false })
});
env = setupStore({
post: Post,
tag: Tag
});
store = env.store;
},
afterEach() {
run(function() {
store.destroy();
});
}
});
test("manyArray.save() calls save() on all records", function(assert) {
assert.expect(3);
run(function() {
Tag.reopen({
save() {
assert.ok(true, 'record.save() was called');
return Ember.RSVP.resolve();
}
});
store.push({
data: [{
type: 'tag',
id: '1',
attributes: {
name: 'Ember.js'
}
}, {
type: 'tag',
id: '2',
attributes: {
name: 'Tomster'
}
}, {
type: 'post',
id: '3',
attributes: {
title: 'A framework for creating ambitious web applications'
},
relationships: {
tags: {
data: [
{ type: 'tag', id: '1' },
{ type: 'tag', id: '2' }
]
}
}
}]
});
var post = store.peekRecord('post', 3);
post.get('tags').save().then(function() {
assert.ok(true, 'manyArray.save() promise resolved');
});
});
});
test("manyArray trigger arrayContentChange functions with the correct values", function(assert) {
assert.expect(12);
var willChangeStartIdx;
var willChangeRemoveAmt;
var willChangeAddAmt;
var originalArrayContentWillChange = DS.ManyArray.prototype.arrayContentWillChange;
var originalArrayContentDidChange = DS.ManyArray.prototype.arrayContentDidChange;
DS.ManyArray.reopen({
arrayContentWillChange(startIdx, removeAmt, addAmt) {
willChangeStartIdx = startIdx;
willChangeRemoveAmt = removeAmt;
willChangeAddAmt = addAmt;
return this._super.apply(this, arguments);
},
arrayContentDidChange(startIdx, removeAmt, addAmt) {
assert.equal(startIdx, willChangeStartIdx, 'WillChange and DidChange startIdx should match');
assert.equal(removeAmt, willChangeRemoveAmt, 'WillChange and DidChange removeAmt should match');
assert.equal(addAmt, willChangeAddAmt, 'WillChange and DidChange addAmt should match');
return this._super.apply(this, arguments);
}
});
run(function() {
store.push({
data: [{
type: 'tag',
id: '1',
attributes: {
name: 'Ember.js'
}
}, {
type: 'tag',
id: '2',
attributes: {
name: 'Tomster'
}
}, {
type: 'post',
id: '3',
attributes: {
title: 'A framework for creating ambitious web applications'
},
relationships: {
tags: {
data: [
{ type: 'tag', id: '1' }
]
}
}
}]
});
store.peekRecord('post', 3);
store.push({
data: {
type: 'post',
id: '3',
attributes: {
title: 'A framework for creating ambitious web applications'
},
relationships: {
tags: {
data: [
{ type: 'tag', id: '1' },
{ type: 'tag', id: '2' }
]
}
}
}
});
store.peekRecord('post', 3);
});
DS.ManyArray.reopen({
arrayContentWillChange: originalArrayContentWillChange,
arrayContentDidChange: originalArrayContentDidChange
});
});
|
import WordSearch from './word-search';
describe('single line grids', () => {
test('Should accept an initial game grid', () => {
const grid = ['jefblpepre'];
const wordSearch = new WordSearch(grid);
expect(wordSearch instanceof WordSearch).toEqual(true);
});
xtest('can accept a target search word', () => {
const grid = ['jefblpepre'];
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['glasnost'])).toEqual({ glasnost: undefined });
});
xtest('should locate a word written left to right', () => {
const grid = ['clojurermt'];
const expectedResults = {
clojure: {
start: [1, 1],
end: [1, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a different position', () => {
const grid = ['mtclojurer'];
const expectedResults = {
clojure: {
start: [1, 3],
end: [1, 9],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a different left to right word', () => {
const grid = ['coffeelplx'];
const expectedResults = {
coffee: {
start: [1, 1],
end: [1, 6],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['coffee'])).toEqual(expectedResults);
});
xtest('can locate that different left to right word in a different position', () => {
const grid = ['xcoffeezlp'];
const expectedResults = {
coffee: {
start: [1, 2],
end: [1, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['coffee'])).toEqual(expectedResults);
});
});
describe('multi line grids', () => {
xtest('can locate a left to right word in a two line grid', () => {
const grid = ['jefblpepre', 'clojurermt'];
const expectedResults = {
clojure: {
start: [2, 1],
end: [2, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a different position in a two line grid', () => {
const grid = ['jefblpepre', 'tclojurerm'];
const expectedResults = {
clojure: {
start: [2, 2],
end: [2, 8],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a three line grid', () => {
const grid = ['camdcimgtc', 'jefblpepre', 'clojurermt'];
const expectedResults = {
clojure: {
start: [3, 1],
end: [3, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a ten line grid', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a left to right word in a different position in a ten line grid', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'clojurermt',
'jalaycalmp',
];
const expectedResults = {
clojure: {
start: [9, 1],
end: [9, 7],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['clojure'])).toEqual(expectedResults);
});
xtest('can locate a different left to right word in a ten line grid', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'clojurermt',
'jalaycalmp',
];
const expectedResults = {
scree: {
start: [7, 1],
end: [7, 5],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['scree'])).toEqual(expectedResults);
});
});
describe('can find multiple words', () => {
xtest('can find two words written left to right', () => {
const grid = [
'aefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
'xjavamtzlp',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
java: {
start: [11, 2],
end: [11, 5],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['java', 'clojure'])).toEqual(expectedResults);
});
});
describe('different directions', () => {
xtest('should locate a single word written right to left', () => {
const grid = ['rixilelhrs'];
const expectedResults = {
elixir: {
start: [1, 6],
end: [1, 1],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['elixir'])).toEqual(expectedResults);
});
xtest('should locate multiple words written in different horizontal directions', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['elixir', 'clojure'])).toEqual(expectedResults);
});
});
describe('vertical directions', () => {
xtest('should locate words written top to bottom', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['elixir', 'clojure', 'ecmascript'])).toEqual(
expectedResults
);
});
xtest('should locate words written bottom to top', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find(['elixir', 'clojure', 'ecmascript', 'rust'])
).toEqual(expectedResults);
});
xtest('should locate words written top left to bottom right', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find(['clojure', 'elixir', 'ecmascript', 'rust', 'java'])
).toEqual(expectedResults);
});
xtest('should locate words written bottom right to top left', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
lua: {
start: [9, 8],
end: [7, 6],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find([
'clojure',
'elixir',
'ecmascript',
'rust',
'java',
'lua',
])
).toEqual(expectedResults);
});
xtest('should locate words written bottom left to top right', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
lua: {
start: [9, 8],
end: [7, 6],
},
lisp: {
start: [6, 3],
end: [3, 6],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find([
'clojure',
'elixir',
'ecmascript',
'rust',
'java',
'lua',
'lisp',
])
).toEqual(expectedResults);
});
xtest('should locate words written top right to bottom left', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
clojure: {
start: [10, 1],
end: [10, 7],
},
elixir: {
start: [5, 6],
end: [5, 1],
},
ecmascript: {
start: [1, 10],
end: [10, 10],
},
rust: {
start: [5, 9],
end: [2, 9],
},
java: {
start: [1, 1],
end: [4, 4],
},
lua: {
start: [9, 8],
end: [7, 6],
},
lisp: {
start: [6, 3],
end: [3, 6],
},
ruby: {
start: [6, 8],
end: [9, 5],
},
};
const wordSearch = new WordSearch(grid);
expect(
wordSearch.find([
'clojure',
'elixir',
'ecmascript',
'rust',
'java',
'lua',
'lisp',
'ruby',
])
).toEqual(expectedResults);
});
describe("word doesn't exist", () => {
xtest('should fail to locate a word that is not in the puzzle', () => {
const grid = [
'jefblpepre',
'camdcimgtc',
'oivokprjsm',
'pbwasqroua',
'rixilelhrs',
'wolcqlirpc',
'screeaumgr',
'alxhpburyi',
'jalaycalmp',
'clojurermt',
];
const expectedResults = {
fail: undefined,
};
const wordSearch = new WordSearch(grid);
expect(wordSearch.find(['fail'])).toEqual(expectedResults);
});
});
});
|
'use strict';
/* Controllers */
angular.module('myApp.controllers')
.controller('DatepickerDemoCtrl', ['$scope','$timeout',function($scope, $timeout) {
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.showWeeks = true;
$scope.toggleWeeks = function () {
$scope.showWeeks = ! $scope.showWeeks;
};
$scope.clear = function () {
$scope.dt = null;
};
// Disable weekend selection
$scope.disabled = function(date, mode) {
return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
};
$scope.toggleMin = function() {
$scope.minDate = ( $scope.minDate ) ? null : new Date();
};
$scope.toggleMin();
$scope.open = function() {
$timeout(function() {
$scope.opened = true;
});
};
$scope.dateOptions = {
'year-format': "'yy'",
'starting-day': 1
};
}])
|
import {Manager} from './manager'
export {Filterer} from './filter';
export {Logger} from './logger';
export {Manager};
var logging = new Manager();
export default logging;
|
/**
* Created by larry on 2017/1/6.
*/
import React from 'react';
import Todo from './Todo';
//圆括号里面要写大括号
const TodoList = ({todos, onTodoClick}) => {
return (
<ul>
{
todos.map
(
todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)
}
</ul>
)
};
export default TodoList; |
requirejs.config({
// baseUrl: '/',
paths: {
lodash: '//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash',
jquery: '//code.jquery.com/jquery-1.11.0.min',
react: '//cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react-with-addons'
},
shim: {
lodash: {exports: '_'},
jquery: {exports: '$'},
react: {exports: 'React'}
}
})
requirejs(['jquery', 'react', 'ImageSearch'], function ($, React, ImageSearch) {
'use strict'
React.renderComponent(ImageSearch(), $('#main').get(0)) //eslint-disable-line new-cap
})
|
export const bubble = {"viewBox":"0 0 16 16","children":[{"name":"path","attribs":{"fill":"#000000","d":"M8 1c4.418 0 8 2.91 8 6.5s-3.582 6.5-8 6.5c-0.424 0-0.841-0.027-1.247-0.079-1.718 1.718-3.77 2.027-5.753 2.072v-0.421c1.071-0.525 2-1.48 2-2.572 0-0.152-0.012-0.302-0.034-0.448-1.809-1.192-2.966-3.012-2.966-5.052 0-3.59 3.582-6.5 8-6.5z"}}]}; |
export { default } from 'ember-fhir/serializers/timing-repeat'; |
$(document).ready(function() {
//Note: default min/max ranges are defined outside of this JS file
//include "js/BoulderRouteGradingSystems.js" before running this script
//generate Bouldering rating selection upon click
//Find which boulder grading system is selected and update the difficulty range
//**********************************************
$("select[name='boulder-rating-select']").click(function()
{
var boulderGradingSelect = document.getElementById("boulder-rating-select");
boulderGradingID = boulderGradingSelect.options[boulderGradingSelect.selectedIndex].value;
console.log(boulderGradingID);
var maxBoulder = boulderRatings[boulderGradingID].length - 1;
var boulderingMinRange = "<div id='boulderprefs'><p>Minimum bouldering rating: <select name='minBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==selectMinBoulder) {
boulderingMinRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMinRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMinRange += "</option></select>";
//get max value of bouldering range
var boulderingMaxRange = "<p>Maximum bouldering rating: <select name='maxBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==Math.min(maxBoulder,selectMaxBoulder)) {
boulderingMaxRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMaxRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMaxRange += "</option></select></div>";
document.getElementById("boulderprefs").innerHTML =
boulderingMinRange + boulderingMaxRange;
});
//**********************************************
//initialize the boulder grading system
var maxBoulder = boulderRatings[boulderGradingID].length - 1;
var boulderingMinRange = "<div id='boulderprefs'><p>Minimum bouldering rating: <select name='minBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==selectMinBoulder) {
boulderingMinRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMinRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMinRange += "</option></select>";
//get max value of bouldering range
var boulderingMaxRange = "<p>Maximum bouldering rating: <select name='maxBoulderRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxBoulder;i++) {
if (i==Math.min(maxBoulder,selectMaxBoulder)) {
boulderingMaxRange += "<option value="+i+" selected>"+boulderRatings[boulderGradingID][i]+"</option>";
} else {
boulderingMaxRange += "<option value="+i+">"+boulderRatings[boulderGradingID][i]+"</option>";
}
}
boulderingMaxRange += "</option></select></div>";
//************************
//Update TR and lead when clicked
//******************************
$("select[name='route-rating-select']").click(function()
{
var routeGradingSelect = document.getElementById("route-rating-select");
routeGradingID = routeGradingSelect.options[routeGradingSelect.selectedIndex].value;
console.log(routeGradingID);
var maxRoute = routeRatings[routeGradingID].length - 1;
//generate TR rating selection
var TRMinRange = "<div id='trprefs'><p>Minimum top-rope rating: <select name='minTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinTR) {
TRMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMinRange += "</option></select>";
var TRMaxRange = "<p>Maximum top-rope rating: <select name='maxTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxTR)) {
TRMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMaxRange += "</option></select></div>";
//generate lead rating selection
var LeadMinRange = "<div id='leadprefs'><p>Minimum lead rating: <select name='minLeadRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinL) {
LeadMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMinRange += "</option></select>";
var LeadMaxRange = "<p>Maximum lead rating: <select name='maxLeadRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxL)) {
LeadMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMaxRange += "</option></select></div>";
document.getElementById("trprefs").innerHTML = TRMinRange + TRMaxRange;
document.getElementById("leadprefs").innerHTML =
LeadMinRange + LeadMaxRange;
});
//**********************************
//Initialize TR and Lead selections
var maxRoute = routeRatings[routeGradingID].length - 1;
//generate TR rating selection
var TRMinRange = "<div id='trprefs'><p>Minimum top-rope rating: <select name='minTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinTR) {
TRMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMinRange += "</option></select>";
var TRMaxRange = "<p>Maximum top-rope rating: <select name='maxTRRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxTR)) {
TRMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
TRMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
TRMaxRange += "</option></select></div>";
//generate lead rating selection
var LeadMinRange = "<div id='leadprefs'><p>Minimum lead rating: <select name='minLeadRange' class='form-control' id='rating-range-select'>";
for (var i = 0;i<=maxRoute;i++) {
if (i==selectMinL) {
LeadMinRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMinRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMinRange += "</option></select>";
var LeadMaxRange = "<p>Maximum lead rating: <select name='maxLeadRange' class='form-control' id='rating-range-select'> ";
for (var i = 0;i<=maxRoute;i++) {
if (i==Math.min(maxRoute,selectMaxL)) {
LeadMaxRange +="<option value="+i+" selected>"+
routeRatings[routeGradingID][i]+"</option>";
} else {
LeadMaxRange += "<option value="+i+">"+
routeRatings[routeGradingID][i]+"</option>";
}
}
LeadMaxRange += "</option></select></div>";
//write rating preferences to html
document.getElementById("ratingrange").innerHTML =
boulderingMinRange + boulderingMaxRange + TRMinRange + TRMaxRange +
LeadMinRange + LeadMaxRange;
$("select[name='country-select']").click(function()
{
//get country value
var country = document.getElementById("country-select");
var countryID = country.options[country.selectedIndex].value;
console.log(countryID);
//determine best guess for grading system?
});
$("input[name='showBoulder']").click(function()
{
if ($(this).is(':checked')) {
$("#boulderprefs").show();
}
else {
$("#boulderprefs").hide();
}
});
$("input[name='showTR']").click(function()
{
if ($(this).is(':checked')) {
$("#trprefs").show();
}
else {
$("#trprefs").hide();
}
});
$("input[name='showLead']").click(function()
{
if ($(this).is(':checked')) {
$("#leadprefs").show();
}
else {
$("#leadprefs").hide();
}
});
});
|
'use strict';
jQuery(document).ready(function ($) {
var lastId,
topMenu = $("#top-navigation"),
topMenuHeight = topMenu.outerHeight(),
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function () {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
//Get width of container
var containerWidth = $('.section .container').width();
//Resize animated triangle
$(".triangle").css({
"border-left": containerWidth / 2 + 'px outset transparent',
"border-right": containerWidth / 2 + 'px outset transparent'
});
//resize
$(window).resize(function () {
containerWidth = $('.container').width();
$(".triangle").css({
"border-left": containerWidth / 2 + 'px outset transparent',
"border-right": containerWidth / 2 + 'px outset transparent'
});
});
//mask
$('.has-mask').each( function() {
var $this = $( this ),
mask = $this.data( 'aria-mask' );
$this.mask( mask );
});
//Initialize header slider.
$('#da-slider').cslider();
//Initial mixitup, used for animated filtering portgolio.
$('#portfolio-grid').mixitup({
'onMixStart': function (config) {
$('div.toggleDiv').hide();
}
});
//Initial Out clients slider in client section
$('#clint-slider').bxSlider({
pager: false,
minSlides: 1,
maxSlides: 5,
moveSlides: 2,
slideWidth: 210,
slideMargin: 25,
prevSelector: $('#client-prev'),
nextSelector: $('#client-next'),
prevText: '<i class="icon-left-open"></i>',
nextText: '<i class="icon-right-open"></i>'
});
$('input, textarea').placeholder();
// Bind to scroll
$(window).scroll(function () {
//Display or hide scroll to top button
if ($(this).scrollTop() > 100) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
if ($(this).scrollTop() > 100) {
$('.navbar').addClass('navbar-fixed-top animated fadeInDown');
} else {
$('.navbar').removeClass('navbar-fixed-top animated fadeInDown');
}
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight + 10;
// Get id of current scroll item
var cur = scrollItems.map(function () {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
/*
Function for scroliing to top
************************************/
$('.scrollup').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
/*
Sand newsletter
**********************************************************************/
$('#subscribe').click(function () {
var error = false;
var emailCompare = /^([a-z0-9_.-]+)@([0-9a-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
var email = $('input#nlmail').val().toLowerCase(); // get the value of the input field
if (email == "" || email == " " || !emailCompare.test(email)) {
$('#err-subscribe').show(500);
$('#err-subscribe').delay(4000);
$('#err-subscribe').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
if (error === false) {
$.ajax({
type: 'POST',
url: 'php/newsletter.php',
data: {
email: $('#nlmail').val()
},
error: function (request, error) {
alert("An error occurred");
},
success: function (response) {
if (response == 'OK') {
$('#success-subscribe').show();
$('#nlmail').val('')
} else {
alert("An error occurred");
}
}
});
}
return false;
});
/*
Sand mail
**********************************************************************/
$("#send-mail").click(function () {
var name = $('input#name').val(); // get the value of the input field
var error = false;
if (name == "" || name == " ") {
$('#err-name').show(500);
$('#err-name').delay(4000);
$('#err-name').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var emailCompare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; // Syntax to compare against input
var email = $('input#email').val().toLowerCase(); // get the value of the input field
if (email == "" || email == " " || !emailCompare.test(email)) {
$('#err-email').show(500);
$('#err-email').delay(4000);
$('#err-email').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
var comment = $('textarea#comment').val(); // get the value of the input field
if (comment == "" || comment == " ") {
$('#err-comment').show(500);
$('#err-comment').delay(4000);
$('#err-comment').animate({
height: 'toggle'
}, 500, function () {
// Animation complete.
});
error = true; // change the error state to true
}
if (error == false) {
var dataString = $('#contact-form').serialize(); // Collect data from form
$.ajax({
type: "POST",
url: $('#contact-form').attr('action'),
data: dataString,
timeout: 6000,
error: function (request, error) {
},
success: function (response) {
response = $.parseJSON(response);
if (response.success) {
$('#successSend').show();
$("#name").val('');
$("#email").val('');
$("#comment").val('');
} else {
$('#errorSend').show();
}
}
});
return false;
}
return false; // stops user browser being directed to the php file
});
//Function for show or hide portfolio desctiption.
$.fn.showHide = function (options) {
var defaults = {
speed: 1000,
easing: '',
changeText: 0,
showText: 'Show',
hideText: 'Hide'
};
var options = $.extend(defaults, options);
$(this).click(function () {
$('.toggleDiv').slideUp(options.speed, options.easing);
var toggleClick = $(this);
var toggleDiv = $(this).attr('rel');
$(toggleDiv).slideToggle(options.speed, options.easing, function () {
if (options.changeText == 1) {
$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
}
});
return false;
});
};
//Initial Show/Hide portfolio element.
$('div.toggleDiv').hide();
/************************
Animate elements
*************************/
//Animate thumbnails
jQuery('.thumbnail').one('inview', function (event, visible) {
if (visible == true) {
jQuery(this).addClass("animated fadeInDown");
} else {
jQuery(this).removeClass("animated fadeInDown");
}
});
//Animate triangles
jQuery('.triangle').bind('inview', function (event, visible) {
if (visible == true) {
jQuery(this).addClass("animated fadeInDown");
} else {
jQuery(this).removeClass("animated fadeInDown");
}
});
//animate first team member
jQuery('#first-person').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('#first-person').addClass("animated pulse");
} else {
jQuery('#first-person').removeClass("animated pulse");
}
});
//animate sectond team member
jQuery('#second-person').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('#second-person').addClass("animated pulse");
} else {
jQuery('#second-person').removeClass("animated pulse");
}
});
//animate thrid team member
jQuery('#third-person').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('#third-person').addClass("animated pulse");
} else {
jQuery('#third-person').removeClass("animated pulse");
}
});
//Animate price columns
jQuery('.price-column, .testimonial').bind('inview', function (event, visible) {
if (visible == true) {
jQuery(this).addClass("animated fadeInDown");
} else {
jQuery(this).removeClass("animated fadeInDown");
}
});
//Animate contact form
jQuery('.contact-form').bind('inview', function (event, visible) {
if (visible == true) {
jQuery('.contact-form').addClass("animated bounceIn");
} else {
jQuery('.contact-form').removeClass("animated bounceIn");
}
});
//Animate skill bars
jQuery('.skills > li > span').one('inview', function (event, visible) {
if (visible == true) {
jQuery(this).each(function () {
jQuery(this).animate({
width: jQuery(this).attr('data-width')
}, 3000);
});
}
});
//initialize pluging
$("a[rel^='prettyPhoto']").prettyPhoto();
//contact form
function enviainfocurso()
{
$.ajax({
type: "POST",
url: "php/phpscripts/infocurso.php",
async: true,
data: $('form.informacao').serialize(),
});
alert('Entraremos em breve em contato com você');
}
//analytics
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-62932901-1', 'auto');
ga('send', 'pageview');
}); // end ready()
$(window).load(function () {
function filterPath(string) {
return string.replace(/^\//, '').replace(/(index|default).[a-zA-Z]{3,4}$/, '').replace(/\/$/, '');
}
$('a[href*=#]').each(function () {
if (filterPath(location.pathname) == filterPath(this.pathname) && location.hostname == this.hostname && this.hash.replace(/#/, '')) {
var $targetId = $(this.hash),
$targetAnchor = $('[name=' + this.hash.slice(1) + ']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ( $target ) {
$(this).click(function (e) {
e.preventDefault();
//Hack collapse top navigation after clicking
// topMenu.parent().attr('style', 'height:0px').removeClass('in'); //Close navigation
$('.navbar .btn-navbar').addClass('collapsed');
var targetOffset = $target.offset().top - 63;
$('html, body').animate({
scrollTop: targetOffset
}, 800);
return false;
});
}
}
});
});
//Initialize google map for contact setion with your location.
function initializeMap() {
if( $("#map-canvas").length ) {
var lat = '-8.0618743';//-8.055967'; //Set your latitude.
var lon = '-34.8734548';//'-34.896303'; //Set your longitude.
var centerLon = lon - 0.0105;
var myOptions = {
scrollwheel: false,
draggable: false,
disableDefaultUI: true,
center: new google.maps.LatLng(lat, centerLon),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Bind map to elemet with id map-canvas
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lon),
});
//var infowindow = new google.maps.InfoWindow();
//google.maps.event.addListener(marker, 'click', function () {
// infowindow.open(map, marker);
//});
// infowindow.open(map, marker);
}
} |
/* eslint-env jasmine, jest */
import React from 'react';
import View from '../';
import StyleSheet from '../../StyleSheet';
import { act } from 'react-dom/test-utils';
import { createEventTarget } from 'dom-event-testing-library';
import { render } from '@testing-library/react';
describe('components/View', () => {
test('default', () => {
const { container } = render(<View />);
expect(container.firstChild).toMatchSnapshot();
});
test('non-text is rendered', () => {
const children = <View testID="1" />;
const { container } = render(<View>{children}</View>);
expect(container.firstChild).toMatchSnapshot();
});
describe('raw text nodes as children', () => {
beforeEach(() => {
jest.spyOn(console, 'error');
console.error.mockImplementation(() => {});
});
afterEach(() => {
console.error.mockRestore();
});
test('error logged (single)', () => {
render(<View>hello</View>);
expect(console.error).toBeCalled();
});
test('error logged (array)', () => {
render(
<View>
<View />
hello
<View />
</View>
);
expect(console.error).toBeCalled();
});
});
describe('prop "accessibilityLabel"', () => {
test('value is set', () => {
const { container } = render(<View accessibilityLabel="accessibility label" />);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('prop "accessibilityLabelledBy"', () => {
test('value is set', () => {
const { container } = render(<View accessibilityLabelledBy="123" />);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('prop "accessibilityLiveRegion"', () => {
test('value is set', () => {
const { container } = render(<View accessibilityLiveRegion="polite" />);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('prop "accessibilityRole"', () => {
test('value is set', () => {
const { container } = render(<View accessibilityRole="none" />);
expect(container.firstChild).toMatchSnapshot();
});
test('value is "button"', () => {
const { container } = render(<View accessibilityRole="button" />);
expect(container.firstChild).toMatchSnapshot();
});
test('value alters HTML element', () => {
const { container } = render(<View accessibilityRole="article" />);
expect(container.firstChild).toMatchSnapshot();
});
});
test('allows "dir" to be overridden', () => {
const { container } = render(<View dir="rtl" />);
expect(container.firstChild).toMatchSnapshot();
});
describe('prop "href"', () => {
test('value is set', () => {
const { container } = render(<View href="https://example.com" />);
expect(container.firstChild).toMatchSnapshot();
});
test('href with accessibilityRole', () => {
const { container } = render(<View accessibilityRole="none" href="https://example.com" />);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('prop "hrefAttrs"', () => {
test('requires "href"', () => {
const { container } = render(<View hrefAttrs={{ download: 'filename.jpg' }} />);
expect(container.firstChild).toMatchSnapshot();
});
test('value is set', () => {
const hrefAttrs = {
download: 'filename.jpg',
rel: 'nofollow',
target: '_blank'
};
const { container } = render(<View href="https://example.com" hrefAttrs={hrefAttrs} />);
expect(container.firstChild).toMatchSnapshot();
});
test('target variant is set', () => {
const hrefAttrs = {
target: 'blank'
};
const { container } = render(<View href="https://example.com" hrefAttrs={hrefAttrs} />);
expect(container.firstChild).toMatchSnapshot();
});
test('null values are excluded', () => {
const hrefAttrs = {
download: null,
rel: null,
target: null
};
const { container } = render(<View href="https://example.com" hrefAttrs={hrefAttrs} />);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('prop "nativeID"', () => {
test('value is set', () => {
const { container } = render(<View nativeID="nativeID" />);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('prop "onBlur"', () => {
test('is called', () => {
const onBlur = jest.fn();
const ref = React.createRef();
act(() => {
render(<View onBlur={onBlur} ref={ref} />);
});
const target = createEventTarget(ref.current);
const body = createEventTarget(document.body);
act(() => {
target.focus();
body.focus({ relatedTarget: target.node });
});
expect(onBlur).toBeCalled();
});
});
describe('prop "onFocus"', () => {
test('is called', () => {
const onFocus = jest.fn();
const ref = React.createRef();
act(() => {
render(<View onFocus={onFocus} ref={ref} />);
});
const target = createEventTarget(ref.current);
act(() => {
target.focus();
target.blur();
});
expect(onFocus).toBeCalled();
});
});
describe('prop "ref"', () => {
test('value is set', () => {
const ref = jest.fn();
render(<View ref={ref} />);
expect(ref).toBeCalled();
});
test('is not called for prop changes', () => {
const ref = jest.fn();
let rerender;
act(() => {
({ rerender } = render(<View nativeID="123" ref={ref} style={{ borderWidth: 5 }} />));
});
expect(ref).toHaveBeenCalledTimes(1);
act(() => {
rerender(<View nativeID="1234" ref={ref} style={{ borderWidth: 6 }} />);
});
expect(ref).toHaveBeenCalledTimes(1);
});
test('node has imperative methods', () => {
const ref = React.createRef();
act(() => {
render(<View ref={ref} />);
});
const node = ref.current;
expect(typeof node.measure === 'function');
expect(typeof node.measureLayout === 'function');
expect(typeof node.measureInWindow === 'function');
expect(typeof node.setNativeProps === 'function');
});
describe('setNativeProps method', () => {
test('works with react-native props', () => {
const ref = React.createRef();
const { container } = render(<View ref={ref} />);
const node = ref.current;
node.setNativeProps({
accessibilityLabel: 'label',
pointerEvents: 'box-only',
style: {
marginHorizontal: 10,
shadowColor: 'black',
shadowWidth: 2,
textAlignVertical: 'top'
}
});
expect(container.firstChild).toMatchSnapshot();
});
test('style updates as expected', () => {
const ref = React.createRef();
const styles = StyleSheet.create({ root: { color: 'red' } });
// initial render
const { container, rerender } = render(
<View ref={ref} style={[styles.root, { width: 10 }]} />
);
const node = ref.current;
expect(container.firstChild).toMatchSnapshot();
// set native props
node.setNativeProps({ style: { color: 'orange', height: 20, width: 20 } });
expect(container.firstChild).toMatchSnapshot();
// set native props again
node.setNativeProps({ style: { width: 30 } });
expect(container.firstChild).toMatchSnapshot();
node.setNativeProps({ style: { width: 30 } });
node.setNativeProps({ style: { width: 30 } });
node.setNativeProps({ style: { width: 30 } });
expect(container.firstChild).toMatchSnapshot();
// update render
rerender(<View ref={ref} style={[styles.root, { width: 40 }]} />);
expect(container.firstChild).toMatchSnapshot();
});
});
});
test('prop "pointerEvents"', () => {
const { container } = render(<View pointerEvents="box-only" />);
expect(container.firstChild).toMatchSnapshot();
});
describe('prop "style"', () => {
test('value is set', () => {
const { container } = render(<View style={{ borderWidth: 5 }} />);
expect(container.firstChild).toMatchSnapshot();
});
});
describe('prop "testID"', () => {
test('value is set', () => {
const { container } = render(<View testID="123" />);
expect(container.firstChild).toMatchSnapshot();
});
});
});
|
/*
* Globalize Culture co
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd.
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "co", "default", {
name: "co",
englishName: "Corsican",
nativeName: "Corsu",
language: "co",
numberFormat: {
",": " ",
".": ",",
"NaN": "Mica numericu",
negativeInfinity: "-Infinitu",
positiveInfinity: "+Infinitu",
percent: {
",": " ",
".": ","
},
currency: {
pattern: ["-n $","n $"],
",": " ",
".": ",",
symbol: "€"
}
},
calendars: {
standard: {
firstDay: 1,
days: {
names: ["dumenica","luni","marti","mercuri","ghjovi","venderi","sabbatu"],
namesAbbr: ["dum.","lun.","mar.","mer.","ghj.","ven.","sab."],
namesShort: ["du","lu","ma","me","gh","ve","sa"]
},
months: {
names: ["ghjennaghju","ferraghju","marzu","aprile","maghju","ghjunghju","lugliu","aostu","settembre","ottobre","nuvembre","dicembre",""],
namesAbbr: ["ghje","ferr","marz","apri","magh","ghju","lugl","aost","sett","otto","nuve","dice",""]
},
AM: null,
PM: null,
eras: [{"name":"dopu J-C","start":null,"offset":0}],
patterns: {
d: "dd/MM/yyyy",
D: "dddd d MMMM yyyy",
t: "HH:mm",
T: "HH:mm:ss",
f: "dddd d MMMM yyyy HH:mm",
F: "dddd d MMMM yyyy HH:mm:ss",
M: "d MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
|
(function () {
'use strict';
angular.module('customers')
.controller('OneCustomerCtrl', function ($scope, customers, $stateParams) {
var cid = $stateParams.cid;
$scope.customer=_.find(customers, function (customer) {
return customer.profile.userName===cid;
});
console.log($scope.customer);
});
})();
|
var exptemplate = require('../prepublic/javascripts/exptemplate');
module.exports = exptemplate;
|
/**
* Created by jsturtevant on 1/18/14
*/
var DEFAULT_SHORTCUT_KEY = 'ctrl+shift+k';
var LOCAL_STORAGE_KEY = 'optionsStore'
var defaultOptions = {
shortcuts: [
{key: "", value:""}
],
cssSelectors: [{value:""}],
shortcutKey: DEFAULT_SHORTCUT_KEY,
includeIFrames: true
};
var optionsApp = angular.module('optionsApp', []);
optionsApp.factory('OptionsData', function() {
var optionsJSON = localStorage[LOCAL_STORAGE_KEY];
if (!optionsJSON){
return defaultOptions;
}
else{
return JSON.parse(optionsJSON);
}
});
optionsApp.directive("showhide", function() {
return function(scope, element, attrs) {
var bodyelement =angular.element(document.getElementById(attrs.showhide));
element.bind("mouseover", function() {
element.css("cursor", "pointer");
element.css('color', attrs.togglecolor);
})
element.bind("mouseleave", function() {
if (bodyelement.hasClass('hidden')){
element.css('color', "");
}
});
element.bind("click", function() {
angular.element(bodyelement).toggleClass('hidden');
element.css('color', attrs.togglecolor);
});
};
});
function OptionsCtrl($scope, OptionsData, $timeout){
$scope.options = OptionsData;
$scope.AddShortcut = function(){
$scope.options.shortcuts.push({key: "", value:""})
};
$scope.AddSelector = function(){
if (!$scope.options.cssSelectors){
$scope.options.cssSelectors = defaultOptions.cssSelectors;
}
$scope.options.cssSelectors.push({value: ""})
};
$scope.Save = function(){
localStorage[LOCAL_STORAGE_KEY] = JSON.stringify($scope.options);
$scope.message = 'Changes saved!';
$timeout(function() {
$scope.message = null;
}, 5 * 1000);
};
$scope.Delete = function (index){
$scope.options.shortcuts.splice(index,1);
};
$scope.DeleteSelector = function (index){
$scope.options.cssSelectors.splice(index,1);
};
};
|
import { fromJS, OrderedMap } from 'immutable';
const vaccines = fromJS([
{
name: 'AVA (BioThrax)',
id: '8b013618-439e-4829-b88f-98a44b420ee8',
diseases: ['Anthrax'],
},
{
name: 'VAR (Varivax)',
id: 'f3e08a56-003c-4b46-9dea-216298401ca0',
diseases: ['Varicella (Chickenpox)'],
},
{
name: 'MMRV (ProQuad)',
id: '3373721d-3d14-490c-9fa9-69a223888322',
diseases: [
'Varicella (Chickenpox)',
'Measles',
'Mumps',
'Rubella (German Measles)',
],
},
{
name: 'HepA (Havrix, Vaqta)',
id: 'a9144edf-13a2-4ce5-b6af-14eb38fd848c',
diseases: ['Hepatitis A'],
},
{
name: 'HepA-HepB (Twinrix)',
id: '6888fd1a-af4f-4f33-946d-40d4c473c9cc',
diseases: ['Hepatitis A', 'Hepatitis B'],
},
{
name: 'HepB (Engerix-B, Recombivax HB)',
id: 'ca079856-a561-4bc9-9bef-e62429ed3a38',
diseases: ['Hepatitis B'],
},
{
name: 'Hib-HepB (Comvax)',
id: '7305d769-0d1e-4bef-bd09-6998dc839825',
diseases: ['Hepatitis B', 'Haemophilus influenzae type b (Hib)'],
},
{
name: 'Hib (ActHIB, PedvaxHIB, Hiberix)',
id: 'd241f0c7-9920-4bc6-8f34-288a13e03f4d',
diseases: ['Haemophilus influenzae type b (Hib)'],
},
{
name: 'HPV4 (Gardasil)',
id: 'c2fef03c-db7f-483b-af70-50560712b189',
diseases: ['Human Papillomavirus (HPV)'],
},
{
name: 'HPV2 (Cervarix)',
id: '286f55e4-e727-4fc4-86b0-5a08ea712a77',
diseases: ['Human Papillomavirus (HPV)'],
},
{
name: 'TIV (Afluria, Agriflu, FluLaval, Fluarix, Fluvirin, Fluzone, Fluzone High-Dose, Fluzone Intradermal)', // eslint-disable-line max-len
id: '60e85a31-6a54-48e1-b0b7-deb28120675b',
diseases: ['Seasonal Influenza (Flu)'],
},
{
name: 'LAIV (FluMist)',
id: '9e67e321-9a7f-426f-ba9b-28885f93f9b9',
diseases: ['Seasonal Influenza (Flu)'],
},
{
name: 'JE (Ixiaro)',
id: '5ce00584-3350-442d-ac6c-7f19567eff8a',
diseases: ['Japanese Encephalitis'],
},
{
name: 'MMR (M-M-R II)',
id: 'd10b7bf0-d51e-4117-a6a4-08bdb5cb682a',
diseases: ['Measles', 'Mumps', 'Rubella (German Measles)'],
},
{
name: 'MCV4 (Menactra)',
id: '6295fe11-f0ce-4967-952c-f271416cc300',
diseases: ['Meningococcal'],
},
{
name: 'MPSV4 (Menomune)',
id: '65f6d6d0-6dd8-49c9-95da-ed9fa403ae96',
diseases: ['Meningococcal'],
},
{
name: 'MODC (Menveo)',
id: 'be10b480-7934-46be-a488-66540aac2881',
diseases: ['Meningococcal'],
},
{
name: 'Tdap (Adacel, Boostrix)',
id: '0c6c33fb-f4dc-44c6-8684-625099f6fa21',
diseases: ['Pertussis (Whooping Cough)', 'Tetanus (Lockjaw)', 'Diphtheria'],
},
{
name: 'PCV13 (Prevnar13)',
id: 'd8c5a723-21e2-49a6-a921-705da16563e1',
diseases: ['Pneumococcal'],
},
{
name: 'PPSV23 (Pneumovax 23)',
id: '4005de2f-8e6d-40ae-bb5f-068ac56885b8',
diseases: ['Pneumococcal'],
},
{
name: 'Polio (Ipol)',
id: '9c1582f2-8a7b-4bae-8ba5-656efe33fb29',
diseases: ['Polio'],
},
{
name: 'Rabies (Imovax Rabies, RabAvert)',
id: '2bfeeb1f-b7a7-4ce6-aae1-72e840a93e2e',
diseases: ['Rabies'],
},
{
name: 'RV1 (Rotarix)',
id: '8ddfa840-7558-469a-a53b-19a40d016518',
diseases: ['Rotavirus'],
},
{
name: 'RV5 (RotaTeq)',
id: '9281ddcb-5ef3-47e6-a249-6b2b8bee1e7f',
diseases: ['Rotavirus'],
},
{
name: 'ZOS (Zostavax)',
id: '2921b034-8a4c-46f5-9753-70a112dfec3f',
diseases: ['Shingles (Herpes Zoster)'],
},
{
name: 'Vaccinia (ACAM2000)',
id: 'e26378f4-5d07-4b5f-9c93-53816c0faf9f',
diseases: ['Smallpox'],
},
{
name: 'DTaP (Daptacel, Infanrix)',
id: 'b23e765e-a05b-4a24-8095-03d79e47a8aa',
diseases: [
'Tetanus (Lockjaw)',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'Td (Decavac, generic)',
id: '1af45230-cb2a-4242-81ac-2430cd64f8ce',
diseases: ['Tetanus (Lockjaw)', 'Diphtheria'],
},
{
name: 'DT (-generic-)',
id: '6eb77e28-aaa1-4e29-b124-5793a4bd6f1f',
diseases: ['Tetanus (Lockjaw)', 'Diphtheria'],
},
{
name: 'TT (-generic-)',
id: 'd6cf7277-831c-43c6-a1fa-7109d3325168',
diseases: ['Tetanus (Lockjaw)'],
},
{
name: 'DTaP-IPV (Kinrix)',
id: 'a8ecfef5-5f09-442c-84c3-4dfbcd99b3b8',
diseases: [
'Tetanus (Lockjaw)',
'Polio',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'DTaP-HepB-IPV (Pediarix)',
id: '10bc0626-7b0a-4a42-b1bf-2742f0435c37',
diseases: [
'Tetanus (Lockjaw)',
'Polio',
'Hepatitis B',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'DTaP-IPV/Hib (Pentacel)',
id: 'dcbb9691-1544-44fc-a9ca-351946010876',
diseases: [
'Tetanus (Lockjaw)',
'Polio',
'Haemophilus influenzae type b (Hib)',
'Pertussis (Whooping Cough)',
'Diphtheria',
],
},
{
name: 'DTaP/Hib',
id: 'e817c55d-e3db-4963-9fec-04d5823f6915',
diseases: [
'Tetanus (Lockjaw)',
'Diphtheria',
'Haemophilus influenzae type b (Hib)',
'Pertussis (Whooping Cough)',
],
},
{
name: 'BCG (TICE BCG, Mycobax)',
id: '8f2049a1-a1e3-44e1-947e-debbf3cafecc',
diseases: ['Tuberculosis (TB)'],
},
{
name: 'Typhoid Oral (Vivotif)',
id: '060f44be-e1e7-4575-ba0f-62611f03384b',
diseases: ['Typhoid Fever'],
},
{
name: 'Typhoid Polysaccharide (Typhim Vi)',
id: '87009829-1a48-4330-91e1-6bcd7ab04ee1',
diseases: ['Typhoid Fever'],
},
{
name: 'YF (YF-Vax)',
id: '24d5bfc4-d69a-4311-bb10-8980dddafa20',
diseases: ['Yellow Fever'],
},
]);
const keyedVaccines = vaccines.reduce((result, item) => (
result.set(item.get('id'), item)
), OrderedMap());
export default keyedVaccines.sortBy(vaccine => vaccine.get('name').toLowerCase());
|
(function (r) {
"use strict";
var events = r('events');
var eventEmitter = new events.EventEmitter();
var playerManager = r('../PlayerSetup/player-manager').playerManager;
var helper = r('../helpers');
var world = {
valston: r('../../World/valston/prison')
};
var time = function () {
var settings = {
tickCount: 0,
tickDuration: 45000,
ticksInDay: 48,
autoSaveTick: 300000,
sunrise: 11,
morning: 14,
midDay: 24,
afternoon: 30,
sunset: 36,
moonRise: 40,
night: 42,
midNight: 48,
twilight: 8,
hour: 0,
minute: 0
};
var recursive = function () {
eventEmitter.emit('updateTime');
eventEmitter.emit('updatePlayer', "hitpoints", "maxHitpoints", "constitution");
eventEmitter.emit('updatePlayer', "mana", "maxMana", "intelligence");
eventEmitter.emit('updatePlayer', "moves", "maxMoves", "dexterity");
eventEmitter.emit('updateRoom');
eventEmitter.emit('showPromptOnTick');
// console.log(year);
/*
* Every 45 Seconds update player health, mana, moves
* Update game clock, weather, other effects,
* trigger npc scripts?
* when to reset rooms?
* when to save world
*/
setTimeout(recursive, 50000);
}
/* Shows player prompt */
function showPromptOnTick() {
var player = playerManager.getPlayers;
playerManager.each(function (player) {
var socket = player.getSocket();
var playerPrompt = player.getPrompt(true);
helper.helpers.send(socket, playerPrompt);
});
};
/*Update Time, Day/night cycles*/
function updateTime() {
var tickCount = settings.tickCount;
var ticksInDay = settings.ticksInDay;
if (tickCount !== 0) {
if (settings.minute === 30) {
settings.hour += 1;
if (settings.hour === 24) {
settings.hour = 0;
}
}
settings.minute += 30;
if (settings.minute === 60) {
settings.minute = 0;
}
}
var hour = settings.hour;
var minute = settings.minute;
//increment tick
settings.tickCount += 1;
if (settings.tickCount === 48) {
settings.tickCount = 0;
}
function addZero(time) {
if (time.toString().length === 1) {
return "0" + time;
}
return time;
}
console.log("time " + addZero(hour) + ":" + addZero(minute));
//Shows message for day/night
//TODO: code for moon phases?
if (tickCount <= 35) {
switch (true) {
case (tickCount == 3):
// Emit event "night";
playerManager.broadcast("The moon is slowly moving west across the sky.");
break;
case (tickCount == 9):
// Emit event "Twilight";
playerManager.broadcast("The moon slowly sets in the west.");
break;
case (tickCount == 11):
// Emit event "Sunrise";
playerManager.broadcast("The sun slowly rises from the east.");
break;
case (tickCount == 13):
// Emit event "Morning";
playerManager.broadcast("The sun has risen from the east, the day has begun.");
break;
case (tickCount === 24):
// Emit event "Midday";
playerManager.broadcast("The sun is high in the sky.");
break;
case (tickCount === 29):
// Emit event "Afternoon";
playerManager.broadcast("The sun is slowly moving west across the sky.");
}
} else {
switch (true) {
case (tickCount == 36):
// Emit event "Sunset";
playerManager.broadcast("The sun slowly sets in the west.");
break;
case (tickCount == 40):
// Emit event "MoonRise";
playerManager.broadcast("The moon slowly rises in the west.");
break;
case (tickCount == 43):
// Emit event "Night";
playerManager.broadcast("The moon has risen from the east, the night has begun.");
break;
case (tickCount === 48):
// Emit event "MidNight";
playerManager.broadcast("The moon is high in the sky.");
break;
}
}
if (tickCount === ticksInDay) {
//New day reset
settings.tickCount = 0;
}
//TODO: Date update,
}
/**
Update player and mob HP,Mana,Moves.
@param {string} stat The stat to update
@param {string} maxStat The maxStat of stat to update
@param {string} statType The primary ability linked to stat
*/
function updatePlayer(stat, maxStat, statType) {
console.log(stat + " " + maxStat + " " + statType);
console.time("updatePlayer");
var player = playerManager.getPlayers;
playerManager.each(function (player) {
var playerInfo = player.getPlayerInfo();
//Update Hitpoints if player/mob is hurt
if (playerInfo.information[stat] !== playerInfo.information[maxStat]) {
var gain = playerInfo.information[stat] += playerInfo.information.stats[statType];
if (gain > playerInfo.information[maxStat]) {
gain = playerInfo.information[maxStat];
}
playerInfo.information[stat] = gain;
}
});
console.timeEnd("updatePlayer");
}
/*
* Create function to update rooms / heal mobs
* --------------------------------------------
* When player interacts with the room. (Get item, Attack mob)
* Set room clean status to false.
* This will add the room to an array.
* The update function will loop through this array and only update the dirty rooms.
* The array will check for missing items and add them back if there is no player in the room.
* It will also check / update mob health
* If there is a corpse it should be removed
* have a delay for when to do the update? Update if it's been 5 minutes? this should stop looping through a large amount of
* rooms. set a timestamp when we set dirty? then check the difference in the update? if the timestamp >= the update time. update the room
* Have a flag for when room items are clean?
* Have flag for when mobs are clean this will stop unnecessary looping through room items so we only update mob status
* once all clean, remove from modified room array
* That should cover it!!
*/
var room = [
world.valston.prison
];
var roomLength = room.length;
function updateRoom(onLoad) {
console.time("updateRoom");
/* Searches all areas */
for (var i = 0; i < roomLength; i++) {
var area = room[i];
for (var key in area) {
//Items
var defaultItems = area[key].defaults.items;
var defaultItemCount = defaultItems.length;
//Mobs
var defaultMobs = area[key].defaults.mobs;
var defaultMobsCount = defaultMobs.length;
//Update Items
for (var j = 0; j < defaultItemCount; j++) {
// If an item is missing from the room, indexOf will return -1
// so we then push it to the room items array
if (area[key].items.indexOf(defaultItems[j]) == -1) {
area[key].items.push(defaultItems[j]);
}
//If container, lets check the items
if (defaultItems[j].actions.container == true) {
var defaultContainerItems = defaultItems[j].defaults.items;
var defaultCotainerItemsCount = defaultContainerItems.length;
//update Container items
for (var k = 0; k < defaultCotainerItemsCount; k++) {
if (defaultItems[j].items.indexOf(defaultContainerItems[k]) == -1) {
defaultItems[j].items.push(defaultContainerItems[k]);
}
}
}
}
//Update Mobs
for (var l = 0; l < defaultMobsCount; l++) {
if (area[key].mobs.indexOf(defaultMobs[l]) == -1) {
area[key].mobs.push(defaultMobs[l]);
} else {
// Check Mob health
//var mob = area[key].mobs;
//var mobHP = area[key].mobs.information.hitpoints;
//var mobMaxHp = mob.information.maxHitpoints;
//var mobMana = mob.information.mana;
//var mobMaxMana = mob.information.maxMana;
//console.log(mobHP)
//if (mobHP != mobMaxHp || mobMana != mobMaxMana) {
// var gain = mob.level * 2;
// if (gain > mobMaxHp) {
// gain = mobMaxHp;
// }
// console.log(gain + " " + mobHP)
// mob.information.hitpoints = gain;
// if (gain > mobMaxMana) {
// gain = mobMaxMana;
// }
// mob.information.maxMana = gain;
//}
}
}
}
}
console.timeEnd("updateRoom");
}
eventEmitter.on('updateTime', updateTime);
eventEmitter.on('updatePlayer', updatePlayer);
eventEmitter.on('showPromptOnTick', showPromptOnTick);
eventEmitter.on('updateRoom', updateRoom);
eventEmitter.on('tickTImerStart', recursive);
eventEmitter.emit('tickTImerStart');
}
exports.time = time;
})(require); |
/**
* 页面管理
* @author: SimonHao
* @date: 2015-12-19 14:24:08
*/
'use strict';
var path = require('path');
var fs = require('fs');
var extend = require('extend');
var mid = require('made-id');
var file = require('./file');
var config = require('./config');
var page_list = {};
var comm_option = config.get('comm');
var server = comm_option.server;
var base_path = comm_option.path.base;
var dist_path = comm_option.path.dist;
var page_path = path.join(dist_path, 'page');
var view_option = extend({
basedir: base_path
}, comm_option.view);
var style_option = extend({
basedir: base_path
}, comm_option.style);
var script_option = extend({
basedir: base_path
}, comm_option.script);
exports.get = function(src){
if(exports.has(src)){
return page_list[src];
}
};
exports.has = function(src){
return src in page_list;
};
exports.set = function(src){
if(exports.has(src)){
return exports.get(src);
}else{
return page_list[src] = new PageInfo(src);
}
};
function PageInfo(src){
this.info = new ModuleInfo(src);
this.deps = [];
this.external_style = {};
this.external_script = {};
this.page_style = path.dirname(this.info.view) + '.css';
this.page_script = path.dirname(this.info.view) + '.js';
this._dist = null;
this._url = null;
}
PageInfo.prototype.link_style = function(pack_name){
this.external_style[pack_name] = path.join(base_path, pack_name + '.css');
};
PageInfo.prototype.link_script = function(pack_name){
this.external_script[pack_name] = path.join(base_path, pack_name + '.js');
};
PageInfo.prototype.script_module = function(){
var script_module = [];
this.deps.forEach(function(module_info){
if(module_info.script){
script_module.push(module_info.script);
}
});
if(this.info.script){
script_module.push(this.info.script);
}
return script_module;
};
PageInfo.prototype.style_module = function(){
var style_module = [];
this.deps.forEach(function(module_info){
if(module_info.style){
style_module.push(module_info.style);
}
});
if(this.info.style){
style_module.push(this.info.style);
}
return style_module;
};
PageInfo.prototype.add_deps = function(deps){
var self = this;
deps.forEach(function(dep_info){
self.deps.push(new ModuleInfo(dep_info.filename, dep_info));
});
};
PageInfo.prototype.entry = function(){
var entry_list = [];
this.deps.filter(function(module_info){
return module_info.script;
}).forEach(function(module_info){
entry_list.push({
id: module_info.id,
options: module_info.info.options || {},
instance: module_info.info.instance
});
});
if(this.info.script){
entry_list.push({
id: this.info.id,
options: {},
instance: null
});
}
return entry_list;
};
PageInfo.prototype.dist = function(){
if(this._dist) return this._dist;
var path_dir = path.normalize(this.info.id).split(path.sep);
path_dir.splice(1,1);
return this._dist = path.join(page_path, path_dir.join(path.sep) + '.html');
};
PageInfo.prototype.url = function(){
if(this._url) return this._url
var relative_path = path.relative(page_path, this.dist());
var url = server.web_domain + server.web_path + relative_path.split(path.sep).join('/');
this._url = url;
return url;
};
/**
* Include Module Info
* @param {string} filename view filename
*/
function ModuleInfo(filename, info){
this.info = info || {};
this.view = filename;
this.id = mid.id(filename, view_option);
this.script = mid.path(this.id, script_option);
this.style = mid.path(this.id, style_option);
}
|
export { default } from 'ember-flexberry-gis/components/flexberry-wfs-filter'; |
lychee.define('Font').exports(function(lychee) {
var Class = function(spriteOrImages, settings) {
this.settings = lychee.extend({}, this.defaults, settings);
if (this.settings.kerning > this.settings.spacing) {
this.settings.kerning = this.settings.spacing;
}
this.__cache = {};
this.__images = null;
this.__sprite = null;
if (Object.prototype.toString.call(spriteOrImages) === '[object Array]') {
this.__images = spriteOrImages;
} else {
this.__sprite = spriteOrImages;
}
this.__init();
};
Class.prototype = {
defaults: {
// default charset from 32-126
charset: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
baseline: 0,
spacing: 0,
kerning: 0,
map: null
},
__init: function() {
// Single Image Mode
if (this.__images !== null) {
this.__initImages();
// Sprite Image Mode
} else if (this.__sprite !== null) {
if (Object.prototype.toString.call(this.settings.map) === '[object Array]') {
var test = this.settings.map[0];
if (Object.prototype.toString.call(test) === '[object Object]') {
this.__initSpriteXY();
} else if (typeof test === 'number') {
this.__initSpriteX();
}
}
}
},
__initImages: function() {
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var image = this.__images[c] || null;
if (image === null) continue;
var chr = {
id: this.settings.charset[c],
image: image,
width: image.width,
height: image.height,
x: 0,
y: 0
};
this.__cache[chr.id] = chr;
}
},
__initSpriteX: function() {
var offset = this.settings.spacing;
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var chr = {
id: this.settings.charset[c],
width: this.settings.map[c] + this.settings.spacing * 2,
height: this.__sprite.height,
real: this.settings.map[c],
x: offset - this.settings.spacing,
y: 0
};
offset += chr.width;
this.__cache[chr.id] = chr;
}
},
__initSpriteXY: function() {
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var frame = this.settings.map[c];
var chr = {
id: this.settings.charset[c],
width: frame.width + this.settings.spacing * 2,
height: frame.height,
real: frame.width,
x: frame.x - this.settings.spacing,
y: frame.y
};
this.__cache[chr.id] = chr;
}
},
get: function(id) {
if (this.__cache[id] !== undefined) {
return this.__cache[id];
}
return null;
},
getSettings: function() {
return this.settings;
},
getSprite: function() {
return this.__sprite;
}
};
return Class;
});
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M8 9v1.5h2.25V15h1.5v-4.5H14V9H8zM6 9H3c-.55 0-1 .45-1 1v5h1.5v-1.5h2V15H7v-5c0-.55-.45-1-1-1zm-.5 3h-2v-1.5h2V12zM21 9h-4.5c-.55 0-1 .45-1 1v5H17v-4.5h1V14h1.5v-3.51h1V15H22v-5c0-.55-.45-1-1-1z"
}), 'AtmOutlined'); |
var fb = "https://glaring-fire-5349.firebaseio.com";
var TodoCheck = React.createClass({displayName: "TodoCheck",
getInitialState: function() {
this.checked = false;
return {checked: this.checked};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/checked");
// Update the checked state when it changes.
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
this.checked = snap.val();
this.setState({
checked: this.checked
});
this.props.todo.setDone(this.checked);
} else {
this.ref.set(false);
this.props.todo.setDone(false);
}
}.bind(this));
},
toggleCheck: function(event) {
this.ref.set(!this.checked);
event.preventDefault();
},
render: function() {
return (
React.createElement("a", {
onClick: this.toggleCheck,
href: "#",
className: "pull-left todo-check"},
React.createElement("span", {
className: "todo-check-mark glyphicon glyphicon-ok",
"aria-hidden": "true"}
)
)
);
},
});
var TodoText = React.createClass({displayName: "TodoText",
componentWillUnmount: function() {
this.ref.off();
$("#" + this.props.todoKey + "-text").off('blur');
},
setText: function(text) {
this.text = text;
this.props.todo.setHasText(!!text);
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/text");
// Update the todo's text when it changes.
this.setText("");
this.ref.on("value", function(snap) {
if (snap.val() !== null) {
$("#" + this.props.todoKey + "-text").text(snap.val());
this.setText(snap.val());
} else {
this.ref.set("");
}
}.bind(this));
},
onTextBlur: function(event) {
this.ref.set($(event.target).text());
},
render: function() {
setTimeout(function() {
$("#" + this.props.todoKey + "-text").text(this.text);
}.bind(this), 0);
return (
React.createElement("span", {
id: this.props.todoKey + "-text",
onBlur: this.onTextBlur,
contentEditable: "plaintext-only",
"data-ph": "Todo",
className: "todo-text"}
)
);
},
});
var TodoDelete = React.createClass({displayName: "TodoDelete",
getInitialState: function() {
return {};
},
componentWillUnmount: function() {
this.ref.off();
},
componentWillMount: function() {
this.ref = new Firebase(fb + "/react_todos/" + this.props.todoKey + "/deleted");
},
onClick: function() {
this.ref.set(true);
},
render: function() {
if (this.props.isLast) {
return null;
}
return (
React.createElement("button", {
onClick: this.onClick, type: "button",
className: "close", "aria-label": "Close"},
React.createElement("span", {
"aria-hidden": "true",
dangerouslySetInnerHTML: {__html: '×'}})
)
);
},
});
var Todo = React.createClass({displayName: "Todo",
getInitialState: function() {
return {};
},
setDone: function(done) {
this.setState({
done: done
});
},
setHasText: function(hasText) {
this.setState({
hasText: hasText
});
},
render: function() {
var doneClass = this.state.done ? "todo-done" : "todo-not-done";
return (
React.createElement("li", {
id: this.props.todoKey,
className: "list-group-item todo " + doneClass},
React.createElement(TodoCheck, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoText, {todo: this, todoKey: this.props.todoKey}),
React.createElement(TodoDelete, {isLast: false, todoKey: this.props.todoKey})
)
);
}
});
var TodoList = React.createClass({displayName: "TodoList",
getInitialState: function() {
this.todos = [];
return {todos: this.todos};
},
componentWillMount: function() {
this.ref = new Firebase("https://glaring-fire-5349.firebaseio.com/react_todos/");
// Add an empty todo if none currently exist.
this.ref.on("value", function(snap) {
if (snap.val() === null) {
this.ref.push({
text: "",
});
return;
}
// Add a new todo if no undeleted ones exist.
var returnedTrue = snap.forEach(function(data) {
if (!data.val().deleted) {
return true;
}
});
if (!returnedTrue) {
this.ref.push({
text: "",
});
return;
}
}.bind(this));
// Add an added child to this.todos.
this.ref.on("child_added", function(childSnap) {
this.todos.push({
k: childSnap.key(),
val: childSnap.val()
});
this.replaceState({
todos: this.todos
});
}.bind(this));
this.ref.on("child_removed", function(childSnap) {
var key = childSnap.key();
var i;
for (i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
break;
}
}
this.todos.splice(i, 1);
this.replaceState({
todos: this.todos,
});
}.bind(this));
this.ref.on("child_changed", function(childSnap) {
var key = childSnap.key();
for (var i = 0; i < this.todos.length; i++) {
if (this.todos[i].k == key) {
this.todos[i].val = childSnap.val();
this.replaceState({
todos: this.todos,
});
break;
}
}
}.bind(this));
},
componentWillUnmount: function() {
this.ref.off();
},
render: function() {
console.log(this.todos);
var todos = this.state.todos.map(function (todo) {
if (todo.val.deleted) {
return null;
}
return (
React.createElement(Todo, {todoKey: todo.k})
);
}).filter(function(todo) { return todo !== null; });
console.log(todos);
return (
React.createElement("div", null,
React.createElement("h1", {id: "list_title"}, this.props.title),
React.createElement("ul", {id: "todo-list", className: "list-group"},
todos
)
)
);
}
});
var ListPage = React.createClass({displayName: "ListPage",
render: function() {
return (
React.createElement("div", null,
React.createElement("div", {id: "list_page"},
React.createElement("a", {
onClick: this.props.app.navOnClick({page: "LISTS"}),
href: "/#/lists",
id: "lists_link",
className: "btn btn-primary"},
"Back to Lists"
)
),
React.createElement("div", {className: "page-header"},
this.props.children
)
)
);
}
});
var Nav = React.createClass({displayName: "Nav",
render: function() {
return (
React.createElement("nav", {className: "navbar navbar-default navbar-static-top"},
React.createElement("div", {className: "container"},
React.createElement("div", {className: "navbar-header"},
React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), className: "navbar-brand", href: "/#/lists"}, "Firebase Todo")
),
React.createElement("ul", {className: "nav navbar-nav"},
React.createElement("li", null, React.createElement("a", {onClick: this.props.app.navOnClick({page: "LISTS"}), href: "/#/lists"}, "Lists"))
)
)
)
);
},
});
var App = React.createClass({displayName: "App",
getInitialState: function() {
var state = this.getState();
this.setHistory(state, true);
return this.getState();
},
setHistory: function(state, replace) {
// Don't bother pushing a history entry if the latest state is
// the same.
if (_.isEqual(state, this.state)) {
return;
}
var histFunc = replace ?
history.replaceState.bind(history) :
history.pushState.bind(history);
if (state.page === "LIST") {
histFunc(state, "", "#/list/" + state.todoListKey);
} else if (state.page === "LISTS") {
histFunc(state, "", "#/lists");
} else {
console.log("Unknown page: " + state.page);
}
},
getState: function() {
var url = document.location.toString();
if (url.match(/#/)) {
var path = url.split("#")[1];
var res = path.match(/\/list\/([^\/]*)$/);
if (res) {
return {
page: "LIST",
todoListKey: res[1],
};
}
res = path.match(/lists$/);
if (res) {
return {
page: "LISTS"
}
}
}
return {
page: "LISTS"
}
},
componentWillMount: function() {
// Register history listeners.
var app = this;
window.onpopstate = function(event) {
app.replaceState(event.state);
};
},
navOnClick: function(state) {
return function(event) {
this.setHistory(state, false);
this.replaceState(state);
event.preventDefault();
}.bind(this);
},
getPage: function() {
if (this.state.page === "LIST") {
return (
React.createElement(ListPage, {app: this},
React.createElement(TodoList, {todoListKey: this.state.todoListKey})
)
);
} else if (this.state.page === "LISTS") {
return (
React.createElement("a", {onClick: this.navOnClick({page: "LIST", todoListKey: "-JjcFYgp1LyD5oDNNSe2"}), href: "/#/list/-JjcFYgp1LyD5oDNNSe2"}, "hi")
);
} else {
console.log("Unknown page: " + this.state.page);
}
},
render: function() {
return (
React.createElement("div", null,
React.createElement(Nav, {app: this}),
React.createElement("div", {className: "container", role: "main"},
this.getPage()
)
)
);
}
});
React.render(
React.createElement(App, null),
document.getElementById('content')
); |
// bundles everything except TS files which will be built by rollup.
// webpack stuff
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var failPlugin = require('webpack-fail-plugin');
var helpers = require('./helpers');
const basePlugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.optimize.CommonsChunkPlugin('globals'),
new HtmlWebpackPlugin({
template: 'index.template.html',
favicon: 'favicon.ico'
}),
new ExtractTextPlugin("styles.css"),
failPlugin
];
const devPlugins = [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
})
];
const plugins = basePlugins
.concat((process.env.NODE_ENV === 'development') ? devPlugins: []);
module.exports = {
entry: {
globals: [
'core-js',
'zone.js',
'reflect-metadata'
]
},
output: {
path: helpers.root(''),
publicPath: '',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
resolve: {
extensions: [
'.webpack.js', '.web.js', '.js', '.html'
]
},
module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.html$/, loader: 'raw' },
{ test: /\.(ico)$/, loader: 'file' },
{ test: /\.(png|jpe?g|gif)$/, loader: 'file', query: {name: 'assets/[name].[hash].[ext]'} },
{ test: /\.css$/, exclude: helpers.root('src', 'app'), loader: ExtractTextPlugin.extract({
fallbackLoader: "style-loader",
loader: "css-loader"
}) },
{ test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw' },
{ test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'application/font-woff'} },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'application/octet-stream'} },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'image/svg+xml'} }
]
},
plugins: plugins
};
// gulp tasks
var gulp = require('gulp');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
gulp.task('build', function () {
console.log('build Working!');
});
gulp.task('watch', function () {
watch('**/*.ts', batch(function (events, done) {
gulp.start('build', done);
}));
}); |
exports.up = function (knex, Promise) {
return Promise.all([
knex.schema.createTable('locations', function (table) {
table.uuid('id').notNullable().primary()
table.string('title').notNullable().unique()
table.text('description')
table.string('address_1')
table.string('address_2')
table.string('town')
table.string('county')
table.string('zipcode')
table.string('country')
}),
knex.schema.createTable('conferences', function (table) {
table.uuid('id').notNullable().primary()
table.string('title').notNullable().unique()
table.text('description')
table.string('organiser').notNullable().unique()
table.dateTime('startTime')
table.dateTime('endTime')
table.uuid('location').references('locations.id')
})
])
}
exports.down = function (knex, Promise) {
return Promise.all([
knex.schema.dropTable('conferences'),
knex.schema.dropTable('locations')
])
}
|
(function( window, $, undefined ) {
// http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
$.fn.touchwipe = function(settings) {
var config = {
min_move_x: 20,
min_move_y: 20,
wipeLeft: function() { },
wipeRight: function() { },
wipeUp: function() { },
wipeDown: function() { },
preventDefaultEvents: true
};
if (settings) $.extend(config, settings);
this.each(function() {
var startX;
var startY;
var isMoving = false;
function cancelTouch() {
this.removeEventListener('touchmove', onTouchMove);
startX = null;
isMoving = false;
}
function onTouchMove(e) {
if(config.preventDefaultEvents) {
e.preventDefault();
}
if(isMoving) {
var x = e.touches[0].pageX;
var y = e.touches[0].pageY;
var dx = startX - x;
var dy = startY - y;
if(Math.abs(dx) >= config.min_move_x) {
cancelTouch();
if(dx > 0) {
config.wipeLeft();
}
else {
config.wipeRight();
}
}
else if(Math.abs(dy) >= config.min_move_y) {
cancelTouch();
if(dy > 0) {
config.wipeDown();
}
else {
config.wipeUp();
}
}
}
}
function onTouchStart(e)
{
if (e.touches.length == 1) {
startX = e.touches[0].pageX;
startY = e.touches[0].pageY;
isMoving = true;
this.addEventListener('touchmove', onTouchMove, false);
}
}
if ('ontouchstart' in document.documentElement) {
this.addEventListener('touchstart', onTouchStart, false);
}
});
return this;
};
$.elastislide = function( options, element ) {
this.$el = $( element );
this._init( options );
};
$.elastislide.defaults = {
speed : 450, // animation speed
easing : '', // animation easing effect
imageW : 190, // the images width
margin : 3, // image margin right
border : 2, // image border
minItems : 1, // the minimum number of items to show.
// when we resize the window, this will make sure minItems are always shown
// (unless of course minItems is higher than the total number of elements)
current : 0, // index of the current item
// when we resize the window, the carousel will make sure this item is visible
navPrev :'<span class="es-nav-prev">Prev</span>',
navNext :'<span class="es-nav-next">Next</span>',
onClick : function() { return false; } // click item callback
};
$.elastislide.prototype = {
_init : function( options ) {
this.options = $.extend( true, {}, $.elastislide.defaults, options );
// <ul>
this.$slider = this.$el.find('ul');
// <li>
this.$items = this.$slider.children('li');
// total number of elements / images
this.itemsCount = this.$items.length;
// cache the <ul>'s parent, since we will eventually need to recalculate its width on window resize
this.$esCarousel = this.$slider.parent();
// validate options
this._validateOptions();
// set sizes and initialize some vars...
this._configure();
// add navigation buttons
this._addControls();
// initialize the events
this._initEvents();
// show the <ul>
this.$slider.show();
// slide to current's position
this._slideToCurrent( false );
},
_validateOptions : function() {
if( this.options.speed < 0 )
this.options.speed = 450;
if( this.options.margin < 0 )
this.options.margin = 4;
if( this.options.border < 0 )
this.options.border = 1;
if( this.options.minItems < 1 || this.options.minItems > this.itemsCount )
this.options.minItems = 1;
if( this.options.current > this.itemsCount - 1 )
this.options.current = 0;
},
_configure : function() {
// current item's index
this.current = this.options.current;
// the ul's parent's (div.es-carousel) width is the "visible" width
this.visibleWidth = this.$esCarousel.width();
// test to see if we need to initially resize the items
if( this.visibleWidth < this.options.minItems * ( this.options.imageW + 2 * this.options.border ) + ( this.options.minItems - 1 ) * this.options.margin ) {
this._setDim( ( this.visibleWidth - ( this.options.minItems - 1 ) * this.options.margin ) / this.options.minItems );
this._setCurrentValues();
// how many items fit with the current width
this.fitCount = this.options.minItems;
}
else {
this._setDim();
this._setCurrentValues();
}
// set the <ul> width
this.$slider.css({
width : this.sliderW
});
},
_setDim : function( elW ) {
// <li> style
this.$items.css({
marginRight : this.options.margin,
width : ( elW ) ? elW : this.options.imageW + 2 * this.options.border
}).children('a').css({ // <a> style
borderWidth : this.options.border
});
},
_setCurrentValues : function() {
// the total space occupied by one item
this.itemW = this.$items.outerWidth(true);
// total width of the slider / <ul>
// this will eventually change on window resize
this.sliderW = this.itemW * this.itemsCount;
// the ul parent's (div.es-carousel) width is the "visible" width
this.visibleWidth = this.$esCarousel.width();
// how many items fit with the current width
this.fitCount = Math.floor( this.visibleWidth / this.itemW );
},
_addControls : function() {
this.$navNext = $(this.options.navNext);
this.$navPrev = $(this.options.navPrev);
$('<div class="es-nav"/>')
.append( this.$navPrev )
.append( this.$navNext )
.appendTo( this.$el );
//this._toggleControls();
},
_toggleControls : function( dir, status ) {
// show / hide navigation buttons
if( dir && status ) {
if( status === 1 )
( dir === 'right' ) ? this.$navNext.show() : this.$navPrev.show();
else
( dir === 'right' ) ? this.$navNext.hide() : this.$navPrev.hide();
}
else if( this.current === this.itemsCount - 1 || this.fitCount >= this.itemsCount )
this.$navNext.hide();
},
_initEvents : function() {
var instance = this;
// window resize
$(window).on('resize.elastislide', function( event ) {
instance._reload();
// slide to the current element
clearTimeout( instance.resetTimeout );
instance.resetTimeout = setTimeout(function() {
instance._slideToCurrent();
}, 200);
});
// navigation buttons events
this.$navNext.on('click.elastislide', function( event ) {
instance._slide('right');
});
this.$navPrev.on('click.elastislide', function( event ) {
instance._slide('left');
});
// item click event
this.$slider.on('click.elastislide', 'li', function( event ) {
instance.options.onClick( $(this) );
return false;
});
// touch events
instance.$slider.touchwipe({
wipeLeft : function() {
instance._slide('right');
},
wipeRight : function() {
instance._slide('left');
}
});
},
reload : function( callback ) {
this._reload();
if ( callback ) callback.call();
},
_reload : function() {
var instance = this;
// set values again
instance._setCurrentValues();
// need to resize items
if( instance.visibleWidth < instance.options.minItems * ( instance.options.imageW + 2 * instance.options.border ) + ( instance.options.minItems - 1 ) * instance.options.margin ) {
instance._setDim( ( instance.visibleWidth - ( instance.options.minItems - 1 ) * instance.options.margin ) / instance.options.minItems );
instance._setCurrentValues();
instance.fitCount = instance.options.minItems;
}
else{
instance._setDim();
instance._setCurrentValues();
}
instance.$slider.css({
width : instance.sliderW + 10 // TODO: +10px seems to solve a firefox "bug" :S
});
},
_slide : function( dir, val, anim, callback ) {
// if animating return
//if( this.$slider.is(':animated') )
//return false;
// current margin left
var ml = parseFloat( this.$slider.css('margin-left') );
// val is just passed when we want an exact value for the margin left (used in the _slideToCurrent function)
if( val === undefined ) {
// how much to slide?
var amount = this.fitCount * this.itemW, val;
if( amount < 0 ) return false;
// make sure not to leave a space between the last item / first item and the end / beggining of the slider available width
if( dir === 'right' && this.sliderW - ( Math.abs( ml ) + amount ) < this.visibleWidth ) {
amount = this.sliderW - ( Math.abs( ml ) + this.visibleWidth ) - this.options.margin; // decrease the margin left
// show / hide navigation buttons
this._toggleControls( 'right', -1 );
this._toggleControls( 'left', 1 );
}
else if( dir === 'left' && Math.abs( ml ) - amount < 0 ) {
amount = Math.abs( ml );
// show / hide navigation buttons
this._toggleControls( 'left', -1 );
this._toggleControls( 'right', 1 );
}
else {
var fml; // future margin left
( dir === 'right' )
? fml = Math.abs( ml ) + this.options.margin + Math.abs( amount )
: fml = Math.abs( ml ) - this.options.margin - Math.abs( amount );
// show / hide navigation buttons
if( fml > 0 )
this._toggleControls( 'left', 1 );
else
this._toggleControls( 'left', -1 );
if( fml < this.sliderW - this.visibleWidth )
this._toggleControls( 'right', 1 );
else
this._toggleControls( 'right', -1 );
}
( dir === 'right' ) ? val = '-=' + amount : val = '+=' + amount
}
else {
var fml = Math.abs( val ); // future margin left
if( Math.max( this.sliderW, this.visibleWidth ) - fml < this.visibleWidth ) {
val = - ( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth );
if( val !== 0 )
val += this.options.margin; // decrease the margin left if not on the first position
// show / hide navigation buttons
this._toggleControls( 'right', -1 );
fml = Math.abs( val );
}
// show / hide navigation buttons
if( fml > 0 )
this._toggleControls( 'left', 1 );
else
this._toggleControls( 'left', -1 );
if( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth > fml + this.options.margin )
this._toggleControls( 'right', 1 );
else
this._toggleControls( 'right', -1 );
}
$.fn.applyStyle = ( anim === undefined ) ? $.fn.animate : $.fn.css;
var sliderCSS = { marginLeft : val };
var instance = this;
this.$slider.stop().applyStyle( sliderCSS, $.extend( true, [], { duration : this.options.speed, easing : this.options.easing, complete : function() {
if( callback ) callback.call();
} } ) );
},
_slideToCurrent : function( anim ) {
// how much to slide?
var amount = this.current * this.itemW;
this._slide('', -amount, anim );
},
add : function( $newelems, callback ) {
// adds new items to the carousel
this.$items = this.$items.add( $newelems );
this.itemsCount = this.$items.length;
this._setDim();
this._setCurrentValues();
this.$slider.css({
width : this.sliderW
});
this._slideToCurrent();
if ( callback ) callback.call( $newelems );
},
setCurrent : function( idx, callback ) {
this.current = idx;
var ml = Math.abs( parseFloat( this.$slider.css('margin-left') ) ),
posR = ml + this.visibleWidth,
fml = Math.abs( this.current * this.itemW );
if( fml + this.itemW > posR || fml < ml ) {
this._slideToCurrent();
}
if ( callback ) callback.call();
},
destroy : function( callback ) {
this._destroy( callback );
},
_destroy : function( callback ) {
this.$el.off('.elastislide').removeData('elastislide');
$(window).off('.elastislide');
if ( callback ) callback.call();
}
};
var logError = function( message ) {
if ( this.console ) {
console.error( message );
}
};
$.fn.elastislide = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'elastislide' );
if ( !instance ) {
logError( "cannot call methods on elastislide prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for elastislide instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'elastislide' );
if ( !instance ) {
$.data( this, 'elastislide', new $.elastislide( options, this ) );
}
});
}
return this;
};
})( window, jQuery ); |
#!/usr/bin/env node
var _ = require('lodash');
var async = require('async-chainable');
var asyncFlush = require('async-chainable-flush');
var colors = require('chalk');
var doop = require('.');
var glob = require('glob');
var fs = require('fs');
var fspath = require('path');
var program = require('commander');
var sha1 = require('node-sha1');
program
.version(require('./package.json').version)
.description('List units installed for the current project')
.option('-b, --basic', 'Display a simple list, do not attempt to hash file differences')
.option('-v, --verbose', 'Be verbose. Specify multiple times for increasing verbosity', function(i, v) { return v + 1 }, 0)
.parse(process.argv);
async()
.use(asyncFlush)
.then(doop.chProjectRoot)
.then(doop.getUserSettings)
// Get the list of units {{{
.then('units', function(next) {
doop.getUnits(function(err, units) {
if (err) return next(err);
next(null, units.map(u => { return {
id: u,
path: fspath.join(doop.settings.paths.units, u),
files: {},
} }));
});
})
// }}}
// Hash file comparisons unless program.basic {{{
// Get repo {{{
.then('repo', function(next) {
if (program.basic) return next();
doop.getDoopPath(next, program.repo);
})
.then(function(next) {
if (program.basic) return next();
if (program.verbose) console.log('Using Doop source:', colors.cyan(this.repo));
next();
})
// }}}
// Scan project + Doop file list and hash all files (unless !program.basic) {{{
.then(function(next) {
if (program.basic) return next();
// Make a list of all files in both this project and in the doop repo
// For each file create an object with a `local` sha1 hash and `doop` sha1 hash
var hashQueue = async(); // Hash tasks to perform
async()
.forEach(this.units, function(next, unit) {
async()
.parallel([
// Hash all project files {{{
function(next) {
glob(fspath.join(unit.path, '**'), {nodir: true}, function(err, files) {
if (files.length) {
unit.existsInProject = true;
files.forEach(function(file) {
hashQueue.defer(file, function(next) {
if (program.verbose) console.log('Hash file (Proj)', colors.cyan(file));
sha1(fs.createReadStream(file), function(err, hash) {
if (!unit.files[file]) unit.files[file] = {path: file};
unit.files[file].project = hash;
next();
});
});
});
} else {
unit.existsInProject = false;
}
next();
});
},
// }}}
// Hash all Doop files {{{
function(next) {
glob(fspath.join(doop.settings.paths.doop, unit.path, '**'), {nodir: true}, function(err, files) {
if (files.length) {
unit.existsInDoop = true;
files.forEach(function(rawFile) {
var croppedPath = rawFile.substr(doop.settings.paths.doop.length + 1);
var file = fspath.join(doop.settings.paths.doop, croppedPath);
hashQueue.defer(file, function(next) {
if (program.verbose) console.log('Hash file (Doop)', colors.cyan(croppedPath));
sha1(fs.createReadStream(file), function(err, hash) {
if (!unit.files[croppedPath]) unit.files[croppedPath] = {path: file};
unit.files[croppedPath].doop = hash;
next();
});
});
});
} else {
unit.existsInDoop = false;
}
next();
});
},
// }}}
])
.end(next)
})
.end(function(err) {
if (err) return next(err);
// Wait for hashing queue to finish
hashQueue.await().end(next);
});
})
// }}}
// }}}
// Present the list {{{
.then(function(next) {
var task = this;
if (program.verbose > 1) console.log();
this.units.forEach(function(unit) {
if (unit.existsInProject && !unit.existsInDoop) {
console.log(colors.grey(' -', unit.id));
} else if (!unit.existsInProject && unit.existsInDoop) {
console.log(colors.red(' -', unit.id));
} else { // In both Doop + Project - examine file differences
var changes = [];
// Edited {{{
var items = _.filter(unit.files, f => f.project && f.doop && f.project != f.doop);
if (_.get(doop.settings, 'list.changes.maxEdited') && items.length > doop.settings.list.changes.maxEdited) {
changes.push(colors.yellow.bold('~' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.yellow.bold('~') + f.path.substr(unit.path.length+1)));
}
// }}}
// Created {{{
var items = _.filter(unit.files, f => f.project && !f.doop);
if (_.get(doop.settings, 'list.changes.maxCreated') && items.length > doop.settings.list.changes.maxCreated) {
changes.push(colors.green.bold('+' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.green.bold('+') + f.path.substr(unit.path.length+1)));
}
// }}}
// Deleted {{{
var items = _.filter(unit.files, f => f.doop && !f.project);
if (_.get(doop.settings, 'list.changes.maxDeleted') && items.length > doop.settings.list.changes.maxDeleted) {
changes.push(colors.red.bold('-' + items.length + ' items'));
} else {
items.forEach(f => changes.push(colors.red.bold('-') + f.path.substr(doop.settings.paths.doop.length+unit.path.length+2)));
}
// }}}
if (changes.length) {
console.log(' -', unit.id, colors.blue('('), changes.join(', '), colors.blue(')'));
} else {
console.log(' -', unit.id);
}
}
});
next();
})
// }}}
// End {{{
.flush()
.end(function(err) {
if (err) {
console.log(colors.red('Doop Error'), err.toString());
process.exit(1);
} else {
process.exit(0);
}
});
// }}}
|
if(!Hummingbird) { var Hummingbird = {}; }
Hummingbird.Base = function() {};
Hummingbird.Base.prototype = {
validMessageCount: 0,
messageRate: 20,
initialize: function() {
this.averageLog = [];
this.setFilter();
this.registerHandler();
},
registerHandler: function() {
this.socket.registerHandler(this.onData, this);
},
onMessage: function(message) {
console.log("Base class says: " + JSON.stringify(message));
},
onData: function(fullData) {
var average;
var message = this.extract(fullData);
if(typeof(message) != "undefined") {
this.validMessageCount += 1;
// Calculate the average over N seconds if the averageOver option is set
if(this.options.averageOver) { average = this.addToAverage(message); }
if((!this.options.every) || (this.validMessageCount % this.options.every == 0)) {
this.onMessage(message, this.average());
}
}
},
extract: function(data) {
if(typeof(data) == "undefined") { return; }
var obj = data;
for(var i = 0, len = this.filter.length; i < len; i++) {
obj = obj[this.filter[i]];
if(typeof(obj) == "undefined") { return; }
}
return obj;
},
setFilter: function() {
// TODO: extend this (and extract) to support multiple filters
var obj = this.options.data;
this.filter = [];
while(typeof(obj) == "object") {
for(var i in obj) {
this.filter.push(i);
obj = obj[i];
break;
}
}
},
addToAverage: function(newValue) {
var averageCount = this.options.averageOver * this.messageRate;
this.averageLog.push(newValue);
if(this.averageLog.length > averageCount) {
this.averageLog.shift();
}
},
average: function() {
if(this.averageLog.length == 0) { return 0; }
return this.averageLog.sum() * 1.0 / this.averageLog.length * this.messageRate;
}
};
|
define([
'knockout'
],function(
ko
){
ko.bindingHandlers.withfirst = {
'init' : function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var savedNodes;
ko.computed(function() {
var dataValue = ko.utils.unwrapObservable(valueAccessor());
var shouldDisplay = typeof dataValue.length == "number" && dataValue.length;
var isFirstRender = !savedNodes;
// Save a copy of the inner nodes on the initial update,
// but only if we have dependencies.
if (isFirstRender && ko.computedContext.getDependenciesCount()) {
savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
}
if (shouldDisplay) {
if (!isFirstRender) {
ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
}
ko.applyBindingsToDescendants( bindingContext['createChildContext'](dataValue && dataValue[0]), element);
} else {
ko.virtualElements.emptyNode(element);
}
}, null).extend({ rateLimit: 50 });
return { 'controlsDescendantBindings': true };
}
}
}); |
var bunyanConfig = require('../index');
var bunyan = require('bunyan');
var path = require('path');
describe('bunyan-config', function () {
it('should not convert things it does not understand', function () {
bunyanConfig({
name: 'test',
streams: [{
path: '/tmp/log.log'
}, {
type: 'raw',
stream: 'unknown'
}],
serializers: 5
}).should.deep.equal({
name: 'test',
streams: [{
path: '/tmp/log.log'
}, {
type: 'raw',
stream: 'unknown'
}],
serializers: 5
});
});
describe('streams', function () {
it('should convert stdout and stderr', function () {
bunyanConfig({
streams: [{
level: 'info',
stream: 'stdout'
}, {
stream: {name: 'stderr'}
}]
}).should.deep.equal({
streams: [{
level: 'info',
stream: process.stdout
}, {
stream: process.stderr
}]
});
});
it('should convert bunyan-logstash', function () {
bunyanConfig({
streams: [{
level: 'error',
type: 'raw',
stream: {
name: 'bunyan-logstash',
params: {
host: 'example.com',
port: 1234
}
}
}]
}).should.deep.equal({
streams: [{
level: 'error',
type: 'raw',
stream: require('bunyan-logstash').createStream({
host: 'example.com',
port: 1234
})
}]
});
});
it('should convert bunyan-redis stream', function () {
var config = bunyanConfig({
streams: [{
type: 'raw',
stream: {
name: 'bunyan-redis',
params: {
host: 'example.com',
port: 1234
}
}
}]
});
config.streams[0].stream.should.be.an.instanceof(require('events').EventEmitter);
config.streams[0].stream._client.host.should.equal('example.com');
config.streams[0].stream._client.port.should.equal(1234);
config.streams[0].stream._client.end();
});
});
describe('serializers', function () {
it('should convert serializers property, if it is a string', function () {
bunyanConfig({
serializers: 'bunyan:stdSerializers'
}).should.deep.equal({
serializers: bunyan.stdSerializers
});
});
it('should not convert serializers, if it is an empty string', function () {
bunyanConfig({
serializers: ''
}).should.deep.equal({
serializers: ''
});
});
it('should convert serializers object', function () {
var absolutePathWithProps = path.resolve(__dirname, './fixtures/dummySerializerWithProps');
var relativePathWithProps = './' + path.relative(process.cwd(), absolutePathWithProps);
var absolutePathWithoutProps = path.resolve(__dirname, './fixtures/dummySerializerWithoutProps');
var relativePathWithoutProps = './' + path.relative(process.cwd(), absolutePathWithoutProps);
bunyanConfig({
serializers: {
moduleWithProps: 'bunyan:stdSerializers.req',
moduleWithoutProps: 'bunyan',
absoluteWithProps: relativePathWithProps + ':c',
relativeWithProps: relativePathWithProps + ':a.b',
absoluteWithoutProps: absolutePathWithoutProps,
relativeWithoutProps: relativePathWithoutProps,
empty: '',
noModuleId: ':abc'
}
}).should.deep.equal({
serializers: {
moduleWithProps: bunyan.stdSerializers.req,
moduleWithoutProps: bunyan,
absoluteWithProps: require('./fixtures/dummySerializerWithProps').c,
relativeWithProps: require('./fixtures/dummySerializerWithProps').a.b,
absoluteWithoutProps: require('./fixtures/dummySerializerWithoutProps'),
relativeWithoutProps: require('./fixtures/dummySerializerWithoutProps'),
empty: '',
noModuleId: ':abc'
}
});
});
});
});
|
'use strict';
var http = require('http');
var Logger = require('bunyan');
var log = new Logger({
name: 'test-server',
level: 'debug'
});
var server = http.createServer(function (request) {
var data = '';
log.info({ url: request.url }, 'Incoming Request');
request.on('data', function (chunk) {
data += chunk;
});
throw new Error('expected error');
});
var port = 3000;
server.listen(port);
log.info({
port: port
}, 'listening');
|
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import EmailField from '../EmailField';
// EmailField
// props: inputId
// behavior: renders a <Field /> component
// test: renders a <Field /> component
describe('<EmailField />', () => {
it('should render a Field component', () => {
let wrapper = shallow(<EmailField inputId='testField'/>);
expect(toJson(wrapper)).toMatchSnapshot();
});
}); |
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
addFavorite() {
this.sendAction('addFavorite', this.get('newFavorite'));
}
}
});
|
(function ($) {
'use strict';
// Device check for limiting resize handling.
var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
function FullHeight(el, options) {
this.el = $(el);
var data = {};
$.each(this.el.data(), function (attr, value) {
if (/^fullheight/.test(attr)) {
var key = attr.replace('fullheight', '').toLowerCase();
data[key] = value;
}
});
options = $.extend({}, FullHeight.defaults, options, data);
this.debug = options.debug;
this.container = $(options.container);
this.property = options.property;
this.propertyBefore = this.el.css(this.property);
// Chrome for Android resizes the browser a lot when scrolling due to the address bar collapsing.
// This causes a lot of arbitrary layout jumps and slow image resize operations with this plugin.
// So for device UA where height should not change, we only update if the width changes as well (f.ex.
// orientation changes).
this.allowDeviceHeightResize = !(
options.allowDeviceHeightResize === null ||
options.allowDeviceHeightResize === false ||
options.allowDeviceHeightResize === 'false'
);
this.lastWidth = this.container.innerWidth();
this.timerResize = 0;
this.container.on('resize.yrkup3.fullheight', $.proxy(this, '_onResize'));
this.update();
}
FullHeight.defaults = {
debug: false,
allowDeviceHeightResize: false,
container: window,
property: 'min-height'
};
FullHeight.prototype._onResize = function () {
var newWidth = this.container.innerWidth();
var allowResize = !IS_DEVICE || this.allowDeviceHeightResize || newWidth !== this.lastWidth;
// Do the update if expected.
if (allowResize) {
var root = this;
clearTimeout(this.timerResize);
this.timerResize = setTimeout(function () {
root.update();
}, 200);
}
this.lastWidth = newWidth;
};
FullHeight.prototype.update = function () {
if (this.debug) {
console.log('update', this.el);
}
var newHeight;
var offset = this.container.offset();
if (typeof offset == 'undefined') {
newHeight = $(window).innerHeight();
} else {
newHeight = this.container.innerHeight() - (this.el.offset().top - offset.top);
}
if (newHeight !== this.lastHeight) {
if (this.debug) {
console.log('set `' + this.property + '` to ' + newHeight);
}
this.el.css(this.property, newHeight);
this.lastHeight = newHeight;
}
};
FullHeight.prototype.dispose = function () {
if (this.debug) {
console.log('dispose');
}
this.container.off('.yrkup3.fullheight');
this.el.css(this.property, this.propertyBefore);
};
$.fn.fullheight = function (options) {
this.each(function () {
var el = $(this);
// Store data
var data = el.data('yrkup3.fullheight');
if (!data) {
el.data('yrkup3.fullheight', (data = new FullHeight(el, options)));
}
// Run command
if (typeof options == 'string') {
data[options]();
}
});
return this;
};
})(jQuery);
|
var _ = require('lodash'),
restify = require('restify'),
async = require('async');
module.exports = function(settings, server, db){
var globalLogger = require(settings.path.root('logger'));
var auth = require(settings.path.lib('auth'))(settings, db);
var api = require(settings.path.lib('api'))(settings, db);
var vAlpha = function(path){ return {path: path, version: settings.get("versions:alpha")} };
function context(req){
return {logger: req.log};
}
server.get(vAlpha('/ping'), function(req, res, next){
res.json();
next();
});
/**
* API to create or update an email template. If a template exists (accountId + Name pair), it will be updated. Otherwise a new one will be created
*/
server.post(vAlpha('/email/:name'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params || !params.name || !params.htmlData || !params.htmlType || !params.cssData || !params.cssType){
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
api.email.createOrUpdate.call(context(req), params.accountId, params.name, params.htmlData, params.htmlType, params.cssData, params.cssType, function(err){
if (err) {
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json();
}
next();
});
});
server.put(vAlpha('/trigger/:name/on/event'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.actionId || !params.eventName) {
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
var eventCondition = {
name: params.eventName,
attrs: params.eventAttrs
};
api.trigger.create.call(context(req),
params.accountId, params.name, eventCondition, null, params.actionId,
function(err, triggerDoc){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json({id: triggerDoc.id})
}
next();
})
});
server.put(vAlpha('/trigger/:name/on/time'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.actionId || (!params.next && !params.every)) {
var err = new restify.BadRequestError("Invalid arguments");
logger.info(err, params);
return res.send(err);
}
var timeCondition = {
next: params.next,
every: params.every
};
api.trigger.create.call(context(req),
params.accountId, params.name, null, timeCondition, params.actionId,
function(err, triggerDoc){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.json({id: triggerDoc.id})
}
next();
})
});
server.post(vAlpha('/event/:name'), auth, function(req, res, next){
var logger = req.log || globalLogger;
var params = req.params;
if (!params.accountId || !params.name || !params.userId){
var err = restify.BadRequestError("Invalid Arguments");
logger.info(err, params);
return res.send(err);
}
api.event.add.call(context(req),
params.accountId, params.name, params.userId, params.attrs,
function(err){
if (err){
logger.error(err);
res.send(new restify.InternalServerError("Something went wrong"));
}
else {
res.send();
}
next();
});
});
};
|
'use strict';
/**
* @ngdoc directive
* @name SubSnoopApp.directive:pieChart
* @description
* # pieChart
*/
angular.module('SubSnoopApp')
.directive('donutChart', ['d3Service', '$window', '$document', 'subFactory', '$filter', 'moment', 'sentiMood', 'reaction',
function (d3Service, $window, $document, subFactory, $filter, moment, sentiMood, reaction) {
/*
Based on http://embed.plnkr.co/YICxe0/
*/
var windowWidth = $window.innerWidth;
var $win = angular.element($window);
return {
restrict: 'EA',
replace: true,
scope: true,
link: function(scope, element, attrs) {
scope.chartReady = false;
scope.loaderImg = '../images/103.gif';
var subname = scope.subreddit;
d3Service.d3().then(function(d3) {
/*
Set dimensions for pie charts
*/
var height;
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
height = 375;
} else {
height = 475;
}
function configChart(scope_chart, window_width) {
if (window_width < 700) {
scope_chart = setChartConfig(300);
} else {
scope_chart = setChartConfig(260);
}
return scope_chart;
}
/*
Default configuration for pie chart
*/
function setChartConfig(chart_width) {
return {
width: chart_width,
height: height,
thickness: 30,
grow: 10,
labelPadding: 35,
duration: 0,
margin: {
top: 50, right: 50, bottom: -50, left: 50
}
};
};
function init() {
// --------------------------------------------------------
/*
Get data to populate pie charts
*/
var user;
var chartData;
var d3ChartEl;
// --------------------------------------------------------
scope.getChart = function() {
d3ChartEl = d3.select(element[0]);
user = subFactory.getUser();
if (subname && attrs.type === 'sentiment') {
sentiMood.setSubData(subname, subFactory.getEntries(subname, null), user);
chartData = sentiMood.getData(subname);
} else if (subname && attrs.type === 'reaction') {
reaction.setSubData(subname, subFactory.getEntries(subname, null), user);
chartData = reaction.getData(subname);
}
scope.chartReady = true;
scope.chartConfig = configChart(scope.chartConfig, windowWidth);
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'w': w.width()
};
};
try {
drawChart(chartData, scope.chartConfig);
w.bind('resize', function() {
scope.$apply();
drawChart(chartData, scope.chartConfig);
});
} catch(error) {
console.log(error);
}
}
}
/*
Draw the pie chart with center text and mouse over events
*/
function drawChart(chartData, chartConfig) {
var width = chartConfig.width,
height = chartConfig.height,
margin = chartConfig.margin,
grow = chartConfig.grow,
labelRadius,
radius,
duration = chartConfig.duration;
width = width - margin.left - margin.right;
height = height - margin.top - margin.bottom,
radius = Math.min(width, height) / 2,
labelRadius = radius + chartConfig.labelPadding;
var thickness = chartConfig.thickness || Math.floor(radius / 5);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - thickness);
var arcOver = d3.svg.arc()
.outerRadius(radius + grow)
.innerRadius(radius - thickness);
var pieFn = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var centerValue = (!!chartData.center.value) ? chartData.center.value : '';
var centerValue2 = (!!chartData.center.value2) ? chartData.center.value2 : '';
var d3ChartEl = d3.select(element[0]);
d3ChartEl.select('svg').remove();
var gRoot = d3ChartEl.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g');
gRoot.attr('transform', 'translate(' + (width / 2 + margin.left) + ',' + (height / 2 + margin.top) + ')');
var middleCircle = gRoot.append('svg:circle')
.attr('cx', 0)
.attr('cy', 0)
.attr('r', radius)
.style('fill', '#1F2327');
/*
Display percentage and center text statistics when hovering over an arc
*/
scope.mouseOverPath = function(d) {
d3.select(this)
.transition()
.duration(duration)
.each("end", function(d) {
d3.select('.center-value-' + attrs.type).text(d.data.label);
var line1;
if (attrs.type === 'upvotes') {
line1 = 'Points: ' + $filter('number')(d.data.value);
} else {
line1 = 'Entries: ' + $filter('number')(d.data.value);
}
d3.select('.line-1-' + attrs.type)
.text(line1);
d3.selectAll('.arc-' + attrs.type + ' .legend .percent')
.transition()
.duration(duration)
.style('fill-opacity', 0);
d3.select(this.parentNode).select('.legend .percent')
.transition()
.duration(duration)
.style("fill-opacity", 1);
d3.selectAll('.arc-' + attrs.type).style('opacity', function(e) {
return e.data.label === d.data.label ? '1' : '0.3';
});
})
.attr("d", arcOver);
};
/*
Shrink the arc back to original width of pie chart ring
*/
scope.reduceArc = function(d) {
try {
if (d) {
d3.select(this)
.transition()
.attr("d", arc);
} else {
d3.selectAll('.arc-' + attrs.type + ' path')
.each(function() {
d3.select(this)
.transition()
.attr("d", arc);
});
}
} catch(error) {
console.log("Error: " + error);
}
}
/*
The state of the chart when the mouse is not hovered over it
*/
scope.restoreCircle = function() {
d3.selectAll('.arc-' + attrs.type).style('opacity', '1');
d3.select('.center-value-' + attrs.type).text(centerValue);
d3.select('.line-1-' + attrs.type).text(centerValue2);
d3.selectAll('.arc-' + attrs.type + ' .legend .percent')
.transition()
.duration(duration)
.style("fill-opacity", 0);
scope.reduceArc();
};
gRoot.on('mouseleave', function(e) {
if (!e) {
scope.restoreCircle();
}
});
middleCircle.on('mouseover', function() {
scope.restoreCircle();
});
var arcs = gRoot.selectAll('g.arc')
.data(pieFn(chartData.values))
.enter()
.append('g')
.attr('class', 'arc-' + attrs.type);
var partition = arcs.append('svg:path')
.style('fill', function(d) {
return chartData.colors[d.data.label];
})
.on("mouseover", scope.mouseOverPath)
.each(function() {
this._current = {
startAngle: 0,
endAngle: 0
};
})
.on("mouseleave", scope.reduceArc)
.attr('d', arc)
.transition()
.duration(duration)
.attrTween('d', function(d) {
try {
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
} catch(error) {
console.log(e);
}
});
/*
Set up center text for pie chart with name of chart and number of posts
*/
var centerText = gRoot.append('svg:text')
.attr('class', 'center-label');
var titleSize = '14px';
var dataSize = '14px';
centerText.append('tspan')
.text(centerValue)
.attr('x', 0)
.attr('dy', '0em')
.attr("text-anchor", "middle")
.attr("class", 'center-value-' + attrs.type)
.attr("font-size", titleSize)
.attr("fill", "#fff")
.attr("font-weight", "bold");
centerText.append('tspan')
.text(centerValue2)
.attr('x', 0)
.attr('dy', '1em')
.attr("text-anchor", "middle")
.attr("class", 'line-1-' + attrs.type)
.attr("font-size", dataSize)
.attr("fill", "#9099A1")
.attr("font-weight", "400");
var percents = arcs.append("svg:text")
.style('fill-opacity', 0)
.attr('class', 'legend')
.attr("transform", function(d) {
var c = arc.centroid(d),
x = c[0],
y = c[1],
height = Math.sqrt(x * x + y * y);
return "translate(" + ((x-13) / height * labelRadius) + ',' +
((y+5) / height * labelRadius) + ")";
});
percents.append('tspan')
.attr('class', 'percent')
.attr('x', 0)
.attr('font-size', '13px')
.attr('font-weight', '400')
.attr('fill', '#fff')
.style("fill-opacity", 0)
.text(function(d, i) {
return d.data.percent + '%';
});
var legend = gRoot.append('g')
.attr('class', 'legend')
.selectAll('text')
.data(chartData.values)
.enter();
/*
Displays legend indicating what color represents what category
*/
legend.append('rect')
.attr('height', 10)
.attr('width', 10)
.attr('x', function(d) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return 0 - radius - 35;
} else {
return 0 - radius - 20;
}
})
.attr('y', function(d, i) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return (20 * (i + 1) - 210);
} else {
return (20 * (i + 1)) - 260;
}
})
.on('mouseover', function(d, i) {
var sel = d3.selectAll('.arc-' + attrs.type).filter(function(d) {
return d.data.id === i;
});
scope.mouseOverPath.call(sel.select('path')[0][0], sel.datum());
})
.style('fill', function(d) {
return chartData.colors[d.label];
});
legend.append('text')
.attr('x', function(d) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return 0 - radius - 15;
} else {
return 0 - radius;
}
})
.attr('y', function(d, i) {
if (attrs.type === 'sentiment' || attrs.type === 'reaction') {
return (20 * (i + 1) - 200);
} else {
return (20 * (i + 1)) - 250;
}
})
.attr('font-size', '12px')
.attr('fill', '#9099A1')
.on('mouseover', function(d, i) {
var sel = d3.selectAll('.arc-' + attrs.type).filter(function(d) {
return d.data.id === i;
});
scope.mouseOverPath.call(sel.select('path')[0][0], sel.datum());
})
.text(function(d) { return d.label; });
}
init();
$document.ready(function() {
var chart = angular.element('#piecharts-' + subname);
var donutElem = element.parent().parent().parent();
var prevElem = donutElem[0].previousElementSibling;
var idName = '#' + prevElem.id + ' .graph';
// If no activity in the last year, there will be no charts, get top entries instead
if (prevElem.id.length == 0) {
var prevElem = prevElem.previousElementSibling;
if (angular.element('#top-post-' + subname).length > 0) {
idName = '#' + prevElem.id + ' .post-content';
} else {
idName = '#' + prevElem.id + ' .post-body';
}
}
var winHeight = $win.innerHeight();
var listener = scope.$watch(function() { return angular.element(idName).height() > 0 }, function() {
var e = angular.element(idName);
if (!scope.chartReady && e.length > 0 && e[0].clientHeight > 0) {
var boxTop = chart[0].offsetTop - winHeight + 100;
$win.on('scroll', function (e) {
var scrollY = $win.scrollTop();
if (!scope.chartReady && (scrollY >= boxTop)) {
scope.getChart();
scope.$apply();
return;
}
});
}
});
});
});
}
};
}]);
|
// Description:
// There are two lists of different length. The first one consists of keys,
// the second one consists of values. Write a function
//createDict(keys, values) that returns a dictionary created from keys and
// values. If there are not enough values, the rest of keys should have a
//None (JS null)value. If there not enough keys, just ignore the rest of values.
// Example 1:
// keys = ['a', 'b', 'c', 'd']
// values = [1, 2, 3]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3, 'd': null}
// Example 2:
// keys = ['a', 'b', 'c']
// values = [1, 2, 3, 4]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3}
function createDict(keys, values){
var result = {};
for(var i = 0;i<keys.length;i++){
result[keys[i]] = values[i]!=undefined ? values[i] : null;
}
return result;
}
|
"use strict";
const { ParserError } = require("../util/errors");
const yaml = require("js-yaml");
module.exports = {
/**
* The order that this parser will run, in relation to other parsers.
*
* @type {number}
*/
order: 200,
/**
* Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
*
* @type {boolean}
*/
allowEmpty: true,
/**
* Determines whether this parser can parse a given file reference.
* Parsers that match will be tried, in order, until one successfully parses the file.
* Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
* every parser will be tried.
*
* @type {RegExp|string[]|function}
*/
canParse: [".yaml", ".yml", ".json"], // JSON is valid YAML
/**
* Parses the given file as YAML
*
* @param {object} file - An object containing information about the referenced file
* @param {string} file.url - The full URL of the referenced file
* @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
* @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
* @returns {Promise}
*/
async parse (file) { // eslint-disable-line require-await
let data = file.data;
if (Buffer.isBuffer(data)) {
data = data.toString();
}
if (typeof data === "string") {
try {
return yaml.load(data);
}
catch (e) {
throw new ParserError(e.message, file.url);
}
}
else {
// data is already a JavaScript value (object, array, number, null, NaN, etc.)
return data;
}
}
};
|
define([
'jquery',
'underscore',
'backbone',
'collections/users/students',
'collections/users/classes',
'collections/users/streams',
'text!templates/students/studentnew.html',
'text!templates/students/classes.html',
'text!templates/students/streams.html',
'jqueryui',
'bootstrap'
], function($, _, Backbone, Students, Classes, Streams, StudentTpl, classesTpl, streamsTpl){
var NewStudent = Backbone.View.extend({
tagName: 'div',
title: "New Student - Student Information System",
events: {
'submit form#new-student' : 'addStudent',
'change #class_id' : 'getStreams'
},
template: _.template(StudentTpl),
classesTpl: _.template(classesTpl),
streamsTpl: _.template(streamsTpl),
initialize: function(){
$("title").html(this.title);
//fetch list of all classes for this class from the database
var self = this;
Classes.fetch({
data: $.param({
token: tokenString
}),
success: function(data){
self.setClasses();
}
});
//fetch list of all streams for this client from the database
Streams.fetch({
data: $.param({
token: tokenString
})
});
},
render: function(){
this.$el.html(this.template());
this.$classes = this.$("#classes-list");
this.$streams = this.$("#streams-list");
return this;
},
addStudent: function(evt){
evt.preventDefault();
var student = {
reg_number: $("#reg_number").val(),
first_name: $("#first_name").val(),
middle_name: $("#middle_name").val(),
last_name: $("#last_name").val(),
dob: $("#dob").val(),
pob: $("#pob").val(),
bcn: $("#bcn").val(),
sex: $("#sex").val(),
nationality: $("#nationality").val(),
doa: $("#doa").val(),
class_id: $("#class_id").val(),
stream_id: ($("#stream_id").val()) ? $("#stream_id").val() : '',
address: $("#address").val(),
code: $("#code").val(),
town: $("#town").val(),
pg_f_name: $("#pg_f_name").val(),
pg_l_name: $("#pg_l_name").val(),
pg_email: $("#pg_email").val(),
pg_phone: $("#pg_phone").val()
};
$(".submit-button").html("Please wait...");
$(".error-message").hide(200);
$(".success-message").hide(200);
Students.create(student, {
url: baseURL + 'students/students?token=' + tokenString,
success: function(){
$(".success-message").html("Student added successfully!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
//empty the form
$("#reg_number").val(''),
$("#first_name").val(''),
$("#middle_name").val(''),
$("#last_name").val(''),
$("#dob").val(''),
$("#pob").val(''),
$("#bcn").val(''),
$("#sex").val(''),
$("#nationality").val(''),
$("#doa").val(''),
$("#class_id").val(''),
$("#stream_id").val(''),
$("#address").val(''),
$("#code").val(''),
$("#town").val(''),
$("#pg_f_name").val(''),
$("#pg_l_name").val(''),
$("#pg_email").val(''),
$("#pg_phone").val('')
},
error : function(jqXHR, textStatus, errorThrown) {
if(textStatus.status != 401 && textStatus.status != 403) {
$(".error-message").html("Please check the errors below!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
}
}
});
},
setClasses: function(){
this.$classes.empty();
var regClasses = [];
Classes.each(function(oneClass){
regClasses.push(oneClass.toJSON());
}, this);
this.$classes.html(this.classesTpl({
regClasses: regClasses
}));
},
getStreams: function(){
var classID = $("#class_id").val();
var regStreams = [];
var streams = Streams.where({
class_id: classID
});
$.each(streams, function(key, oneStream){
regStreams.push(oneStream.toJSON());
});
this.$streams.html(this.streamsTpl({
regStreams: regStreams
}));
}
});
return NewStudent;
}); |
/* global describe */
/* global module */
/* global beforeEach */
/* global inject */
/* global it */
/* global expect */
describe('PanZoom specs', function () {
var $scope = null;
var $compile = null;
var $interval = null;
var PanZoomService = null;
var deferred = null;
var $document = null;
// copied from jquery but makes it use the angular $interval instead of setInterval for its timer
var timerId = null;
jQuery.fx.start = function () {
//console.log('jQuery.fx.start');
if (!timerId) {
timerId = $interval(jQuery.fx.tick, jQuery.fx.interval);
}
};
jQuery.fx.stop = function () {
//console.log('jQuery.fx.stop');
$interval.cancel(timerId);
timerId = null;
};
// copied from jQuery but makes it possible to pretend to be in the future
var now = 0;
jQuery.now = function () {
return now;
};
var shark = {
x: 391,
y: 371,
width: 206,
height: 136
};
var chopper = {
x: 88,
y: 213,
width: 660,
height: 144
};
var ladder = {
x: 333,
y: 325,
width: 75,
height: 200
};
var testApp = angular.module('testApp', ['panzoom', 'panzoomwidget']);
beforeEach(module('testApp'));
beforeEach(inject(function ($rootScope, _$compile_, _$interval_, _PanZoomService_, $q, _$document_) {
$scope = $rootScope;
$compile = _$compile_;
$interval = _$interval_;
PanZoomService = _PanZoomService_;
deferred = $q.defer();
$document = _$document_;
$scope.rects = [chopper, shark, ladder];
// Instantiate models which will be passed to <panzoom> and <panzoomwidget>
// The panzoom config model can be used to override default configuration values
$scope.panzoomConfig = {
zoomLevels: 10,
neutralZoomLevel: 5,
scalePerZoomLevel: 1.5
};
// The panzoom model should initially be empty; it is initialized by the <panzoom>
// directive. It can be used to read the current state of pan and zoom. Also, it will
// contain methods for manipulating this state.
$scope.panzoomModel = {};
}));
afterEach(function () {
$scope.$broadcast('$destroy');
$interval.flush(jQuery.fx.interval); // wait for the first event tick to complete as this will do the actual unregistering
});
it('should create markup', function () {
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom>');
$compile(element)($scope);
$scope.$digest();
expect(element.html()).toMatch(/<div.*<\/div>/);
});
it('should not zoom when using neutral zoom level', function () {
$scope.panzoomConfig.neutralZoomLevel = 3;
$scope.panzoomConfig.initialZoomLevel = 3;
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom>');
$compile(element)($scope);
$scope.$digest();
expect($(element).find('.zoom-element').css('-webkit-transform')).toBe('scale(1)');
$scope.panzoomConfig.neutralZoomLevel = 5;
$scope.panzoomConfig.initialZoomLevel = 5;
element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom>');
$compile(element)($scope);
$scope.$digest();
expect($(element).find('.zoom-element').css('-webkit-transform')).toBe('scale(1)');
});
it('Should pan when the mouse is dragged', function () {
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"><div id="WrappedElement"/></panzoom>');
$compile(element)($scope);
$scope.$digest();
var overlay = $document.find('#PanZoomOverlay');
function createMouseEvent(type, clientX, clientY) {
var e = document.createEvent('MouseEvents');
// type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget
e.initMouseEvent(type, true, true, window, 1, 0, 0, clientX || 0, clientY || 0, false, false, false, false, 0, null);
e.preventDefault = undefined;
e.stopPropagation = undefined;
return e;
}
element.find('#WrappedElement').trigger(createMouseEvent('mousedown', 100, 100));
expect($scope.panzoomModel.pan).toEqual({
x: 0,
y: 0
});
now += 40; // pretend that time passed
overlay.trigger(createMouseEvent('mousemove', 110, 100));
expect($scope.panzoomModel.pan).toEqual({
x: 10,
y: 0
});
overlay.trigger(createMouseEvent('mouseup', 120, 120));
for (var i = 0; i < 10; i++) {
$interval.flush(jQuery.fx.interval);
now += jQuery.fx.interval;
}
expect($scope.panzoomModel.pan.x).toBeGreaterThan(10); // due to sliding effects; specific value doesn't matter
expect($scope.panzoomModel.pan.y).toEqual(0);
});
it('should pan when dragging the finger (touch)', function () {
var element = angular.element('<panzoom config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"><div id="WrappedElement"/></panzoom>');
$compile(element)($scope);
$scope.$digest();
var overlay = $document.find('#PanZoomOverlay');
function createTouchEvent(type, touches) {
var e = document.createEvent('MouseEvents');
// type, canBubble, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget
e.initMouseEvent(type, true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
e.touches = touches || [];
//e.preventDefault = undefined;
//e.stopPropagation = undefined;
return $.event.fix(e);
}
element.find('#WrappedElement').trigger(createTouchEvent('touchstart', [{pageX: 100, pageY: 100}]));
expect($scope.panzoomModel.pan).toEqual({
x: 0,
y: 0
});
now += 40; // pretend that time passed
overlay.trigger(createTouchEvent('touchmove', [{pageX: 110, pageY: 100}]));
expect($scope.panzoomModel.pan).toEqual({
x: 10,
y: 0
});
overlay.trigger(createTouchEvent('touchend'));
for (var i = 0; i < 10; i++) {
$interval.flush(jQuery.fx.interval);
now += jQuery.fx.interval;
}
expect($scope.panzoomModel.pan.x).toBeGreaterThan(10); // due to sliding effects; specific value doesn't matter
expect($scope.panzoomModel.pan.y).toEqual(0);
});
it('should use {{interpolated}} value for panzoomid', function () {
var element = angular.element('<panzoom id="{{panZoomElementId}}" config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"><div id="WrappedElement"/></panzoom>');
$scope.panZoomElementId = "panZoom1";
$compile(element)($scope);
var handler = jasmine.createSpy('success');
PanZoomService.getAPI('panZoom1').then(handler);
$scope.$digest();
expect(handler).toHaveBeenCalled();
});
it('should publish and unpublish its API', function () {
var _this = this;
var element = angular.element('<div ng-if="includeDirective"><panzoom id="PanZoomElementId" config="panzoomConfig" model="panzoomModel" style="width:800px; height: 600px"></panzoom></div>');
$compile(element)($scope);
$scope.includeDirective = true;
$scope.$digest();
var handler = jasmine.createSpy('success');
PanZoomService.getAPI('PanZoomElementId').then(handler);
$scope.$digest();
expect(handler).toHaveBeenCalled();
$scope.includeDirective = false;
$scope.$digest();
PanZoomService.getAPI('PanZoomElementId').then(function (api) {
_this.fail(Error('Failed to unregister API'));
});
});
});
|
var express = require('express');
var user = require('../model/user');
var jsonReturn = require('../common/jsonReturn');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
user.getUsers(function(err, rows, fields){
res.render('users', { users : rows } );
})
});
router.post('/getUsers', function (req, res, next) {
if(req.body.username){
user.getUsers(function(err, rows, fields){
res.json(jsonReturn({ users : rows } ));
})
}
});
module.exports = router;
|
import { createAction } from 'redux-actions';
import { APP_LAYOUT_CHANGE, APP_LAYOUT_INIT } from './constants';
// 选中菜单列表项
const appLayoutInit = createAction(APP_LAYOUT_INIT);
export const onAppLayoutInit = (key) => {
return (dispatch) => {
dispatch(appLayoutInit(key));
};
};
const appLayoutChange = createAction(APP_LAYOUT_CHANGE);
export const onAppLayoutChange = (key) => {
return (dispatch) => {
dispatch(appLayoutChange(key));
};
};
|
Subsets and Splits