code stringlengths 2 1.05M |
|---|
// rollup.config.js
import json from 'rollup-plugin-json';
export default {
output: {
format: 'umd',
},
plugins: [
json(),
],
};
|
var searchData=
[
['length',['Length',['../classCSF_1_1Zpt_1_1Rendering_1_1RepetitionInfo.html#ac5115ce30afab8873915bb65711a3bd8',1,'CSF::Zpt::Rendering::RepetitionInfo']]],
['localdefinitions',['LocalDefinitions',['../classCSF_1_1Zpt_1_1Rendering_1_1Model.html#a2d32cef4e4dca44c3b5a0aa0883cdc4b',1,'CSF::Zpt::Rendering::Model']]],
['lowerletter',['LowerLetter',['../classCSF_1_1Zpt_1_1Rendering_1_1RepetitionInfo.html#a5350e5974ab5adf39435f696465b9345',1,'CSF::Zpt::Rendering::RepetitionInfo']]]
];
|
/**
* Exports
*/
module.exports = isValue
/**
* Check if a value exists.
*
* @param {*} value
* @return {Boolean}
*/
function isValue(value) {
return !!arguments.length && value != null
}
|
function eForStep(arr, arrLen, i, callback) {
if (i < arrLen) {
let item = arr[i];
callback(true, item);
setTimeout(eForStep.bind(this, arr, arrLen, i + 1, callback), 0);
} else {
callback(false);
}
}
/**
* For statement emulation to work with large arrays without event loop blocking.
*
* eFor(arr, function (pending, item) {
* if (pending) {
* // do something with item
* } else {
* // do something after cycle end
* }
* });
*
* @param {Array} arr на вход получаем массив
* @param {Function} callback функция для выполнения с каждым элементом массива
*/
function eFor(arr, callback) {
eForStep(arr, arr.length, 0, callback);
}
export {eFor, eForStep};
|
/**
* @author Toru Nagashima
* @copyright 2017 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const RuleTester = require("eslint").RuleTester
const rule = require("../../../lib/rules/no-invalid-v-if")
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const tester = new RuleTester({
parser: "vue-eslint-parser",
parserOptions: {ecmaVersion: 2015},
})
tester.run("no-invalid-v-if", rule, {
valid: [
{
filename: "test.vue",
code: "",
},
{
filename: "test.vue",
code: "<template><div><div v-if=\"foo\"></div></div></template>",
},
],
invalid: [
{
filename: "test.vue",
code: "<template><div><div v-if=\"foo\" v-else></div></div></template>",
errors: ["'v-if' and 'v-else' directives can't exist on the same element. You may want 'v-else-if' directives."],
},
{
filename: "test.vue",
code: "<template><div><div v-if=\"foo\" v-else-if=\"bar\"></div></div></template>",
errors: ["'v-if' and 'v-else-if' directives can't exist on the same element."],
},
{
filename: "test.vue",
code: "<template><div><div v-if:aaa=\"foo\"></div></div></template>",
errors: ["'v-if' directives require no argument."],
},
{
filename: "test.vue",
code: "<template><div><div v-if.aaa=\"foo\"></div></div></template>",
errors: ["'v-if' directives require no modifier."],
},
{
filename: "test.vue",
code: "<template><div><div v-if></div></div></template>",
errors: ["'v-if' directives require that attribute value."],
},
],
})
|
module.exports = {
colorPrimary: '#4169E1',
colorPrimaryDark: '#2B58DE',
colorAccent: '#577AE4',
white: '#FFFFFF',
ghostWhite: '#F8F8FF',
whiteSmoke: '#E8E8E8',
silver: '#C0C0C0',
darkGray: '#A9A9A9',
gray: '#808080',
dimGray: '#696969',
black: '#000000',
}; |
/* global describe, it, expect, sinon */
const boolean = require('src/typeStrategies/boolean')
describe('type:boolean', () => {
it('calls context.fail if type is not a boolean', () => {
const context = {
value: 'foo',
fail: sinon.spy()
}
boolean.default(context)
expect(context.fail).to.be.calledWith('Value must be a boolean')
})
it('does not call context.fail if type is a boolean', () => {
const context = {
value: true,
fail: sinon.spy()
}
boolean.default(context)
expect(context.fail).to.not.be.called
})
})
|
function(doc){
if(doc.status){
emit(doc.date, doc);
}
} |
module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"rules": {
"accessor-pairs": "error",
"array-bracket-spacing": "error",
"array-callback-return": "error",
"arrow-body-style": "error",
"arrow-parens": [
"error",
"always"
],
"arrow-spacing": [
"error",
{
"after": true,
"before": true
}
],
"block-scoped-var": "error",
"block-spacing": "error",
"brace-style": [
"error",
"1tbs"
],
"callback-return": "error",
"camelcase": "error",
"capitalized-comments": "error",
"class-methods-use-this": "error",
"comma-dangle": "error",
"comma-spacing": [
"error",
{
"after": true,
"before": false
}
],
"comma-style": [
"error",
"last"
],
"complexity": "error",
"computed-property-spacing": "error",
"consistent-return": "error",
"consistent-this": "error",
"curly": "off",
"default-case": "error",
"dot-location": [
"error",
"property"
],
"dot-notation": "error",
"eol-last": "error",
"eqeqeq": "error",
"func-call-spacing": "error",
"func-name-matching": "error",
"func-names": [
"error",
"never"
],
"func-style": [
"error",
"declaration"
],
"generator-star-spacing": "error",
"global-require": "error",
"guard-for-in": "error",
"handle-callback-err": "error",
"id-blacklist": "error",
"id-match": "error",
"indent": "off",
"init-declarations": "off",
"jsx-quotes": "error",
"key-spacing": "error",
"keyword-spacing": "off",
"line-comment-position": "error",
"linebreak-style": [
"error",
"unix"
],
"lines-around-comment": "error",
"lines-around-directive": "off",
"max-depth": "error",
"max-len": "off",
"max-lines": "error",
"max-nested-callbacks": "error",
"max-params": "error",
"max-statements": "off",
"max-statements-per-line": "error",
"new-cap": "error",
"new-parens": "error",
"newline-after-var": [
"error",
"always"
],
"newline-before-return": "off",
"newline-per-chained-call": "error",
"no-alert": "error",
"no-array-constructor": "error",
"no-await-in-loop": "error",
"no-bitwise": "error",
"no-caller": "error",
"no-catch-shadow": "error",
"no-confusing-arrow": "error",
"no-continue": "error",
"no-div-regex": "error",
"no-duplicate-imports": "error",
"no-else-return": "error",
"no-empty-function": "error",
"no-eq-null": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-extra-label": "error",
"no-extra-parens": "off",
"no-floating-decimal": "error",
"no-implicit-coercion": "error",
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-inline-comments": "error",
"no-invalid-this": "error",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-lonely-if": "error",
"no-loop-func": "error",
"no-magic-numbers": "off",
"no-mixed-operators": [
"error",
{
"allowSamePrecedence": true
}
],
"no-mixed-requires": "error",
"no-multi-assign": "error",
"no-multi-spaces": "error",
"no-multi-str": "error",
"no-multiple-empty-lines": "error",
"no-native-reassign": "error",
"no-negated-condition": "error",
"no-negated-in-lhs": "error",
"no-nested-ternary": "error",
"no-new": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-new-require": "error",
"no-new-wrappers": "error",
"no-octal-escape": "error",
"no-param-reassign": [
"error",
{
"props": false
}
],
"no-path-concat": "error",
"no-plusplus": "off",
"no-process-env": "error",
"no-process-exit": "error",
"no-proto": "error",
"no-prototype-builtins": "error",
"no-restricted-globals": "error",
"no-restricted-imports": "error",
"no-restricted-modules": "error",
"no-restricted-properties": "error",
"no-restricted-syntax": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-script-url": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-shadow": "error",
"no-shadow-restricted-names": "error",
"no-spaced-func": "error",
"no-sync": "off",
"no-tabs": "off",
"no-template-curly-in-string": "error",
"no-ternary": "off",
"no-throw-literal": "error",
"no-trailing-spaces": "error",
"no-undef-init": "error",
"no-undefined": "error",
"no-underscore-dangle": "error",
"no-unmodified-loop-condition": "error",
"no-unneeded-ternary": "error",
"no-unused-expressions": "error",
"no-use-before-define": "off",
"no-useless-call": "error",
"no-useless-computed-key": "error",
"no-useless-concat": "error",
"no-useless-constructor": "error",
"no-useless-escape": "error",
"no-useless-rename": "error",
"no-useless-return": "error",
"no-var": "error",
"no-void": "error",
"no-warning-comments": "error",
"no-whitespace-before-property": "error",
"no-with": "error",
"object-curly-newline": "error",
"object-curly-spacing": "off",
"object-property-newline": "error",
"object-shorthand": "off",
"one-var": "off",
"one-var-declaration-per-line": [
"error",
"initializations"
],
"operator-assignment": "error",
"operator-linebreak": [
"error",
"before"
],
"padded-blocks": "off",
"prefer-arrow-callback": "off",
"prefer-const": "off",
"prefer-numeric-literals": "error",
"prefer-promise-reject-errors": "error",
"prefer-reflect": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "off",
"quote-props": "off",
"quotes": [
"error",
"single"
],
"radix": "error",
"require-await": "error",
"require-jsdoc": "off",
"rest-spread-spacing": "error",
"semi": "off",
"semi-spacing": "error",
"sort-imports": "error",
"sort-keys": "off",
"sort-vars": "off",
"space-before-blocks": "error",
"space-before-function-paren": "off",
"space-in-parens": [
"error",
"never"
],
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"strict": "error",
"symbol-description": "error",
"template-curly-spacing": "error",
"template-tag-spacing": "error",
"unicode-bom": [
"error",
"never"
],
"valid-jsdoc": "error",
"vars-on-top": "error",
"wrap-iife": "error",
"wrap-regex": "error",
"yield-star-spacing": "error",
"yoda": [
"error",
"never"
]
}
};
|
var jsonServer = require('json-server')
var server = jsonServer.create()
server.use(jsonServer.defaults())
var router = jsonServer.router('api/db.json')
server.use(router)
console.log('Listening at 5000')
server.listen(5000)
|
'use strict'
var _ = require('./lodash')
module.exports = universe
function universe(data, options) {
var service = {
options: _.assign({}, options),
columns: [],
filters: {},
dataListeners: [],
filterListeners: [],
}
var cf = require('./crossfilter')(service)
var filters = require('./filters')(service)
data = cf.generateColumns(data)
return cf.build(data)
.then(function (data) {
service.cf = data
return _.assign(service, {
add: cf.add,
remove: cf.remove,
column: require('./column')(service),
query: require('./query')(service),
filter: filters.filter,
filterAll: filters.filterAll,
applyFilters: filters.applyFilters,
clear: require('./clear')(service),
destroy: require('./destroy')(service),
onDataChange: onDataChange,
onFilter: onFilter,
})
})
function onDataChange(cb) {
service.dataListeners.push(cb)
return function () {
service.dataListeners.splice(service.dataListeners.indexOf(cb), 1)
}
}
function onFilter(cb) {
service.filterListeners.push(cb)
return function () {
service.filterListeners.splice(service.filterListeners.indexOf(cb), 1)
}
}
}
|
/*
nchor Slider by Cedric Dugas ***
*** Http://www.position-absolute.com ***
Never have an anchor jumping your content, slide it.
Don't forget to put an id to your anchor !
You can use and modify this script for any project you want, but please leave this comment as credit.
*****/
$(document).ready(function() {
$("#bubble").everyTime(10, function(){
$("#bubble").animate({top:"-15px"}, 600).animate({top:"15px"}, 1370);
});
$("a.scroll").anchorAnimate()
});
jQuery.fn.anchorAnimate = function(settings) {
settings = jQuery.extend({
speed : 1100
}, settings);
return this.each(function(){
var caller = this
$(caller).click(function (event) {
event.preventDefault()
var locationHref = window.location.href
var elementClick = $(caller).attr("href")
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
window.location.hash = elementClick
});
return false;
})
})
}
|
var adapters
, path = require('path')
, _aliases
, _adapters
, _paths;
_aliases = {
postgres: 'postgres'
, pg: 'postgres'
, postgresql: 'postgres'
, mysql: 'mysql'
, sqlite: 'sqlite'
, riak: 'riak'
, mongo: 'mongo'
, mongodb: 'mongo'
, memory: 'memory'
, filesystem: 'filesystem'
, level: 'level'
};
_adapters = {
postgres: {
path: 'sql/postgres'
, lib: 'pg'
, type: 'sql'
}
, mysql: {
path: 'sql/mysql'
, lib: 'mysql'
, type: 'sql'
}
, sqlite: {
path: 'sql/sqlite'
, lib: 'sqlite3'
, type: 'sql'
}
, riak: {
path: 'riak/index'
, lib: null
, type: 'nosql'
}
, mongo: {
path: 'mongo/index'
, lib: 'mongodb'
, type: 'nosql'
}
, memory: {
path: 'memory/index'
, lib: null
, type: 'nosql'
}
, filesystem: {
path: 'filesystem/index'
, lib: null
, type: 'nosql'
}
, level: {
path: 'level/index'
, lib: 'level'
, type: 'nosql'
}
};
for (var p in _adapters) {
_adapters[p].name = p;
}
adapters = new (function () {
this.getAdapterInfo = function (adapter) {
var canonical = _aliases[adapter]
, adapter = _adapters[canonical];
return adapter || null;
};
this.create = function (name, config) {
var info = this.getAdapterInfo(name)
, ctorPath
, ctor;
if (!info) {
throw new Error('"' + name + '" is not a valid adapter.');
}
ctorPath = path.join(__dirname, info.path)
ctor = require(ctorPath).Adapter;
return new ctor(config || {});
};
})();
module.exports = adapters;
|
'use strict';
//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
angular.module(ApplicationConfiguration.applicationModuleName).constant('_', window._);
angular.module(ApplicationConfiguration.applicationModuleName).constant('USER_ROLES', { admin : 'ADMIN', user : 'USER' });
//Then define the init function for starting up the application
angular.element(document).ready(function() {
//Fixing facebook bug with redirect
//if (window.location.hash === '#_=_') window.location.hash = '#!';
//Fixing google bug with redirect
//if (window.location.hash === '') window.location.hash = '#!';
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
|
import * as React from 'react';
import TopLayoutBlog from 'docs/src/modules/components/TopLayoutBlog';
import { docs } from './2021-q3-update.md?@mui/markdown';
export default function Page() {
return <TopLayoutBlog docs={docs} />;
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "m20.41 6.41-2.83-2.83c-.37-.37-.88-.58-1.41-.58H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h7.4l8.6-8.6V7.83c0-.53-.21-1.04-.59-1.42zM12 18c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-9c0 .55-.45 1-1 1H7c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h7c.55 0 1 .45 1 1v2zm4.99 7.25 1.77 1.77-4.84 4.84c-.1.09-.23.14-.36.14H15.5c-.28 0-.5-.22-.5-.5v-1.06c0-.13.05-.26.15-.35l4.84-4.84zm3.26.26-.85.85-1.77-1.77.85-.85c.2-.2.51-.2.71 0l1.06 1.06c.2.2.2.52 0 .71z"
}), 'SaveAsRounded'); |
function Modal(modalSelector, showCallback, hideCallback) {
this.shown = false;
this.showCallback = showCallback;
this.hideCallback = hideCallback;
this._modal = _(modalSelector);
this._triggerBtn = _(this._modal.data('trigger'));
this._closeBtn = _(this._modal.data('close'));
this._triggerBtn.on('click', this.show.bind(this));
this._closeBtn.on('click', this.hide.bind(this));
window.on('resize', this.invalidatePosition.bind(this));
}
Modal.prototype.getDimensions = function() {
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var modalWidth = this._modal.width();
var modalHeight = this._modal.height();
return [windowWidth, windowHeight, modalWidth, modalHeight];
}
Modal.prototype.getPosition = function(dimensions) {
var left = (dimensions[0] - dimensions[2]) / 2.0;
var top = (dimensions[1] - dimensions[3]) / 2.0;
return [top, left];
}
Modal.prototype.setPosition = function(position) {
this._modal.style.top = position[0] + 'px';
this._modal.style.left = position[1] + 'px';
}
Modal.prototype.invalidatePosition = function() {
if (!this.shown)
return;
var dimensions = this.getDimensions();
var position = this.getPosition(dimensions);
this.setPosition(position);
}
Modal.prototype.show = function() {
if (this.shown)
return;
this.shown = true;
this._modal.style.display = "block";
this.invalidatePosition();
if (this.showCallback)
this.showCallback();
}
Modal.prototype.hide = function() {
if (!this.shown)
return;
this.shown = false;
this._modal.style.display = "none";
if (this.hideCallback)
this.hideCallback();
}
|
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.402653, lng: -111.78539515},
zoom: 15,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
}
function hole1Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40206695, lng: -111.78514838},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4031413225741, -111.787138581276),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.401887209997, -111.783217191696),
map: map,
icon: Green
});
}
function hole2Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40418299, lng: -111.78313136},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4020792092027, -111.782788038254),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4063684103854, -111.783281564713),
map: map,
icon: Green
});
}
function hole3Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.4076387738438, lng: -111.7832896113395},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4068504178157, -111.783050894737),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4084271298719, -111.783528327942),
map: map,
icon: Green
});
}
function hole4Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.4068381413583, lng: -111.784080862999},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4085619247846, -111.78429543972),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.405114357932, -111.783866286278),
map: map,
icon: Green
});
}
function hole5Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.4037111656301, lng: -111.784088909626},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4051184428314, -111.784563660622),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4023038884288, -111.78361415863),
map: map,
icon: Green
});
}
function hole6Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40410740107695, lng: -111.7847728729245},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4024019300379, -111.784166693687),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.405812872116, -111.785379052162),
map: map,
icon: Green
});
}
function hole7Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.4069484361078, lng: -111.784791648388},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4054493188547, -111.784729957581),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4084475533609, -111.784853339195),
map: map,
icon: Green
});
}
function hole8Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.4079640236085, lng: -111.7861461639405},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4084812521041, -111.785588264465),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4074467951129, -111.786704063416),
map: map,
icon: Green
});
}
function hole9Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40567804248085, lng: -111.7864291369915},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4076612445616, -111.785923540592),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4036948404001, -111.786934733391),
map: map,
icon: Green
});
}
function hole10Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40211699156295, lng: -111.785341501236},
zoom: 16,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4029084760769, -111.78761869669),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.401325507049, -111.783064305782),
map: map,
icon: Green
});
}
function hole11Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.4033108312691, lng: -111.7822355031965},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4016952102438, -111.782114803791),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4049264522944, -111.782356202602),
map: map,
icon: Green
});
}
function hole12Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40320769806315, lng: -111.7817848920825},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4041094651626, -111.781862676144),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4023059309637, -111.781707108021),
map: map,
icon: Green
});
}
function hole13Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40082660791165, lng: -111.783859580755},
zoom: 16,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4011672080989, -111.781637370586),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4004860077244, -111.786081790924),
map: map,
icon: Green
});
}
function hole14Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40133571817495, lng: -111.786604821682},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4008577581085, -111.785888671875),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4018136782414, -111.787320971489),
map: map,
icon: Green
});
}
function hole15Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.40129077365305, lng: -111.7894586920735},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4024386956045, -111.788823008537),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4001428517016, -111.79009437561),
map: map,
icon: Green
});
}
function hole16Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.39866396443795, lng: -111.791269183159},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4006126481957, -111.790974140167),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.3967152806802, -111.791564226151),
map: map,
icon: Green
});
}
function hole17Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.3980225834686, lng: -111.7922776937485},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.3965804620435, -111.792744398117),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.3994647048937, -111.79181098938),
map: map,
icon: Green
});
}
function hole18Map() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.4017278714575, lng: -111.790705919266},
zoom: 17,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var Tee = 'img/golfTee.png';
var beachMarker1 = new google.maps.Marker({
position: new google.maps.LatLng(40.4001019996776, -111.791617870331),
map: map,
icon: Tee
});
var Green = 'img/golfFlag.png';
var beachMarker2 = new google.maps.Marker({
position: new google.maps.LatLng(40.4033537432374, -111.789793968201),
map: map,
icon: Green
});
}
var holes = 18;
function holeMaps() {
var newMap = new google.maps.Map(document.getElementById('map'), {
center: {
lat: beachMarker1.position.lat.value - beachMarker2.position.lat.value,
lng: beachMarker1.position.lng.value - beachMarker2.position.lng.value,
},
zoom: 18,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
maps.push(newMap);
}
var xhttp = new XMLHttpRequest();
function currentWeather() {
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var myObj = JSON.parse(xhttp.responseText);
document.getElementById("myWeather").innerHTML = myObj.weather[0].description;
document.getElementById("weatherImg").src = "http://openweathermap.org/img/w/" + myObj.weather[0].icon + ".png";
}
};
xhttp.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=Provo&appid=2ed7fbd66625cddb671decbf801e3add", true);
xhttp.send();
}
var myCourse = {};
function getCourseInfo() {
var xhttp = new XMLHttpRequest;
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myCourse = JSON.parse(xhttp.responseText);
var course = myCourse.course;
document.getElementById("g1").innerHTML = course.holes[0].tee_boxes[0].yards;
document.getElementById("g2").innerHTML = course.holes[1].tee_boxes[0].yards;
document.getElementById("g3").innerHTML = course.holes[2].tee_boxes[0].yards;
document.getElementById("g4").innerHTML = course.holes[3].tee_boxes[0].yards;
document.getElementById("g5").innerHTML = course.holes[4].tee_boxes[0].yards;
document.getElementById("g6").innerHTML = course.holes[5].tee_boxes[0].yards;
document.getElementById("g7").innerHTML = course.holes[6].tee_boxes[0].yards;
document.getElementById("g8").innerHTML = course.holes[7].tee_boxes[0].yards;
document.getElementById("g9").innerHTML = course.holes[8].tee_boxes[0].yards;
document.getElementById("g10").innerHTML = course.holes[9].tee_boxes[0].yards;
document.getElementById("g11").innerHTML = course.holes[10].tee_boxes[0].yards;
document.getElementById("g12").innerHTML = course.holes[11].tee_boxes[0].yards;
document.getElementById("g13").innerHTML = course.holes[12].tee_boxes[0].yards;
document.getElementById("g14").innerHTML = course.holes[13].tee_boxes[0].yards;
document.getElementById("g15").innerHTML = course.holes[14].tee_boxes[0].yards;
document.getElementById("g16").innerHTML = course.holes[15].tee_boxes[0].yards;
document.getElementById("g17").innerHTML = course.holes[16].tee_boxes[0].yards;
document.getElementById("g18").innerHTML = course.holes[17].tee_boxes[0].yards;
document.getElementById("b1").innerHTML = course.holes[0].tee_boxes[1].yards;
document.getElementById("b2").innerHTML = course.holes[1].tee_boxes[1].yards;
document.getElementById("b3").innerHTML = course.holes[2].tee_boxes[1].yards;
document.getElementById("b4").innerHTML = course.holes[3].tee_boxes[1].yards;
document.getElementById("b5").innerHTML = course.holes[4].tee_boxes[1].yards;
document.getElementById("b6").innerHTML = course.holes[5].tee_boxes[1].yards;
document.getElementById("b7").innerHTML = course.holes[6].tee_boxes[1].yards;
document.getElementById("b8").innerHTML = course.holes[7].tee_boxes[1].yards;
document.getElementById("b9").innerHTML = course.holes[8].tee_boxes[1].yards;
document.getElementById("b10").innerHTML = course.holes[9].tee_boxes[1].yards;
document.getElementById("b11").innerHTML = course.holes[10].tee_boxes[1].yards;
document.getElementById("b12").innerHTML = course.holes[11].tee_boxes[1].yards;
document.getElementById("b13").innerHTML = course.holes[12].tee_boxes[1].yards;
document.getElementById("b14").innerHTML = course.holes[13].tee_boxes[1].yards;
document.getElementById("b15").innerHTML = course.holes[14].tee_boxes[1].yards;
document.getElementById("b16").innerHTML = course.holes[15].tee_boxes[1].yards;
document.getElementById("b17").innerHTML = course.holes[16].tee_boxes[1].yards;
document.getElementById("b18").innerHTML = course.holes[17].tee_boxes[1].yards;
document.getElementById("w1").innerHTML = course.holes[0].tee_boxes[2].yards;
document.getElementById("w2").innerHTML = course.holes[1].tee_boxes[2].yards;
document.getElementById("w3").innerHTML = course.holes[2].tee_boxes[2].yards;
document.getElementById("w4").innerHTML = course.holes[3].tee_boxes[2].yards;
document.getElementById("w5").innerHTML = course.holes[4].tee_boxes[2].yards;
document.getElementById("w6").innerHTML = course.holes[5].tee_boxes[2].yards;
document.getElementById("w7").innerHTML = course.holes[6].tee_boxes[2].yards;
document.getElementById("w8").innerHTML = course.holes[7].tee_boxes[2].yards;
document.getElementById("w9").innerHTML = course.holes[8].tee_boxes[2].yards;
document.getElementById("w10").innerHTML = course.holes[9].tee_boxes[2].yards;
document.getElementById("w11").innerHTML = course.holes[10].tee_boxes[2].yards;
document.getElementById("w12").innerHTML = course.holes[11].tee_boxes[2].yards;
document.getElementById("w13").innerHTML = course.holes[12].tee_boxes[2].yards;
document.getElementById("w14").innerHTML = course.holes[13].tee_boxes[2].yards;
document.getElementById("w15").innerHTML = course.holes[14].tee_boxes[2].yards;
document.getElementById("w16").innerHTML = course.holes[15].tee_boxes[2].yards;
document.getElementById("w17").innerHTML = course.holes[16].tee_boxes[2].yards;
document.getElementById("w18").innerHTML = course.holes[17].tee_boxes[2].yards;
document.getElementById("r1").innerHTML = course.holes[0].tee_boxes[3].yards;
document.getElementById("r2").innerHTML = course.holes[1].tee_boxes[3].yards;
document.getElementById("r3").innerHTML = course.holes[2].tee_boxes[3].yards;
document.getElementById("r4").innerHTML = course.holes[3].tee_boxes[3].yards;
document.getElementById("r5").innerHTML = course.holes[4].tee_boxes[3].yards;
document.getElementById("r6").innerHTML = course.holes[5].tee_boxes[3].yards;
document.getElementById("r7").innerHTML = course.holes[6].tee_boxes[3].yards;
document.getElementById("r8").innerHTML = course.holes[7].tee_boxes[3].yards;
document.getElementById("r9").innerHTML = course.holes[8].tee_boxes[3].yards;
document.getElementById("r10").innerHTML = course.holes[9].tee_boxes[3].yards;
document.getElementById("r11").innerHTML = course.holes[10].tee_boxes[3].yards;
document.getElementById("r12").innerHTML = course.holes[11].tee_boxes[3].yards;
document.getElementById("r13").innerHTML = course.holes[12].tee_boxes[3].yards;
document.getElementById("r14").innerHTML = course.holes[13].tee_boxes[3].yards;
document.getElementById("r15").innerHTML = course.holes[14].tee_boxes[3].yards;
document.getElementById("r16").innerHTML = course.holes[15].tee_boxes[3].yards;
document.getElementById("r17").innerHTML = course.holes[16].tee_boxes[3].yards;
document.getElementById("r18").innerHTML = course.holes[17].tee_boxes[3].yards;
document.getElementById("h1").innerHTML = course.holes[0].tee_boxes[0].hcp;
document.getElementById("h2").innerHTML = course.holes[1].tee_boxes[0].hcp;
document.getElementById("h3").innerHTML = course.holes[2].tee_boxes[0].hcp;
document.getElementById("h4").innerHTML = course.holes[3].tee_boxes[0].hcp;
document.getElementById("h5").innerHTML = course.holes[4].tee_boxes[0].hcp;
document.getElementById("h6").innerHTML = course.holes[5].tee_boxes[0].hcp;
document.getElementById("h7").innerHTML = course.holes[6].tee_boxes[0].hcp;
document.getElementById("h8").innerHTML = course.holes[7].tee_boxes[0].hcp;
document.getElementById("h9").innerHTML = course.holes[8].tee_boxes[0].hcp;
document.getElementById("h10").innerHTML = course.holes[9].tee_boxes[0].hcp;
document.getElementById("h11").innerHTML = course.holes[10].tee_boxes[0].hcp;
document.getElementById("h12").innerHTML = course.holes[11].tee_boxes[0].hcp;
document.getElementById("h13").innerHTML = course.holes[12].tee_boxes[0].hcp;
document.getElementById("h14").innerHTML = course.holes[13].tee_boxes[0].hcp;
document.getElementById("h15").innerHTML = course.holes[14].tee_boxes[0].hcp;
document.getElementById("h16").innerHTML = course.holes[15].tee_boxes[0].hcp;
document.getElementById("h17").innerHTML = course.holes[16].tee_boxes[0].hcp;
document.getElementById("h18").innerHTML = course.holes[17].tee_boxes[0].hcp;
document.getElementById("p1").innerHTML = course.holes[0].tee_boxes[0].par;
document.getElementById("p2").innerHTML = course.holes[1].tee_boxes[0].par;
document.getElementById("p3").innerHTML = course.holes[2].tee_boxes[0].par;
document.getElementById("p4").innerHTML = course.holes[3].tee_boxes[0].par;
document.getElementById("p5").innerHTML = course.holes[4].tee_boxes[0].par;
document.getElementById("p6").innerHTML = course.holes[5].tee_boxes[0].par;
document.getElementById("p7").innerHTML = course.holes[6].tee_boxes[0].par;
document.getElementById("p8").innerHTML = course.holes[7].tee_boxes[0].par;
document.getElementById("p9").innerHTML = course.holes[8].tee_boxes[0].par;
document.getElementById("p10").innerHTML = course.holes[9].tee_boxes[0].par;
document.getElementById("p11").innerHTML = course.holes[10].tee_boxes[0].par;
document.getElementById("p12").innerHTML = course.holes[11].tee_boxes[0].par;
document.getElementById("p13").innerHTML = course.holes[12].tee_boxes[0].par;
document.getElementById("p14").innerHTML = course.holes[13].tee_boxes[0].par;
document.getElementById("p15").innerHTML = course.holes[14].tee_boxes[0].par;
document.getElementById("p16").innerHTML = course.holes[15].tee_boxes[0].par;
document.getElementById("p17").innerHTML = course.holes[16].tee_boxes[0].par;
document.getElementById("p18").innerHTML = course.holes[17].tee_boxes[0].par;
function total() {
var g1 = document.getElementById('g1').innerHTML;
var g2 = document.getElementById('g2').innerHTML;
var g3 = document.getElementById('g3').innerHTML;
var g4 = document.getElementById('g4').innerHTML;
var g5 = document.getElementById('g5').innerHTML;
var g6 = document.getElementById('g6').innerHTML;
var g7 = document.getElementById('g7').innerHTML;
var g8 = document.getElementById('g8').innerHTML;
var g9 = document.getElementById('g9').innerHTML;
var g10 = document.getElementById('g10').innerHTML;
var g11 = document.getElementById('g11').innerHTML;
var g12 = document.getElementById('g12').innerHTML;
var g13 = document.getElementById('g13').innerHTML;
var g14 = document.getElementById('g14').innerHTML;
var g15 = document.getElementById('g15').innerHTML;
var g16 = document.getElementById('g16').innerHTML;
var g17 = document.getElementById('g17').innerHTML;
var g18 = document.getElementById('g18').innerHTML;
var gOutTotal = Number(g1) + Number(g2) + Number(g3) + Number(g4) + Number(g5) + Number(g6) + Number(g7) + Number(g8) + Number(g9);
document.getElementById('gOutTotal').innerHTML = gOutTotal;
var gGrandTotal = Number(g1) + Number(g2) + Number(g3) + Number(g4) + Number(g5) + Number(g6) + Number(g7) + Number(g8) + Number(g9) +
Number(g10) + Number(g11) + Number(g12) + Number(g13) + Number(g14) + Number(g15) + Number(g16) + Number(g17) + Number(g18);
document.getElementById('gGrandTotal').innerHTML = gGrandTotal;
var b1 = document.getElementById('b1').innerHTML;
var b2 = document.getElementById('b2').innerHTML;
var b3 = document.getElementById('b3').innerHTML;
var b4 = document.getElementById('b4').innerHTML;
var b5 = document.getElementById('b5').innerHTML;
var b6 = document.getElementById('b6').innerHTML;
var b7 = document.getElementById('b7').innerHTML;
var b8 = document.getElementById('b8').innerHTML;
var b9 = document.getElementById('b9').innerHTML;
var b10 = document.getElementById('b10').innerHTML;
var b11 = document.getElementById('b11').innerHTML;
var b12 = document.getElementById('b12').innerHTML;
var b13 = document.getElementById('b13').innerHTML;
var b14 = document.getElementById('b14').innerHTML;
var b15 = document.getElementById('b15').innerHTML;
var b16 = document.getElementById('b16').innerHTML;
var b17 = document.getElementById('b17').innerHTML;
var b18 = document.getElementById('b18').innerHTML;
var bOutTotal = Number(b1) + Number(b2) + Number(b3) + Number(b4) + Number(b5) + Number(b6) + Number(b7) + Number(b8) + Number(b9);
document.getElementById('bOutTotal').innerHTML = bOutTotal;
var bGrandTotal = Number(b1) + Number(b2) + Number(b3) + Number(b4) + Number(b5) + Number(b6) + Number(b7) + Number(b8) + Number(b9) +
Number(b10) + Number(b11) + Number(b12) + Number(b13) + Number(b14) + Number(b15) + Number(b16) + Number(b17) + Number(b18);
document.getElementById('bGrandTotal').innerHTML = bGrandTotal;
var w1 = document.getElementById('w1').innerHTML;
var w2 = document.getElementById('w2').innerHTML;
var w3 = document.getElementById('w3').innerHTML;
var w4 = document.getElementById('w4').innerHTML;
var w5 = document.getElementById('w5').innerHTML;
var w6 = document.getElementById('w6').innerHTML;
var w7 = document.getElementById('w7').innerHTML;
var w8 = document.getElementById('w8').innerHTML;
var w9 = document.getElementById('w9').innerHTML;
var w10 = document.getElementById('w10').innerHTML;
var w11 = document.getElementById('w11').innerHTML;
var w12 = document.getElementById('w12').innerHTML;
var w13 = document.getElementById('w13').innerHTML;
var w14 = document.getElementById('w14').innerHTML;
var w15 = document.getElementById('w15').innerHTML;
var w16 = document.getElementById('w16').innerHTML;
var w17 = document.getElementById('w17').innerHTML;
var w18 = document.getElementById('w18').innerHTML;
var wOutTotal = Number(w1) + Number(w2) + Number(w3) + Number(w4) + Number(w5) + Number(w6) + Number(w7) + Number(w8) + Number(w9);
document.getElementById('wOutTotal').innerHTML = wOutTotal;
var wGrandTotal = Number(w1) + Number(w2) + Number(w3) + Number(w4) + Number(w5) + Number(w6) + Number(w7) + Number(w8) + Number(w9) +
Number(w10) + Number(w11) + Number(w12) + Number(w13) + Number(w14) + Number(w15) + Number(w16) + Number(w17) + Number(w18);
document.getElementById('wGrandTotal').innerHTML = wGrandTotal;
var r1 = document.getElementById('r1').innerHTML;
var r2 = document.getElementById('r2').innerHTML;
var r3 = document.getElementById('r3').innerHTML;
var r4 = document.getElementById('r4').innerHTML;
var r5 = document.getElementById('r5').innerHTML;
var r6 = document.getElementById('r6').innerHTML;
var r7 = document.getElementById('r7').innerHTML;
var r8 = document.getElementById('r8').innerHTML;
var r9 = document.getElementById('r9').innerHTML;
var r10 = document.getElementById('r10').innerHTML;
var r11 = document.getElementById('r11').innerHTML;
var r12 = document.getElementById('r12').innerHTML;
var r13 = document.getElementById('r13').innerHTML;
var r14 = document.getElementById('r14').innerHTML;
var r15 = document.getElementById('r15').innerHTML;
var r16 = document.getElementById('r16').innerHTML;
var r17 = document.getElementById('r17').innerHTML;
var r18 = document.getElementById('r18').innerHTML;
var rOutTotal = Number(r1) + Number(r2) + Number(r3) + Number(r4) + Number(r5) + Number(r6) + Number(r7) + Number(r8) + Number(r9);
document.getElementById('rOutTotal').innerHTML = rOutTotal;
var rGrandTotal = Number(r1) + Number(r2) + Number(r3) + Number(r4) + Number(r5) + Number(r6) + Number(r7) + Number(r8) + Number(r9) +
Number(r10) + Number(r11) + Number(r12) + Number(r13) + Number(r14) + Number(r15) + Number(r16) + Number(r17) + Number(r18);
document.getElementById('rGrandTotal').innerHTML = rGrandTotal;
var h1 = document.getElementById('h1').innerHTML;
var h2 = document.getElementById('h2').innerHTML;
var h3 = document.getElementById('h3').innerHTML;
var h4 = document.getElementById('h4').innerHTML;
var h5 = document.getElementById('h5').innerHTML;
var h6 = document.getElementById('h6').innerHTML;
var h7 = document.getElementById('h7').innerHTML;
var h8 = document.getElementById('h8').innerHTML;
var h9 = document.getElementById('h9').innerHTML;
var h10 = document.getElementById('h10').innerHTML;
var h11 = document.getElementById('h11').innerHTML;
var h12 = document.getElementById('h12').innerHTML;
var h13 = document.getElementById('h13').innerHTML;
var h14 = document.getElementById('h14').innerHTML;
var h15 = document.getElementById('h15').innerHTML;
var h16 = document.getElementById('h16').innerHTML;
var h17 = document.getElementById('h17').innerHTML;
var h18 = document.getElementById('h18').innerHTML;
var hOutTotal = Number(h1) + Number(h2) + Number(h3) + Number(h4) + Number(h5) + Number(h6) + Number(h7) + Number(h8) + Number(h9);
document.getElementById('hOutTotal').innerHTML = hOutTotal;
var hGrandTotal = Number(h1) + Number(h2) + Number(h3) + Number(h4) + Number(h5) + Number(h6) + Number(h7) + Number(h8) + Number(h9) +
Number(h10) + Number(h11) + Number(h12) + Number(h13) + Number(h14) + Number(h15) + Number(h16) + Number(h17) + Number(h18);
document.getElementById('hGrandTotal').innerHTML = hGrandTotal;
var p1 = document.getElementById('p1').innerHTML;
var p2 = document.getElementById('p2').innerHTML;
var p3 = document.getElementById('p3').innerHTML;
var p4 = document.getElementById('p4').innerHTML;
var p5 = document.getElementById('p5').innerHTML;
var p6 = document.getElementById('p6').innerHTML;
var p7 = document.getElementById('p7').innerHTML;
var p8 = document.getElementById('p8').innerHTML;
var p9 = document.getElementById('p9').innerHTML;
var p10 = document.getElementById('p10').innerHTML;
var p11 = document.getElementById('p11').innerHTML;
var p12 = document.getElementById('p12').innerHTML;
var p13 = document.getElementById('p13').innerHTML;
var p14 = document.getElementById('p14').innerHTML;
var p15 = document.getElementById('p15').innerHTML;
var p16 = document.getElementById('p16').innerHTML;
var p17 = document.getElementById('p17').innerHTML;
var p18 = document.getElementById('p18').innerHTML;
var pOutTotal = Number(p1) + Number(p2) + Number(p3) + Number(p4) + Number(p5) + Number(p6) + Number(p7) + Number(p8) + Number(p9);
document.getElementById('pOutTotal').innerHTML = pOutTotal;
var pGrandTotal = Number(p1) + Number(p2) + Number(p3) + Number(p4) + Number(p5) + Number(p6) + Number(p7) + Number(p8) + Number(p9) +
Number(p10) + Number(p11) + Number(p12) + Number(p13) + Number(p14) + Number(p15) + Number(p16) + Number(p17) + Number(p18);
document.getElementById('pGrandTotal').innerHTML = pGrandTotal;
}
total()
}
};
xhttp.open("GET", "http://golf-courses-api.herokuapp.com/courses/18300", true);
xhttp.send();
}
function playertotals() {
var p1h1 = document.getElementById('p1h1').value;
var p1h2 = document.getElementById('p1h2').value;
var p1h3 = document.getElementById('p1h3').value;
var p1h4 = document.getElementById('p1h4').value;
var p1h5 = document.getElementById('p1h5').value;
var p1h6 = document.getElementById('p1h6').value;
var p1h7 = document.getElementById('p1h7').value;
var p1h8 = document.getElementById('p1h8').value;
var p1h9 = document.getElementById('p1h9').value;
var p1h10 = document.getElementById('p1h10').value;
var p1h11 = document.getElementById('p1h11').value;
var p1h12 = document.getElementById('p1h12').value;
var p1h13 = document.getElementById('p1h13').value;
var p1h14 = document.getElementById('p1h14').value;
var p1h15 = document.getElementById('p1h15').value;
var p1h16 = document.getElementById('p1h16').value;
var p1h17 = document.getElementById('p1h17').value;
var p1h18 = document.getElementById('p1h18').value;
var p1OutTotal = Number(p1h1) + Number(p1h2) + Number(p1h3) + Number(p1h4) + Number(p1h5) + Number(p1h6) + Number(p1h7) + Number(p1h8) + Number(p1h9);
document.getElementById('p1OutTotal').innerHTML = p1OutTotal;
var p1GrandTotal = Number(p1h1) + Number(p1h2) + Number(p1h3) + Number(p1h4) + Number(p1h5) + Number(p1h6) + Number(p1h7) + Number(p1h8) + Number(p1h9) +
Number(p1h10) + Number(p1h11) + Number(p1h12) + Number(p1h13) + Number(p1h14) + Number(p1h15) + Number(p1h16) + Number(p1h17) + Number(p1h18);
document.getElementById('p1GrandTotal').innerHTML = p1GrandTotal;
var p2h1 = document.getElementById('p2h1').value;
var p2h2 = document.getElementById('p2h2').value;
var p2h3 = document.getElementById('p2h3').value;
var p2h4 = document.getElementById('p2h4').value;
var p2h5 = document.getElementById('p2h5').value;
var p2h6 = document.getElementById('p2h6').value;
var p2h7 = document.getElementById('p2h7').value;
var p2h8 = document.getElementById('p2h8').value;
var p2h9 = document.getElementById('p2h9').value;
var p2h10 = document.getElementById('p2h10').value;
var p2h11 = document.getElementById('p2h11').value;
var p2h12 = document.getElementById('p2h12').value;
var p2h13 = document.getElementById('p2h13').value;
var p2h14 = document.getElementById('p2h14').value;
var p2h15 = document.getElementById('p2h15').value;
var p2h16 = document.getElementById('p2h16').value;
var p2h17 = document.getElementById('p2h17').value;
var p2h18 = document.getElementById('p2h18').value;
var p2OutTotal = Number(p2h1) + Number(p2h2) + Number(p2h3) + Number(p2h4) + Number(p2h5) + Number(p2h6) + Number(p2h7) + Number(p2h8) + Number(p2h9);
document.getElementById('p2OutTotal').innerHTML = p2OutTotal;
var p2GrandTotal = Number(p2h1) + Number(p2h2) + Number(p2h3) + Number(p2h4) + Number(p2h5) + Number(p2h6) + Number(p2h7) + Number(p2h8) + Number(p2h9) +
Number(p2h10) + Number(p2h11) + Number(p2h12) + Number(p2h13) + Number(p2h14) + Number(p2h15) + Number(p2h16) + Number(p2h17) + Number(p2h18);
document.getElementById('p2GrandTotal').innerHTML = p2GrandTotal;
var p3h1 = document.getElementById('p3h1').value;
var p3h2 = document.getElementById('p3h2').value;
var p3h3 = document.getElementById('p3h3').value;
var p3h4 = document.getElementById('p3h4').value;
var p3h5 = document.getElementById('p3h5').value;
var p3h6 = document.getElementById('p3h6').value;
var p3h7 = document.getElementById('p3h7').value;
var p3h8 = document.getElementById('p3h8').value;
var p3h9 = document.getElementById('p3h9').value;
var p3h10 = document.getElementById('p3h10').value;
var p3h11 = document.getElementById('p3h11').value;
var p3h12 = document.getElementById('p3h12').value;
var p3h13 = document.getElementById('p3h13').value;
var p3h14 = document.getElementById('p3h14').value;
var p3h15 = document.getElementById('p3h15').value;
var p3h16 = document.getElementById('p3h16').value;
var p3h17 = document.getElementById('p3h17').value;
var p3h18 = document.getElementById('p3h18').value;
var p3OutTotal = Number(p3h1) + Number(p3h2) + Number(p3h3) + Number(p3h4) + Number(p3h5) + Number(p3h6) + Number(p3h7) + Number(p3h8) + Number(p3h9);
document.getElementById('p3OutTotal').innerHTML = p3OutTotal;
var p3GrandTotal = Number(p3h1) + Number(p3h2) + Number(p3h3) + Number(p3h4) + Number(p3h5) + Number(p3h6) + Number(p3h7) + Number(p3h8) + Number(p3h9) +
Number(p3h10) + Number(p3h11) + Number(p3h12) + Number(p3h13) + Number(p3h14) + Number(p3h15) + Number(p3h16) + Number(p3h17) + Number(p3h18);
document.getElementById('p3GrandTotal').innerHTML = p3GrandTotal;
var p4h1 = document.getElementById('p4h1').value;
var p4h2 = document.getElementById('p4h2').value;
var p4h3 = document.getElementById('p4h3').value;
var p4h4 = document.getElementById('p4h4').value;
var p4h5 = document.getElementById('p4h5').value;
var p4h6 = document.getElementById('p4h6').value;
var p4h7 = document.getElementById('p4h7').value;
var p4h8 = document.getElementById('p4h8').value;
var p4h9 = document.getElementById('p4h9').value;
var p4h10 = document.getElementById('p4h10').value;
var p4h11 = document.getElementById('p4h11').value;
var p4h12 = document.getElementById('p4h12').value;
var p4h13 = document.getElementById('p4h13').value;
var p4h14 = document.getElementById('p4h14').value;
var p4h15 = document.getElementById('p4h15').value;
var p4h16 = document.getElementById('p4h16').value;
var p4h17 = document.getElementById('p4h17').value;
var p4h18 = document.getElementById('p4h18').value;
var p4OutTotal = Number(p4h1) + Number(p4h2) + Number(p4h3) + Number(p4h4) + Number(p4h5) + Number(p4h6) + Number(p4h7) + Number(p4h8) + Number(p4h9);
document.getElementById('p4OutTotal').innerHTML = p4OutTotal;
var p4GrandTotal = Number(p4h1) + Number(p4h2) + Number(p4h3) + Number(p4h4) + Number(p4h5) + Number(p4h6) + Number(p4h7) + Number(p4h8) + Number(p4h9) +
Number(p4h10) + Number(p4h11) + Number(p4h12) + Number(p4h13) + Number(p4h14) + Number(p4h15) + Number(p4h16) + Number(p4h17) + Number(p4h18);
document.getElementById('p4GrandTotal').innerHTML = p4GrandTotal;
var p5h1 = document.getElementById('p5h1').value;
var p5h2 = document.getElementById('p5h2').value;
var p5h3 = document.getElementById('p5h3').value;
var p5h4 = document.getElementById('p5h4').value;
var p5h5 = document.getElementById('p5h5').value;
var p5h6 = document.getElementById('p5h6').value;
var p5h7 = document.getElementById('p5h7').value;
var p5h8 = document.getElementById('p5h8').value;
var p5h9 = document.getElementById('p5h9').value;
var p5h10 = document.getElementById('p5h10').value;
var p5h11 = document.getElementById('p5h11').value;
var p5h12 = document.getElementById('p5h12').value;
var p5h13 = document.getElementById('p5h13').value;
var p5h14 = document.getElementById('p5h14').value;
var p5h15 = document.getElementById('p5h15').value;
var p5h16 = document.getElementById('p5h16').value;
var p5h17 = document.getElementById('p5h17').value;
var p5h18 = document.getElementById('p5h18').value;
var p5OutTotal = Number(p5h1) + Number(p5h2) + Number(p5h3) + Number(p5h4) + Number(p5h5) + Number(p5h6) + Number(p5h7) + Number(p5h8) + Number(p5h9);
document.getElementById('p5OutTotal').innerHTML = p5OutTotal;
var p5GrandTotal = Number(p5h1) + Number(p5h2) + Number(p5h3) + Number(p5h4) + Number(p5h5) + Number(p5h6) + Number(p5h7) + Number(p5h8) + Number(p5h9) +
Number(p5h10) + Number(p5h11) + Number(p5h12) + Number(p5h13) + Number(p5h14) + Number(p5h15) + Number(p5h16) + Number(p5h17) + Number(p5h18);
document.getElementById('p5GrandTotal').innerHTML = p5GrandTotal;
var p6h1 = document.getElementById('p6h1').value;
var p6h2 = document.getElementById('p6h2').value;
var p6h3 = document.getElementById('p6h3').value;
var p6h4 = document.getElementById('p6h4').value;
var p6h5 = document.getElementById('p6h5').value;
var p6h6 = document.getElementById('p6h6').value;
var p6h7 = document.getElementById('p6h7').value;
var p6h8 = document.getElementById('p6h8').value;
var p6h9 = document.getElementById('p6h9').value;
var p6h10 = document.getElementById('p6h10').value;
var p6h11 = document.getElementById('p6h11').value;
var p6h12 = document.getElementById('p6h12').value;
var p6h13 = document.getElementById('p6h13').value;
var p6h14 = document.getElementById('p6h14').value;
var p6h15 = document.getElementById('p6h15').value;
var p6h16 = document.getElementById('p6h16').value;
var p6h17 = document.getElementById('p6h17').value;
var p6h18 = document.getElementById('p6h18').value;
var p6OutTotal = Number(p6h1) + Number(p6h2) + Number(p6h3) + Number(p6h4) + Number(p6h5) + Number(p6h6) + Number(p6h7) + Number(p6h8) + Number(p6h9);
document.getElementById('p6OutTotal').innerHTML = p6OutTotal;
var p6GrandTotal = Number(p6h1) + Number(p6h2) + Number(p6h3) + Number(p6h4) + Number(p6h5) + Number(p6h6) + Number(p6h7) + Number(p6h8) + Number(p6h9) +
Number(p6h10) + Number(p6h11) + Number(p6h12) + Number(p6h13) + Number(p6h14) + Number(p6h15) + Number(p6h16) + Number(p6h17) + Number(p6h18);
document.getElementById('p6GrandTotal').innerHTML = p6GrandTotal;
}
// These are my previous attempts at making my card dynamic.
/*
var numplayers = 1;
var numholes = 18;
function buildcard(){
var numplayers = document.getElementById("numPlayers").value;
var numholes = 18;
var holecollection = "";
var playercollection = "";
var grandTotalCollection = "";
var hole = "";
// create column of player labels
for(var pl = 1; pl <= numplayers; pl++ ){
playercollection += "<input id='player" + pl + "' class='holebox playerbox' placeholder='Player Name'/><br/>";
grandTotalCollection += "<div id='grand" + pl + "' class='grandTotal'></div>";
}
// create golf hole columns before you add holes to them.
for(var c = numholes; c >= 1; c-- ){
holecollection += "<div id='column" + c +"'><div class='holenumbertitle' onclick='holeMaps()'>" + c + "</div></div>" ;
}
// call the function that builds the holes into the columns
function collectHoles() {
var p;
var h;
for(p = 1; p <= numplayers; p++) {
for(h = 1; h <= 18; h++) {
var playerId = "player" + p + "Hole" + h;
hole = "<div id='holeInputs'><input id = " + playerId + " class='holeBox' onkeyup='calculateScore(" + p + ")'></div>";
$("#rightcard").append(hole);
}
// Add the total cells to the total column in the players card
// We add them after adding the holes so that they all align correctly
var totalCell = $("<div id='grand" + p + "' class='grandTotal'></div>")
$("#rightcard").append(totalCell);
}
}
$("#leftcard").html(playercollection);
$("#rightcard").html(("<div><div class='totalTitle'>Total</div></div>") + holecollection);
function buildholes() {
// add 18 holes to the columns
for(var p = 1; p <= numplayers; p++ ){
for(var h = 1; h <= numholes; h++){
$("#column" + h).append("<div onkeyup='calculateScore(" + p + ")' id='player" + p + "hole" + h + "' class='holebox'></div>");
}
}
}
collectHoles();
}
function courseInformationCard(){
var infoRows = ['Gold', 'Blue', 'White', 'Red', 'Handicap', 'Par'];
var infoColumns = 18;
var columncollection = "";
var rowcollection = "";
// create column of player labels
for(var pl = 0; pl < infoRows.length; pl++ ){
rowcollection += "<div id='infoplayer" + pl + "' class='holebox titlebox'>" + infoRows[pl] + "</div>";
}
// create golf hole columns before you add holes to them.
for(var c = infoColumns; c >= 1; c-- ){
columncollection += "<div id='column" + c +"'><div class='holenumbertitle'>" + c + "</div></div>";
}
$("#leftInfoCard").html(rowcollection);
$("#rightInfoCard").html(columncollection);
// call the function that builds the holes into the columns
function collectHoles() {
var p;
var h;
for(p = 1; p <= infoRows.length; p++) {
for(h = 1; h <= 18; h++) {
var teeId = infoRows[h] + "Hole" + h;
var hole = '<div id="holeInputs"><div id = "' + teeId + '" class="holeBox">' + h + '</div></div>';
$("#rightInfoCard").append(hole);
}
}
}
function buildholes() {
// add 18 holes to the columns
for(var p = 1; p <= numplayers; p++ ){
for(var h = 1; h <= numholes; h++){
$("#column" + h).append("<div id='player" + p + "hole" + h + "' class='holebox'></div>");
}
}
}
collectHoles();
buildholes();
}
function calculateScore(thePlayer) {
var theTotal = 0;
for(var t = 1;t <= numholes; t++) {
var playerId = "#player" + thePlayer + "Hole" + t;
theTotal += Number($(playerId).val());
}
$("#grand" + thePlayer).html(theTotal);
}
*/
|
include('harvestfestival:quests/templates/base_npc')
required_npc = 'harvest_goddess'
prereq = '0_axe'
function display (info) {
// Gather 24 logs to learn about blueprints
info.setIcon(createStack('minecraft:log 0'))
.setTitle('gather')
.setDescription('logs')
}
function onNPCChat (player, npc, tasks) {
if (player.has('logWood', 24)) {
tasks.add('say', 'thanks_for_wood')
.add('take_item', 'logWood', 24)
.add('give_item', settlements.blueprint('harvestfestival:carpenter'))
.add('say', 'explain_blueprints')
.add('unlock_note', 'harvestfestival:towns')
.add('unlock_note', 'harvestfestival:blueprints')
.add('set_team_status', 'request_carpenter', 1)
.add('complete_quest')
} else if (random(1, 5) == 1) {
tasks.add('say', 'remind_logs')
}
}
|
(function() {
'use strict';
angular.module('app.data').factory('repository.boxes', RepositoryBoxes);
RepositoryBoxes.$inject = ['$resource'];
function RepositoryBoxes($resource) {
var Boxes = $resource('/api/boxes/:id', { id: '@_id' }, {
update: { method: "PUT" },
findSensor: {
url: '/api/boxes/:boxId/sensor/:sensorId',
method: 'GET',
params: {
boxId: '@boxId',
sensorId: '@sensorId'
}
}
});
return {
getAll: getAll,
getSensor: getSensor
};
function getAll() {
return Boxes.query().$promise;
}
function getSensor(boxId, sensorId) {
return Boxes.findSensor({ boxId: boxId, sensorId: sensorId }).$promise;
}
}
})(); |
var rr = require('./introspection');
var RepositoryUtils = org.jboss.forge.addon.maven.projects.util.RepositoryUtils;
var MavenRepositorySystemUtils = org.apache.maven.repository.internal.MavenRepositorySystemUtils;
var DefaultRepositorySystemSession = org.eclipse.aether.DefaultRepositorySystemSession;
var LocalRepository = org.eclipse.aether.repository.LocalRepository;
var RemoteRepository = org.eclipse.aether.repository.RemoteRepository;
var DefaultArtifact = org.eclipse.aether.artifact.DefaultArtifact;
var LocalArtifactRequest = org.eclipse.aether.repository.LocalArtifactRequest;
var DefaultMetadata = org.eclipse.aether.metadata.DefaultMetadata;
var LocalMetadataRequest = org.eclipse.aether.repository.LocalMetadataRequest;
var File = java.io.File;
var VersionRangeRequest = org.eclipse.aether.resolution.VersionRangeRequest;
var ArtifactDescriptorRequest = org.eclipse.aether.resolution.ArtifactDescriptorRequest;
var defaultRepo =
new RemoteRepository.classes[0]( "central", "default", "http://central.maven.org/maven2/" ).build();
function getLocalArtifact( localRepoManager, repositorySession, artifact )
{
var request = new LocalArtifactRequest();
request.setArtifact( artifact );
var result = localRepoManager.find(repositorySession, request);
return result;
}
function getArtifactDescriptor( repositorySession, artifact )
{
var request = new ArtifactDescriptorRequest();
request.setArtifact( artifact );
var result = command.
container.
repositorySystem.
readArtifactDescriptor(repositorySession, request);
return result;
}
function getMetadata() {
/*
rr.printM( "localRepoManager", localRepoManager );
rr.printC( org.eclipse.aether.metadata.Metadata );
var request = new LocalMetadataRequest();
var metadata = new DefaultMetadata("org.robovm",
"robovm-objc",
RELEASE_OR_SNAPSHOT);
request.setMetadata( metadata );
var result = localRepoManager.find(repositorySession, request);
print( result );
*/
}
try {
rr.printC( "MavenRepositorySystemUtils", MavenRepositorySystemUtils );
rr.printC( "RepositoryUtils", RepositoryUtils );
rr.printM( "command", command.container.repositorySystem );
var settings = command.container.getSettings();
rr.printC( "settings", settings );
//var localRepo = RepositoryUtils.toArtifactRepository("local",
// new File(settings.localRepository).toURI().toURL().toString(), null, true, true);
var localRepo = new LocalRepository(settings.localRepository);
rr.printC( "localRepo", localRepo );
var repositorySession = MavenRepositorySystemUtils.newSession();
var localRepoManager = command.
container.
repositorySystem.
newLocalRepositoryManager(repositorySession, localRepo);
repositorySession.setLocalRepositoryManager( localRepoManager );
{
var artifact = new DefaultArtifact("org.robovm", "robovm-dist", "", "[0,)");
var repositories = new java.util.ArrayList();
repositories.add( defaultRepo );
var request = new VersionRangeRequest();
request.setArtifact( artifact ) ;
request.setRepositories( repositories );
var result = command.
container.
repositorySystem.
resolveVersionRange(repositorySession,request );
result.versions.forEach( function( e,i ) {
print(e);
var a = new DefaultArtifact(artifact.getGroupId(),
artifact.getArtifactId(),
"nocompiler", "tar.gz", e.toString());
var aa = getLocalArtifact( localRepoManager, repositorySession, a );
print( aa );
});
}
"END";
}
catch( e ) {
e.printStackTrace();
print( "ERROR " + e);
}
|
/**
* Lo-Dash 2.3.0 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="node" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
var arrayPool = require('./arrayPool'),
maxPoolSize = require('./maxPoolSize');
/**
* Releases the given array back to the array pool.
*
* @private
* @param {Array} [array] The array to release.
*/
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < maxPoolSize) {
arrayPool.push(array);
}
}
module.exports = releaseArray;
|
'use strict';
/**
* @ngdoc function
* @name aidiApp.controller:AddcontrollerCtrl
* @description
* # AddcontrollerCtrl
* Controller of the aidiApp
*/
angular.module('aidiApp')
.controller('AddcontrollerCtrl', function ($scope, $http, $location, $routeParams, profileFactory, SERVER) {
if(!!$routeParams.linkDate){
profileFactory.api('getLinkFromDate', $routeParams.linkDate).then(function(result){
$scope.form = result.data;
})
}
else{
$scope.form = $routeParams;
}
$scope.processForm = function(){
//validation
if(!$scope.form.linkdate)
{$scope.form.linkdate = Date.now();}
//end validation
$http({
method : 'POST',
url : SERVER+'post.php',
data : $.param($scope.form), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data){
console.log(data);
$location.path("/profile");
})
}
$scope.dateTime = new Date().toLocaleString();
});
|
import AppDispatcher from '../dispatcher/AppDispatcher.js';
import Request from 'superagent';
class NameActions {
loadAllUnprotectedNames(accountId) {
Request
.get('http://localhost:8080/names/unprotected/account/' + accountId)
.withCredentials()
.end((error, response) => {
this.onLoad(response.body, 'RECIEVE_UNPROTECTED_NAMES')
})
}
loadAllProtectedNames(accountId) {
Request
.get('http://localhost:8080/names/protected/account/' + accountId)
.withCredentials()
.end((error, response) => {
this.onLoad(response.body, 'RECIEVE_PROTECTED_NAMES')
})
}
loadAllClients(accountId) {
Request
.get('http://localhost:8080/names/client/account/' + accountId)
.withCredentials()
.end((error, response) => {
this.onLoad(response.body, 'RECIEVE_CLIENTS')
});
}
onLoad(names, action) {
AppDispatcher.handleViewAction({
actionType: action,
data: names
});
}
}
let nameActions = new NameActions();
export default nameActions;
|
var Loader = require('./lib/loader');
exports.loader = function(orm) {
return new Loader(orm);
};
exports.load = function(orm) {
var args = Array.prototype.slice.call(arguments, 1);
var loader = new Loader(orm);
return loader.load.apply(loader, args);
};
exports.Loader = Loader; |
const request = require('request');
const config = require('../../config');
const telegram = require('../telegram');
const models = require('../models');
module.exports = {
poll() {
request('https://jotihunt.net/api/1.0/vossen', (error, response, body) => {
if (error) {
telegram.sendMessage('Debug', error);
}
try {
const data = JSON.parse(body).data;
const callback = (result) => {
// Loop body.data
data.map((subareaStatus) => {
result.map((oldSubareaStatus) => {
if (config.dbMappings.area[subareaStatus.team] === oldSubareaStatus.SubareaId) {
// Determine if status is different
if (config.dbMappings.status[subareaStatus.status] !== oldSubareaStatus.StatusId) {
// Send message
const message = `${config.telegram.status[subareaStatus.status]} ${subareaStatus.team} is op ${subareaStatus.status} gesprongen!`;
telegram.sendMessage(subareaStatus.team, message);
// Save entry to database.
models.SubareaStatus.build({
StatusId: config.dbMappings.status[subareaStatus.status],
SubareaId: config.dbMappings.area[subareaStatus.team],
}).save();
}
}
return 0;
});
return 0;
});
};
models.SubareaStatus.getLatest(callback);
} catch (e) {
}
});
},
};
|
const StreamParser = require('../../../src/token/stream-parser');
const WritableTrackingBuffer = require('../../../src/tracking-buffer/writable-tracking-buffer');
const assert = require('chai').assert;
describe('Env Change Token Parser', () => {
it('should write to database', async () => {
const oldDb = 'old';
const newDb = 'new';
const buffer = new WritableTrackingBuffer(50, 'ucs2');
buffer.writeUInt8(0xe3);
buffer.writeUInt16LE(0); // Length written later
buffer.writeUInt8(0x01); // Database
buffer.writeBVarchar(newDb);
buffer.writeBVarchar(oldDb);
const data = buffer.data;
data.writeUInt16LE(data.length - 3, 1);
const parser = StreamParser.parseTokens([data], {}, {});
const result = await parser.next();
assert.isFalse(result.done);
const token = result.value;
assert.strictEqual(token.type, 'DATABASE');
assert.strictEqual(token.oldValue, 'old');
assert.strictEqual(token.newValue, 'new');
});
it('should write with correct packet size', async () => {
const oldSize = '1024';
const newSize = '2048';
const buffer = new WritableTrackingBuffer(50, 'ucs2');
buffer.writeUInt8(0xe3);
buffer.writeUInt16LE(0); // Length written later
buffer.writeUInt8(0x04); // Packet size
buffer.writeBVarchar(newSize);
buffer.writeBVarchar(oldSize);
const data = buffer.data;
data.writeUInt16LE(data.length - 3, 1);
const parser = StreamParser.parseTokens([data], {}, {});
const result = await parser.next();
assert.isFalse(result.done);
const token = result.value;
assert.strictEqual(token.type, 'PACKET_SIZE');
assert.strictEqual(token.oldValue, 1024);
assert.strictEqual(token.newValue, 2048);
});
it('should be of bad type', async () => {
const buffer = new WritableTrackingBuffer(50, 'ucs2');
buffer.writeUInt8(0xe3);
buffer.writeUInt16LE(0); // Length written later
buffer.writeUInt8(0xff); // Bad type
const data = buffer.data;
data.writeUInt16LE(data.length - 3, 1);
const parser = StreamParser.parseTokens([data], {}, {});
const result = await parser.next();
assert.isTrue(result.done);
});
});
|
let path = require('path');
let APP_DIR = path.resolve(__dirname, 'src');
let BUILD_DIR = path.resolve(__dirname, 'public');
let config = {
entry: [
APP_DIR + '/js/index.js'
],
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: APP_DIR,
use: [{
loader: 'babel-loader',
options: { presets: [ 'es2015', 'react', 'stage-2' ]},
}],
},
]
},
plugins: [ ],
devServer: {
historyApiFallback: true
}
};
module.exports = config;
|
var speed = 0.1;
var maxSpeed = 2;
var Particle = function(inPosition, inRadius, inMouseRadius) {
this.position = inPosition;
this.velocity = createVector(random(-1, 1), random(-1, -1));
this.radius = inRadius;
this.mouseRadius = inMouseRadius;
}
Particle.prototype.update = function(inParticles, index) {
// Map the position to be from 0 to 255
var h = map(this.position.x, 0, height, 0, 255);
// Make the particle move
this.position.add(this.velocity);
// when the particle goes out of bounds
if(this.position.x < -10) this.position.x = width;
if(this.position.x > width + 10) this.position.x = 0;
if(this.position.y < -10) this.position.y = height;
if(this.position.y > height + 10) this.position.y = 0;
// constrain the speed
this.velocity.x = constrain(this.velocity.x + random(-speed, speed), -maxSpeed, maxSpeed);
this.velocity.y = constrain(this.velocity.y + random(-speed, speed), -maxSpeed, maxSpeed);
for(var j = index + 1; j < inParticles.length; ++j) {
var angle = atan2(this.position.y - inParticles[j].position.y, this.position.x - inParticles[j].position.x);
var dist = this.position.dist(inParticles[j].position);
if(dist < this.radius) {
stroke(h, 255, map(dist, 0, this.radius, 255, 0));
strokeWeight(map(dist, 0, this.radius, 2, 0));
line(this.position.x, this.position.y, inParticles[j].position.x, inParticles[j].position.y);
var force = map(dist, 0, this.radius, 5, 0);
this.velocity.x += force * cos(angle);
this.velocity.y += force * sin(angle);
}
}
var angle = atan2(this.position.y - mouseY, this.position.x - mouseX);
var dist = this.position.dist(createVector(mouseX, mouseY));
if(dist < this.radius) {
var force = map(dist, 0, this.radius, 50, 0);
this.velocity.x += force * cos(angle);
this.velocity.y += force * sin(angle);
}
noStroke();
fill(h, 255, 255);
ellipse(mouseX, mouseY, 30, 30);
ellipse(this.position.x, this.position.y, random(5), random(5));
}
|
(function(angular) {
'use strict';
angular
.module('app.viewer')
.controller('viewer.IndexController', controller);
controller.$inject = [
'pattern.Factory',
'$stateParams'
];
function controller(pattern, $stateParams) {
/* jshint validthis: true */
var vm = this;
vm.patterns = pattern.sorted();
}
})(angular);
|
var _App = function(){};
App = new _App(); |
import React from 'react';
import PropTypes from 'prop-types';
import { Provider } from 'react-redux';
import routes from '../routes';
import { Router } from 'react-router';
export default class Root extends React.Component {
render() {
const { store, history } = this.props;
return (
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}; |
import { server as BroccoliServer, Watcher } from 'broccoli';
import program from 'commander';
import createBuilder from '../build-tree';
import getProject from './common';
import onBuild from '../hooks';
import Console from '../console';
program
.command('serve')
.description('starts building server that watches src file changes')
.option('-p, --port <port>', 'http serve port', 3000)
.action(({ port }) => {
const project = getProject();
const builder = createBuilder(project);
const watcher = new Watcher(builder);
watcher.on('buildSuccess', () => onBuild(builder, project));
watcher.on('buildFailure', e => Console.error(e));
BroccoliServer.serve(watcher, 'localhost', Number(port));
});
|
var db = require('../config/mongo_database');
var jwt = require('jsonwebtoken');
var secret = require('../config/secret');
var redisClient = require('../config/redis_database').redisClient;
var tokenManager = require('../config/token_manager');
exports.signin = function(req, res) {
var username = req.body.username || '';
var password = req.body.password || '';
if (username == '' || password == '') {
return res.send(401);
}
db.userModel.findOne({username: username}, function (err, user) {
if (err) {
console.log(err);
return res.send(401);
}
if (user == undefined) {
return res.send(401);
}
user.comparePassword(password, function(isMatch) {
if (!isMatch) {
console.log("Attempt failed to login with " + user.username);
return res.send(401);
}
var token = jwt.sign({id: user._id}, secret.secretToken, { expiresInMinutes: tokenManager.TOKEN_EXPIRATION });
return res.json({token:token, username, username});
});
});
};
exports.logout = function(req, res) {
if (req.user) {
tokenManager.expireToken(req.headers);
delete req.user;
return res.send(200);
}
else {
return res.send(401);
}
}
exports.register = function(req, res) {
var username = req.body.username || '';
var password = req.body.password || '';
var passwordConfirmation = req.body.passwordConfirmation || '';
if (username == '' || password == '' || password != passwordConfirmation) {
return res.send(400);
}
var user = new db.userModel();
user.username = username;
user.password = password;
user.save(function(err) {
if (err) {
console.log(err);
return res.send(500);
}
db.userModel.count(function(err, counter) {
if (err) {
console.log(err);
return res.send(500);
}
if (counter == 1) {
db.userModel.update({username:user.username}, {is_admin:true}, function(err, nbRow) {
if (err) {
console.log(err);
return res.send(500);
}
console.log('First user created as an Admin');
return res.send(200);
});
}
else {
return res.send(200);
}
});
});
} |
/* to reload chat commands:
>> for (var i in require.cache) delete require.cache[i];parseCommand = require('./chat-commands.js').parseCommand;''
*/
var crypto = require('crypto');
/**
* `parseCommand`. This is the function most of you are interested in,
* apparently.
*
* `message` is exactly what the user typed in.
* If the user typed in a command, `cmd` and `target` are the command (with "/"
* omitted) and command target. Otherwise, they're both the empty string.
*
* For instance, say a user types in "/foo":
* cmd === "/foo", target === "", message === "/foo bar baz"
*
* Or, say a user types in "/foo bar baz":
* cmd === "foo", target === "bar baz", message === "/foo bar baz"
*
* Or, say a user types in "!foo bar baz":
* cmd === "!foo", target === "bar baz", message === "!foo bar baz"
*
* Or, say a user types in "foo bar baz":
* cmd === "", target === "", message === "foo bar baz"
*
* `user` and `socket` are the user and socket that sent the message,
* and `room` is the room that sent the message.
*
* Deal with the message however you wish:
* return; will output the message normally: "user: message"
* return false; will supress the message output.
* returning a string will replace the message with that string,
* then output it normally.
*
*/
var modlog = modlog || fs.createWriteStream('logs/modlog.txt', {flags:'a+'});
var updateServerLock = false;
var poofeh = true;
var tourActive = false;
var tourSigyn = false;
var tourBracket = [];
var tourSignup = [];
var tourTier = '';
var tourRound = 0;
var tourSize = 0;
var tourMoveOn = [];
var tourRoundSize = 0;
var tourTierList = ['OU','UU','RU','NU','Random Battle','Ubers','Tier Shift','Challenge Cup 1-vs-1','Hackmons','Balanced Hackmons','LC','Smogon Doubles','Doubles Random Battle','Doubles Challenge Cup','Glitchmons','Stat Swap','Project XY','Slowmons','Suicide Cup'];
var tourTierString = '';
for (var i = 0; i < tourTierList.length; i++) {
if ((tourTierList.length - 1) > i) {
tourTierString = tourTierString + tourTierList[i] + ', ';
} else {
tourTierString = tourTierString + tourTierList[i];
}
}
function parseCommandLocal(user, cmd, target, room, socket, message) {
if (!room) return;
switch (cmd) {
case 'cmd':
var spaceIndex = target.indexOf(' ');
var cmd = target;
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex);
target = target.substr(spaceIndex+1);
} else {
target = '';
}
if (cmd === 'userdetails') {
if (!room) return false;
var targetUser = Users.get(target);
if (!targetUser) {
emit(socket, 'command', {
command: 'userdetails',
userid: toId(target),
rooms: false
});
return false;
}
var roomList = {};
for (var i in targetUser.roomCount) {
if (i==='global') continue;
var targetRoom = Rooms.get(i);
if (!targetRoom) continue;
var roomData = {};
if (targetRoom.battle) {
var battle = targetRoom.battle;
roomData.p1 = battle.p1?' '+battle.p1:'';
roomData.p2 = battle.p2?' '+battle.p2:'';
}
roomList[i] = roomData;
}
if (!targetUser.roomCount['global']) roomList = false;
var userdetails = {
command: 'userdetails',
userid: targetUser.userid,
avatar: targetUser.avatar,
rooms: roomList,
room: room.id
};
if (user.can('ip', targetUser)) {
var ips = Object.keys(targetUser.ips);
if (ips.length === 1) {
userdetails.ip = ips[0];
} else {
userdetails.ips = ips;
}
}
emit(socket, 'command', userdetails);
} else if (cmd === 'roomlist') {
emit(socket, 'command', {
command: 'roomlist',
rooms: Rooms.global.getRoomList(true),
room: 'lobby'
});
}
return false;
break;
//tour commands
case 'tour':
case 'starttour':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
if (tourActive || tourSigyn) {
emit(socket, 'console', 'There is already a tournament running, or there is one in a signup phase.');
return false;
}
if (!target) {
emit(socket, 'console', 'Proper syntax for this command: /tour tier, size');
return false;
}
var targets = splittyDiddles(target);
var tierMatch = false;
var tempTourTier = '';
for (var i = 0; i < tourTierList.length; i++) {
if ((targets[0].trim().toLowerCase()) == tourTierList[i].trim().toLowerCase()) {
tierMatch = true;
tempTourTier = tourTierList[i];
}
}
if (!tierMatch) {
emit(socket, 'console', 'Please use one of the following tiers: ' + tourTierString);
return false;
}
targets[1] = parseInt(targets[1]);
if (isNaN(targets[1])) {
emit(socket, 'console', 'Proper syntax for this command: /tour tier, size');
return false;
}
if (targets[1] < 3) {
emit(socket, 'console', 'Tournaments must contain 3 or more people.');
return false;
}
tourTier = tempTourTier;
tourSize = targets[1];
tourSigyn = true;
tourSignup = [];
room.addRaw('<h2><font color="green">' + sanitize(user.name) + ' has started a ' + tourTier + ' Tournament.</font> <font color="red">/j</font> <font color="green">to join!</font></h2><b><font color="blueviolet">PLAYERS:</font></b> ' + tourSize + '<br /><font color="blue"><b>TIER:</b></font> ' + tourTier + '<hr />');
return false;
break;
/*
case 'winners':
emit(socket, 'console', tourMoveOn + ' --- ' + tourBracket);
return false;
break;
*/
case 'toursize':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
if (!tourSigyn) {
emit(socket, 'console', 'The tournament size cannot be changed now!');
return false;
}
if (!target) {
emit(socket, 'console', 'Proper syntax for this command: /toursize, size');
return false;
}
target = parseInt(target);
if (isNaN(target)) {
emit(socket, 'console', 'Proper syntax for this command: /tour tier, size');
return false;
}
if (target < 4) {
emit(socket, 'console', 'A tournament must have at least 4 people in it.');
return false;
}
if (target < tourSignup.length) {
emit(socket, 'console', 'You can\'t boot people from a tournament like this.');
return false;
}
tourSize = target;
room.addRaw('<b>' + user.name + '</b> has changed the tournament size to: '+ tourSize +'. <b><i>' + (tourSize - tourSignup.length) + ' slots remaining.</b></i>');
if(tourSize == tourSignup.length) {
beginTour();
}
return false;
break;
case 'jointour':
case 'jt':
case 'j':
if ((!tourSigyn) || tourActive) {
emit(socket, 'console', 'There is already a tournament running, or there is not any tournament to join.');
return false;
}
var tourGuy = user.userid;
if (addToTour(tourGuy)) {
room.addRaw('<b>' + user.name + '</b> has joined the tournament. <b><i>' + (tourSize - tourSignup.length) + ' slots remaining.</b></i>');
if(tourSize == tourSignup.length) {
beginTour();
}
} else {
emit(socket, 'console', 'You could not enter the tournament. You may already be in the tournament Type /lt if you want to leave the tournament.');
}
return false;
break;
case 'leavetour':
case 'lt':
if ((!tourSigyn) && (!tourActive)) {
emit(socket, 'console', 'There is no tournament to leave.');
return false;
}
var spotRemover = false;
if (tourSigyn) {
for(var i=0;i<tourSignup.length;i++) {
//emit(socket, 'console', tourSignup[1]);
if (user.userid === tourSignup[i]) {
tourSignup.splice(i,1);
spotRemover = true;
}
}
if (spotRemover) {
Room.addRaw('<b>' + user.name + '</b> has left the tournament. <b><i>' + (tourSize - tourSignup.length) + ' slots remaining.</b></i>');
}
} else if (tourActive) {
var tourBrackCur;
var tourDefWin;
for(var i=0;i<tourBracket.length;i++) {
tourBrackCur = tourBracket[i];
if (tourBrackCur[0] == user.userid) {
tourDefWin = Users.get(tourBrackCur[1]);
if (tourDefWin) {
spotRemover = true;
tourDefWin.tourRole = 'winner';
tourDefWin.tourOpp = '';
user.tourRole = '';
user.tourOpp = '';
}
}
if (tourBrackCur[1] == user.userid) {
tourDefWin = Users.get(tourBrackCur[0]);
if (tourDefWin) {
spotRemover = true;
tourDefWin.tourRole = 'winner';
tourDefWin.tourOpp = '';
user.tourRole = '';
user.tourOpp = '';
}
}
}
if (spotRemover) {
Room.addRaw('<b>' + user.name + '</b> has left the tournament. <b><i>');
}
}
if (!spotRemover) {
emit(socket, 'console', 'You cannot leave this tournament. Either you did not enter the tournament, or your opponent is unavailable.');
}
return false;
break;
case 'forceleave':
case 'fl':
case 'flt':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
if (!tourSigyn) {
emit(socket, 'console', 'There is no tournament in a sign-up phase. Use /dq username if you wish to remove someone in an active tournament.');
return false;
}
if (!target) {
emit(socket, 'console', 'Please specify a user to kick from this signup.');
return false;
}
var targetUser = Users.get(target);
if (targetUser){
target = targetUser.userid;
}
var spotRemover = false;
for(var i=0;i<tourSignup.length;i++) {
//emit(socket, 'console', tourSignup[1]);
if (target === tourSignup[i]) {
tourSignup.splice(i,1);
spotRemover = true;
}
}
if (spotRemover) {
room.addRaw('The user <b>' + target + '</b> has left the tournament by force. <b><i>' + (tourSize - tourSignup.length) + ' slots remaining.</b></i>');
} else {
emit(socket, 'console', 'The user that you specified is not in the tournament.');
}
return false;
break;
case 'vr':
case 'viewround':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
if (!tourActive) {
emit(socket, 'console', 'There is no active tournament running.');
return false;
}
if (tourRound == 1) {
Rooms.lobby.addRaw('<hr /><h3><font color="green">The ' + tourTier + ' tournament has begun!</font></h3><font color="blue"><b>TIER:</b></font> ' + tourTier );
} else {
Rooms.lobby.addRaw('<hr /><h3><font color="green">Round '+ tourRound +'!</font></h3><font color="blue"><b>TIER:</b></font> ' + tourTier );
}
var tourBrackCur;
for(var i = 0;i < tourBracket.length;i++) {
tourBrackCur = tourBracket[i];
if (!(tourBrackCur[0] === 'bye') && !(tourBrackCur[1] === 'bye')) {
Rooms.lobby.addRaw(' - ' + getTourColor(tourBrackCur[0]) + ' VS ' + getTourColor(tourBrackCur[1]));
} else if (tourBrackCur[0] === 'bye') {
Rooms.lobby.addRaw(' - ' + tourBrackCur[1] + ' has recieved a bye!');
} else if (tourBrackCur[1] === 'bye') {
Rooms.lobby.addRaw(' - ' + tourBrackCur[0] + ' has recieved a bye!');
} else {
Rooms.lobby.addRaw(' - ' + tourBrackCur[0] + ' VS ' + tourBrackCur[1]);
}
}
var tourfinalcheck = tourBracket[0];
if ((tourBracket.length == 1) && (!(tourfinalcheck[0] === 'bye') || !(tourfinalcheck[1] === 'bye'))) {
Rooms.lobby.addRaw('This match is the finals! Good luck!');
}
Rooms.lobby.addRaw('<hr />');
return false;
break;
case 'remind':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
if (!tourSigyn) {
emit(socket, 'console', 'There is no tournament to sign up for.');
return false;
}
room.addRaw('<hr /><h2><font color="green">Please sign up for the ' + tourTier + ' Tournament.</font> <font color="red">/j</font> <font color="green">to join!</font></h2><b><font color="blueviolet">PLAYERS:</font></b> ' + tourSize + '<br /><font color="blue"><b>TIER:</b></font> ' + tourTier + '<hr />');
return false;
break;
case 'replace':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
if (!tourActive) {
emit(socket, 'console', 'The tournament is currently in a sign-up phase or is not active, and replacing users only works mid-tournament.');
return false;
}
if (!target) {
emit(socket, 'console', 'Proper syntax for this command is: /replace user1, user2. User 2 will replace User 1 in the current tournament.');
return false;
}
var targets = splittyDiddles(target);
if (!targets[1]) {
emit(socket, 'console', 'Proper syntax for this command is: /replace user1, user2. User 2 will replace User 1 in the current tournament.');
return false;
}
var userOne = Users.get(targets[0]);
var userTwo = Users.get(targets[1]);
if (!userTwo) {
emit(socket, 'console', 'Proper syntax for this command is: /replace user1, user2. The user you specified to be placed in the tournament is not present!');
return false;
} else {
targets[1] = userTwo.userid;
}
if (userOne) {
targets[0] = userOne.userid;
}
var tourBrackCur = [];
var replaceSuccess = false;
//emit(socket, 'console', targets[0] + ' - ' + targets[1]);
for (var i = 0; i < tourBracket.length; i++) {
tourBrackCur = tourBracket[i];
if (tourBrackCur[0] === targets[0]) {
tourBrackCur[0] = targets[1];
userTwo.tourRole = 'participant';
userTwo.tourOpp = tourBrackCur[1];
var oppGuy = Users.get(tourBrackCur[1]);
if (oppGuy) {
if (oppGuy.tourOpp === targets[0]) {
oppGuy.tourOpp = targets[1];
}
}
replaceSuccess = true;
}
if (tourBrackCur[1] === targets[0]) {
tourBrackCur[1] = targets[1];
userTwo.tourRole = 'participant';
userTwo.tourOpp = tourBrackCur[0];
var oppGuy = Users.get(tourBrackCur[0]);
if (oppGuy) {
if (oppGuy.tourOpp === targets[0]) {
oppGuy.tourOpp = targets[1];
}
}
replaceSuccess = true;
}
if (tourMoveOn[i] === targets[0]) {
tourMoveOn[i] = targets[1];
userTwo.tourRole = 'winner';
userTwo.tourOpp = '';
} else if (!(tourMoveOn[i] === '')) {
userTwo.tourRole = '';
userTwo.tourOpp = '';
}
}
if (replaceSuccess) {
room.addRaw('<b>' + targets[0] +'</b> has left the tournament and is replaced by <b>' + targets[1] + '</b>.');
} else {
emit(socket, 'console', 'The user you indicated is not in the tournament!');
}
return false;
break;
case 'endtour':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
tourActive = false;
tourSigyn = false;
tourBracket = [];
tourSignup = [];
tourTier = '';
tourRound = 0;
tourSize = 0;
tourMoveOn = [];
tourRoundSize = 0;
room.addRaw('<h2><b>' + user.name + '</b> has ended the tournament.</h2>');
return false;
break;
case 'dq':
case 'disqualify':
if (!user.can('broadcast')) {
emit(socket, 'console', 'You do not have enough authority to use this command.');
return false;
}
if (!target) {
emit(socket, 'console', 'Proper syntax for this command is: /dq username');
return false;
}
if (!tourActive) {
emit(socket, 'console', 'There is no tournament running at this time!');
return false;
}
var targetUser = Users.get(target);
if (!targetUser) {
var dqGuy = sanitize(target.toLowerCase());
var tourBrackCur;
var posCheck = false;
for(var i = 0;i < tourBracket.length;i++) {
tourBrackCur = tourBracket[i];
if (tourBrackCur[0] === dqGuy) {
var finalGuy = Users.get(tourBrackCur[1]);
finalGuy.tourRole = 'winner';
finalGuy.tourOpp = '';
//targetUser.tourRole = '';
posCheck = true;
}
if (tourBrackCur[1] === dqGuy) {
var finalGuy = Users.get(tourBrackCur[0]);
finalGuy.tourRole = 'winner';
finalGuy.tourOpp = '';
//targetUser.tourRole = '';
posCheck = true;
}
}
if (posCheck) {
room.addRaw('<b>' + dqGuy + '</b> has been disqualified.');
} else {
emit(socket, 'console', 'That user was not in the tournament!');
}
return false;
} else {
var dqGuy = targetUser.userid;
var tourBrackCur;
var posCheck = false;
for(var i = 0;i < tourBracket.length;i++) {
tourBrackCur = tourBracket[i];
if (tourBrackCur[0] === dqGuy) {
var finalGuy = Users.get(tourBrackCur[1]);
finalGuy.tourRole = 'winner';
targetUser.tourRole = '';
posCheck = true;
}
if (tourBrackCur[1] === dqGuy) {
var finalGuy = Users.get(tourBrackCur[0]);
finalGuy.tourRole = 'winner';
targetUser.tourRole = '';
posCheck = true;
}
}
if (posCheck) {
room.addRaw('<b>' + targetUser.name + '</b> has been disqualified.');
} else {
emit(socket, 'console', 'That user was not in the tournament!');
}
return false;
}
break;
//tour commands end
case '!league':
case '!lunaraleaue':
case 'league':
case 'lunaraleague':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"> Information on Dream University\'s own <i>Lunara League</i>. (Leader Name/Gym #/Type/Tier):<br />' +
'- <a href"="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=9" target="_blank">iSmogoon/TheSilverShadow (Dark-type, 8th)</a><br />' +
'- <a href="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=16" target="_blank">EnerG218 (Psychic, RU, 7th)</a><br />' +
'- <a href="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=10" target="_blank">AOrtega (Fighting, CAP, 6th)</a><br />' +
'- <a href="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=12" target="_blank">SmashBrosBrawl (Steel, OU, 5th)</a><br />' +
'- <a href="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=11" target="_blank">Piiiikachuuu (Fire, OU, 4th)</a><br />' +
'- <a href="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=17" target="_blank">Aikenka (3rd, Electric, NU)</a><br />' +
'- <a href="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=13" target="_blank">Miner0 (Ground, OU, 2nd)</a><br />' +
'- <a href="http://fantasy-lab.no-ip.org/forums/showthread.php?tid=1" target="_blank">Professor Xerilia (Flying, UU, 1st)</a>' +
'</div>');
return false;
case '!miner0':
case '!miner':
case 'miner0':
case 'miner':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader Miner:</b><br />' +
'Type: Ground<br />' +
'Tier: Over Used (OU)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=13" target="_blank">Thread</a><br />' +
'Signature Pokemon: Hippowdon<br />' +
'<img src="http://pldh.net/media/pokecons_action/450.gif"><br />' +
'Badge: Mine Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/th_037_zps7830eeed.png">' +
'</div>');
return false;
break;
case 'xerilia':
case '!xerilia':
case 'professorxerilia':
case '!professorxerilia':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader Xerilia:</b><br />' +
'Type: Flying<br />' +
'Tier: Under Used (UU)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=15" target="_blank">Thread</a><br />' +
'Signature Pokemon: Tornadus<br />' +
'<img src="http://www.poke-amph.com/black-white/sprites/small/641.png"><br />' +
'Badge: Skylight Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/148_zpsc03fd480.png">' +
'</div>');
return false;
break;
case 'aikenka':
case '!aikenka':
case 'aik':
case '!aik':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader Aikenka:</b><br />' +
'Type: Electric<br />' +
'Tier: Never Used (NU)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=17" target="_blank">Thread</a><br />' +
'Signature Pokemon: Raichu<br />' +
'<img src="http://www.poke-amph.com/black-white/sprites/small/026.png"><br />' +
'Badge: Fission Storm Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/021_zpsc579bcbb.png">' +
'</div>');
return false;
break;
case 'piiiikachuuu':
case '!piiiikachuuu':
case 'pika':
case '!pika':
case 'chuu':
case '!chuu':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader Piiiikachuuu:</b><br />' +
'Type: Fire<br />' +
'Tier: Over Used (OU)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=11" target="_blank">Thread</a><br />' +
'Signature Pokemon: Ninetales<br />' +
'<img src="http://www.poke-amph.com/black-white/sprites/small/038.png"><br />' +
'Badge: Fire Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/038_zpsc9f8c94e.png">' +
'</div>');
return false;
break;
case 'smashbrosrawl':
case '!smashbrosbrawl':
case 'smash':
case '!smash':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader SmashBrosBrawl:</b><br />' +
'Type: Steel<br />' +
'Tier: Over Used (OU)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=12" target="_blank">Thread</a><br />' +
'Signature Pokemon: Lucario<br />' +
'<img src="http://www.poke-amph.com/black-white/sprites/small/448.png"><br />' +
'Badge: Steel Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/065_zpsd830d811.png">' +
'</div>');
return false;
break;
case 'forums':
case '!forums':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Our forums created by the wonderful jd</b><br />' +
'<a href="http://fantasy-lab.no-ip.org/forums/" target="_blank">Forums</a><br />' +
'</div>');
return false;
break;
case 'statswap':
case '!statswap':
case 'sswap':
case '!sswap':
case 'ss':
case '!ss':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Stat Swap created by Oiawesome:</b><br />' +
'- Stat Swap is a meta where stats get swapped:<br />' +
'- Attack and Special Attack are swapped.<br />' +
'- Defense and Special Defense are swapped.<br />' +
'- HP and Speed are swapped.<br />' +
'- Credits to: Oiawesome (creator) and Nollan101 (programmer)<br />'+'</div>');
return false;
break;
case 'projectxy':
case '!projectxy':
case 'pxy':
case '!pxy':
case 'xy':
case '!xy':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Project XY created by iSmogoon:</b><br />' +
'- <a href="https://docs.google.com/document/d/1QQDd0pC7MgbyE2kWhQbxnIhkhId6pcxco5JLQ2QGwPA/edit" target="_blank">Pokemon Changes</a><br />' +
'- <a href="https://docs.google.com/document/d/1qgzJREJEAhqpLrEwN-Hg7zFgy_a1PSWH_cAMoFab86c/edit" target="_blank">Move Changes</a><br />' +
'- <a href="https://docs.google.com/document/d/1R2ZkL4N0_A4cqNEjyWjgaSR5xQ4r_YPvSLg0YsNxxoY/edit" target="_blank">Ability Changes</a><br />' +
'- <a href="" target="_blank">Item Changes</a><br />' +
'- <a href="https://docs.google.com/document/d/1pRCIeb0O5KnAfbIZDYr2LoeIbYMliV714nlrdaP4zaA/edit" target="_blank">Misc. Changes</a><br />'+'</div>');
return false;
break;
case 'css':
case '!css':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Want to have your background featured on <i>Dream University</i>?</b><br />' +
'- <a href="http://wpeye.net/skitty_bg/skitty.css" target="_blank">Example by Orivexes.</a><br />' +
'- <a href="http://pastebin.com/raw.php?i=jeaA0GQF" target="_blank">Current Background by iSmogoon <i>(Cherrim-Sunny)</a><br />' +
'- Message us the file and we\'ll try to add it!</div>');
return false;
break;
case 'aortega':
case '!aortega':
case 'ao':
case '!ao':
case 'asshole':
case '!asshole':
case 'bitchman':
case '!batman':
case 'stripper':
case '!stripper':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader AOrtega aka Batman:</b><br />' +
'Type: Fighting<br />' +
'Tier: Create-A-Pokemon (CAP)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=10" target="_blank">Thread</a><br />' +
'Signature Pokemon: Tomohawk<br />' +
'<img src="http://50.112.63.201/forums/uploads/avatars/avatar_9.png?dateline=1366934006"><br />' +
'Badge: Kombat Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/006_zps6f18aed3.png">' +
'</div>');
return false;
break;
case 'energ218':
case '!EnerG218':
case 'energ':
case '!energ':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader EnerG218:</b><br />' +
'Type: Psychic<br />' +
'Tier: Rarely Used (RU)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=16" target="_blank">Thread</a><br />' +
'Signature Pokemon: Medicham<br />' +
'<img src="http://www.poke-amph.com/black-white/sprites/small/308.png"><br />' +
'Badge: Force Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/150_zpsd6a4d03e.png">' +
'</div>');
return false;
break;
case 'smogoon':
case '!smogoon':
case 'goon':
case '!goon':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox"><b>Information on Gym Leader iSmogoon:</b><br />' +
'Type: Dark<br />' +
'Tier: Under Used and Over Used (UU and OU)<br />' +
'<a href="http://50.112.63.201/forums/showthread.php?tid=9">Thread</a><br />' +
'Signature Pokemon: Weavile<br />' +
'<img src="http://www.poke-amph.com/black-white/sprites/small/461.png"><br />' +
'Badge: Shadow Badge<br />' +
'<img src="http://i1305.photobucket.com/albums/s542/TheBattleTowerPS/112_zps58abb527.png">' +
'</div>');
return false;
break;
case 'me':
case 'mee':
if (canTalk(user, room)) {
if (config.chatfilter) {
var suffix = config.chatfilter(user, room, socket, target);
if (suffix === false) return false;
return '/' + cmd + ' ' + suffix;
}
return true;
}
break;
case '!kupo':
case 'kupo':
if (canTalk(user, room) && user.can('broadcast') && room.id === 'lobby') {
if (cmd === '!kupo') {
room.add('|c|'+user.getIdentity()+'|!kupo '+target, true);
}
logModCommand(room, user.name + ' has used /kupo to say ' + target, true);
room.add('|c| kupo|/me '+target, true);
return false;
}
case 'smogoonimp':
case 'goonimp':
if (canTalk(user, room) && user.can('broadcast') && room.id === 'lobby') {
logModCommand(room, user.name + ' has used /goon to say ' + target, true);
room.add('|c| iSmogoon|/me '+target, true);
return false;
}
break;
case 'forfeit':
case 'concede':
case 'surrender':
if (!room.battle) {
emit(socket, 'console', "There's nothing to forfeit here.");
return false;
}
if (!room.forfeit(user)) {
emit(socket, 'console', "You can't forfeit this battle.");
}
return false;
break;
case 'register':
emit(socket, 'console', 'You must win a rated battle to register.');
return false;
break;
case 'avatar':
if (!target) return parseCommand(user, 'avatars', '', room, socket);
var parts = target.split(',');
var avatar = parseInt(parts[0]);
if (!avatar || avatar > 294 || avatar < 1) {
if (!parts[1]) {
emit(socket, 'console', 'Invalid avatar.');
}
return false;
}
user.avatar = avatar;
if (!parts[1]) {
emit(socket, 'console', 'Avatar changed to:');
emit(socket, 'console', {rawMessage: '<img src="//play.pokemonshowdown.com/sprites/trainers/'+avatar+'.png" alt="" width="80" height="80" />'});
}
return false;
break;
case 'whois':
case 'ip':
case 'getip':
case 'rooms':
case 'altcheck':
case 'alt':
case 'alts':
case 'getalts':
var targetUser = user;
if (target) {
targetUser = Users.get(target);
}
if (!targetUser) {
emit(socket, 'console', 'User '+target+' not found.');
} else {
emit(socket, 'console', 'User: '+targetUser.name);
if (user.can('alts', targetUser.getHighestRankedAlt())) {
var alts = targetUser.getAlts();
var output = '';
for (var i in targetUser.prevNames) {
if (output) output += ", ";
output += targetUser.prevNames[i];
}
if (output) emit(socket, 'console', 'Previous names: '+output);
for (var j=0; j<alts.length; j++) {
var targetAlt = Users.get(alts[j]);
if (!targetAlt.named && !targetAlt.connected) continue;
emit(socket, 'console', 'Alt: '+targetAlt.name);
output = '';
for (var i in targetAlt.prevNames) {
if (output) output += ", ";
output += targetAlt.prevNames[i];
}
if (output) emit(socket, 'console', 'Previous names: '+output);
}
}
if (config.groups[targetUser.group] && config.groups[targetUser.group].name) {
emit(socket, 'console', 'Group: ' + config.groups[targetUser.group].name + ' (' + targetUser.group + ')');
}
if (!targetUser.authenticated) {
emit(socket, 'console', '(Unregistered)');
}
if (user.can('ip', targetUser)) {
var ips = Object.keys(targetUser.ips);
emit(socket, 'console', 'IP' + ((ips.length > 1) ? 's' : '') + ': ' + ips.join(', '));
}
var output = 'In rooms: ';
var first = true;
for (var i in targetUser.roomCount) {
if (i === 'global') continue;
if (!first) output += ' | ';
first = false;
output += '<a href="/'+i+'" room="'+i+'">'+i+'</a>';
}
emit(socket, 'console', {rawMessage: output});
}
return false;
break;
case 'boom':
case 'ban':
case 'b':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('ban', targetUser)) {
emit(socket, 'console', '/boom - No Explosives left.');
return false;
}
logModCommand(room,""+targetUser.name+" was exploded into oblivion by "+user.name+"." + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.emit('message', user.name+' has banned you. If you feel that your banning was unjustified you can <a href="http://www.smogon.com/forums/announcement.php?f=126&a=204" target="_blank">appeal the ban</a>. '+targets[1]);
var alts = targetUser.getAlts();
if (alts.length) logModCommand(room,""+targetUser.name+"'s alts were also exploded: "+alts.join(", "));
targetUser.ban();
return false;
break;
case 'kick':
case 'warn':
case 'k':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser || !targetUser.connected) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('warn', targetUser)) {
emit(socket, 'console', '/warn - Access denied.');
return false;
}
logModCommand(room,''+targetUser.name+' was warned by '+user.name+'' + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.sendTo('lobby', '|c|~|/warn '+targets[1]);
return false;
break;
case 'dropkick':
case 'dk':
// TODO: /kick will be removed in due course.
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser || !targetUser.connected) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('redirect', targetUser)) {
emit(socket, 'console', '/redirect - Access denied.');
return false;
}
logModCommand(room,''+targetUser.name+' was dropkicked to the floor by '+user.name+'' + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.emit('console', {evalRulesRedirect: 1});
return false;
break;
case 'bitchslap':
case 'bs':
// TODO: /kick will be removed in due course.
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser || !targetUser.connected) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('redirect', targetUser)) {
emit(socket, 'console', '/redirect - The cake is a lie.');
return false;
}
logModCommand(room,''+targetUser.name+' was bitchslapped to death by '+user.name+'' + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.emit('console', {evalRulesRedirect: 1});
return false;
break;
case 'Troutslap':
case 'ts':
// TODO: /kick will be removed in due course.
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser || !targetUser.connected) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('redirect', targetUser)) {
emit(socket, 'console', '/redirect - The cake is a lie.');
return false;
}
logModCommand(room,''+targetUser.name+' was slapped around with a large trout by '+user.name+'' + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.emit('console', {evalRulesRedirect: 1});
return false;
break;
case 'lock':
case 'ipmute':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('lock', targetUser)) {
emit(socket, 'console', '/lock - Access denied.');
return false;
}
logModCommand(room,""+targetUser.name+" was locked from talking by "+user.name+"." + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.emit('message', user.name+' has locked you from talking in chats, battles, and PMing regular users.\n\n'+targets[1]+'\n\nIf you feel that your lock was unjustified, you can still PM staff members (@, &, and ~) to discuss it.');
var alts = targetUser.getAlts();
if (alts.length) logModCommand(room,""+targetUser.name+"'s alts were also locked: "+alts.join(", "));
targetUser.lock();
return false;
break;
case 'unlock':
if (!target) return parseCommand(user, '?', cmd, room, socket);
if (!user.can('lock')) {
emit(socket, 'console', '/unlock - Access denied.');
return false;
}
var unlocked = Users.unlock(target);
if (unlocked) {
var names = Object.keys(unlocked);
logModCommand(room, '' + names.join(', ') + ' ' +
((names.length > 1) ? 'were' : 'was') +
' unlocked by ' + user.name + '.');
} else {
emit(socket, 'console', 'User '+target+' is not locked.');
}
return false;
break;
case 'unban':
if (!target) return parseCommand(user, '?', cmd, room, socket);
if (!user.can('ban')) {
emit(socket, 'console', '/unban - Access denied.');
return false;
}
var name = Users.unban(target);
if (name) {
logModCommand(room,''+name+' was put back together by '+user.name+'.');
} else {
emit(socket, 'console', 'User '+target+' is not banned.');
}
return false;
break;
case 'unbanall':
if (!user.can('ban')) {
emit(socket, 'console', '/unbanall - Access denied.');
return false;
}
// we have to do this the hard way since it's no longer a global
for (var i in Users.bannedIps) {
delete Users.bannedIps[i];
}
for (var i in Users.lockedIps) {
delete Users.lockedIps[i];
}
logModCommand(room,'All bans and locks have been lifted by '+user.name+'.');
return false;
break;
case 'reply':
case 'r':
if (!target) return parseCommand(user, '?', cmd, room, socket);
if (!user.lastPM) {
emit(socket, 'console', 'No one has PMed you yet.');
return false;
}
return parseCommand(user, 'msg', ''+(user.lastPM||'')+', '+target, room, socket);
break;
case 'msg':
case 'pm':
case 'whisper':
case 'w':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targets[1]) {
emit(socket, 'console', 'You forgot the comma.');
return parseCommand(user, '?', cmd, room, socket);
}
if (!targets[0] || !targetUser.connected) {
if (target.indexOf(' ')) {
emit(socket, 'console', 'User '+targets[2]+' not found. Did you forget a comma?');
} else {
emit(socket, 'console', 'User '+targets[2]+' not found. Did you misspell their name?');
}
return parseCommand(user, '?', cmd, room, socket);
}
if (user.locked && !targetUser.can('lock', user)) {
emit(socket, 'console', 'You can only private message members of the moderation team (users marked by %, @, &, or ~) when locked.');
return false;
}
if (!user.named) {
emit(socket, 'console', 'You must choose a name before you can send private messages.');
return false;
}
var message = {
name: user.getIdentity(),
pm: targetUser.getIdentity(),
message: targets[1]
};
user.emit('console', message);
if (targets[0] !== user) targets[0].emit('console', message);
targets[0].lastPM = user.userid;
user.lastPM = targets[0].userid;
return false;
break;
case 'mute':
case 'm':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('mute', targetUser)) {
emit(socket, 'console', '/mute - Access denied.');
return false;
}
if (room.id !== 'lobby') {
emit(socket, 'console', 'Muting only applies to lobby - you probably wanted to /lock.');
return false;
}
logModCommand(room,''+targetUser.name+'\'s mouth was sewn shut by '+user.name+'.' + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.emit('message', user.name+' has muted you. '+targets[1]);
var alts = targetUser.getAlts();
if (alts.length) logModCommand(room,""+targetUser.name+"'s alts were also muted: "+alts.join(", "));
targetUser.mute(7*60*1000);
return false;
break;
case 'hourmute':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('mute', targetUser)) {
emit(socket, 'console', '/mute - Access denied.');
return false;
}
if (room.id !== 'lobby') {
emit(socket, 'console', 'Muting only applies to lobby - you probably wanted to /lock.');
return false;
}
if (targetUser.muted) {
logModCommand(room,''+targetUser.name+' was already muted; '+user.name+' was too late.' + (targets[1] ? " (" + targets[1] + ")" : ""));
return false;
}
logModCommand(room,''+targetUser.name+' was muted by '+user.name+' for 60 minutes.' + (targets[1] ? " (" + targets[1] + ")" : ""));
targetUser.emit('message', user.name+' has muted you for 60 minutes. '+targets[1]);
var alts = targetUser.getAlts();
if (alts.length) logModCommand(room,""+targetUser.name+"'s alts were also muted: "+alts.join(", "));
targetUser.mute(60*60*1000);
return false;
break;
case 'unmute':
case 'um':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targetid = toUserid(target);
var targetUser = Users.get(target);
if (!targetUser) {
emit(socket, 'console', 'User '+target+' not found.');
return false;
}
if (!user.can('mute', targetUser)) {
emit(socket, 'console', '/unmute - Access denied.');
return false;
}
targetUser.unmute();
logModCommand(room,''+targetUser.name+' was shown mercy by '+user.name+' and allowed to talk.');
return false;
break;
case 'promote':
case 'demote':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target, true);
var targetUser = targets[0];
var userid = toUserid(targets[2]);
var currentGroup = ' ';
if (targetUser) {
currentGroup = targetUser.group;
} else if (Users.usergroups[userid]) {
currentGroup = Users.usergroups[userid].substr(0,1);
}
var name = (targetUser ? targetUser.name : targets[2]);
var nextGroup = targets[1] ? targets[1] : Users.getNextGroupSymbol(currentGroup, cmd === 'demote');
if (targets[1] === 'deauth') nextGroup = config.groupsranking[0];
if (!config.groups[nextGroup]) {
emit(socket, 'console', 'Group \'' + nextGroup + '\' does not exist.');
return false;
}
if (!user.checkPromotePermission(currentGroup, nextGroup)) {
emit(socket, 'console', '/promote - Access denied.');
return false;
}
var isDemotion = (config.groups[nextGroup].rank < config.groups[currentGroup].rank);
if (!Users.setOfflineGroup(name, nextGroup)) {
emit(socket, 'console', '/promote - WARNING: This user is offline and could be unregistered. Use /forcepromote if you\'re sure you want to risk it.');
return false;
}
var groupName = (config.groups[nextGroup].name || nextGroup || '').trim() || 'a regular user';
var entry = ''+name+' was '+(isDemotion?'demoted':'promoted')+' to ' + groupName + ' by '+user.name+'.';
logModCommand(room, entry, isDemotion);
if (isDemotion) {
Rooms.lobby.logEntry(entry);
emit(socket, 'console', 'You demoted ' + name + ' to ' + groupName + '.');
if (targetUser) {
targetUser.emit('console', 'You were demoted to ' + groupName + ' by ' + user.name + '.');
}
}
targetUser.updateIdentity();
return false;
break;
case 'forcepromote':
// warning: never document this command in /help
if (!user.can('forcepromote')) {
emit(socket, 'console', '/forcepromote - Access denied.');
return false;
}
var targets = splitTarget(target, true);
var name = targets[2];
var nextGroup = targets[1] ? targets[1] : Users.getNextGroupSymbol(' ', false);
if (!Users.setOfflineGroup(name, nextGroup, true)) {
emit(socket, 'console', '/forcepromote - Don\'t forcepromote unless you have to.');
return false;
}
var groupName = config.groups[nextGroup].name || nextGroup || '';
logModCommand(room,''+name+' was promoted to ' + (groupName.trim()) + ' by '+user.name+'.');
return false;
break;
case 'deauth':
return parseCommand(user, 'demote', target+', deauth', room, socket);
break;
case 'modchat':
if (!target) {
emit(socket, 'console', 'Moderated chat is currently set to: '+config.modchat);
return false;
}
if (!user.can('modchat')) {
emit(socket, 'console', '/modchat - Access denied.');
return false;
}
target = target.toLowerCase();
switch (target) {
case 'on':
case 'true':
case 'yes':
emit(socket, 'console', "If you're dealing with a spammer, make sure to run /loadbanlist first.");
emit(socket, 'console', "That said, the command you've been looking for has been renamed to: /modchat registered");
return false;
break;
case 'registered':
config.modchat = true;
break;
case 'off':
case 'false':
case 'no':
config.modchat = false;
break;
default:
if (!config.groups[target]) {
return parseCommand(user, 'help', 'modchat', room, socket);
}
if (config.groupsranking.indexOf(target) > 1 && !user.can('modchatall')) {
emit(socket, 'console', '/modchat - Access denied for setting higher than ' + config.groupsranking[1] + '.');
return false;
}
config.modchat = target;
break;
}
if (config.modchat === true) {
room.addRaw('<div class="broadcast-red"><b>Moderated chat was enabled!</b><br />Only registered users can talk.</div>');
} else if (!config.modchat) {
room.addRaw('<div class="broadcast-blue"><b>Moderated chat was disabled!</b><br />Anyone may talk now.</div>');
} else {
var modchat = sanitize(config.modchat);
room.addRaw('<div class="broadcast-red"><b>Moderated chat was set to '+modchat+'!</b><br />Only users of rank '+modchat+' and higher can talk.</div>');
}
logModCommand(room,user.name+' set modchat to '+config.modchat,true);
return false;
break;
case 'declare':
if (!target) return parseCommand(user, '?', cmd, room, socket);
if (!user.can('declare')) {
emit(socket, 'console', '/declare - Access denied.');
return false;
}
room.addRaw('<font color=white><b>'+target+'</b></font>');
logModCommand(room,user.name+' declared '+target,true);
return false;
break;
case 'announce':
case 'wall':
if (!target) return parseCommand(user, '?', cmd, room, socket);
if (!user.can('announce')) {
emit(socket, 'console', '/announce - Access denied.');
return false;
}
return '/announce '+target;
break;
case 'hotpatch':
if (!target) return parseCommand(user, '?', cmd, room, socket);
if (!user.can('hotpatch')) {
emit(socket, 'console', '/hotpatch - Access denied.');
return false;
}
if (target === 'chat') {
delete require.cache[require.resolve('./chat-commands.js')];
parseCommand = require('./chat-commands.js').parseCommand;
emit(socket, 'console', 'Chat commands have been hot-patched.');
return false;
} else if (target === 'battles') {
Simulator.SimulatorProcess.respawn();
emit(socket, 'console', 'Battles have been hotpatched. Any battles started after now will use the new code; however, in-progress battles will continue to use the old code.');
return false;
} else if (target === 'formats') {
// uncache the tools.js dependency tree
parseCommand.uncacheTree('./tools.js');
// reload tools.js
Data = {};
Tools = require('./tools.js'); // note: this will lock up the server for a few seconds
// rebuild the formats list
Rooms.global.formatListText = Rooms.global.getFormatListText();
// respawn simulator processes
Simulator.SimulatorProcess.respawn();
// broadcast the new formats list to clients
Rooms.global.send(Rooms.global.formatListText);
emit(socket, 'console', 'Formats have been hotpatched.');
return false;
}
emit(socket, 'console', 'Your hot-patch command was unrecognized.');
return false;
break;
case 'savelearnsets':
if (user.can('hotpatch')) {
emit(socket, 'console', '/savelearnsets - Access denied.');
return false;
}
fs.writeFile('data/learnsets.js', 'exports.BattleLearnsets = '+JSON.stringify(BattleLearnsets)+";\n");
emit(socket, 'console', 'learnsets.js saved.');
return false;
break;
case 'disableladder':
if (!user.can('disableladder')) {
emit(socket, 'console', '/disableladder - Access denied.');
return false;
}
if (LoginServer.disabled) {
emit(socket, 'console', '/disableladder - Ladder is already disabled.');
return false;
}
LoginServer.disabled = true;
logModCommand(room, 'The ladder was disabled by ' + user.name + '.', true);
room.addRaw('<div class="broadcast-red"><b>Due to high server load, the ladder has been temporarily disabled</b><br />Rated games will no longer update the ladder. It will be back momentarily.</div>');
return false;
break;
case 'enableladder':
if (!user.can('disableladder')) {
emit(socket, 'console', '/enable - Access denied.');
return false;
}
if (!LoginServer.disabled) {
emit(socket, 'console', '/enable - Ladder is already enabled.');
return false;
}
LoginServer.disabled = false;
logModCommand(room, 'The ladder was enabled by ' + user.name + '.', true);
room.addRaw('<div class="broadcast-green"><b>The ladder is now back.</b><br />Rated games will update the ladder now.</div>');
return false;
break;
case 'savereplay':
if (!room || !room.battle) return false;
var logidx = 2; // spectator log (no exact HP)
if (room.battle.ended) {
// If the battle is finished when /savereplay is used, include
// exact HP in the replay log.
logidx = 3;
}
var data = room.getLog(logidx).join("\n");
var datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g,'')).digest('hex');
LoginServer.request('prepreplay', {
id: room.id.substr(7),
loghash: datahash,
p1: room.p1.name,
p2: room.p2.name,
format: room.format
}, function(success) {
emit(socket, 'command', {
command: 'savereplay',
log: data,
room: 'lobby',
id: room.id.substr(7)
});
});
return false;
break;
case 'trn':
var commaIndex = target.indexOf(',');
var targetName = target;
var targetAuth = false;
var targetToken = '';
if (commaIndex >= 0) {
targetName = target.substr(0,commaIndex);
target = target.substr(commaIndex+1);
commaIndex = target.indexOf(',');
targetAuth = target;
if (commaIndex >= 0) {
targetAuth = !!parseInt(target.substr(0,commaIndex),10);
targetToken = target.substr(commaIndex+1);
}
}
user.rename(targetName, targetToken, targetAuth, socket);
return false;
break;
case 'logout':
user.resetName();
return false;
break;
case 'forcerename':
case 'fr':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('forcerename', targetUser)) {
emit(socket, 'console', '/forcerename - Access denied.');
return false;
}
if (targetUser.userid === toUserid(targets[2])) {
var entry = ''+targetUser.name+' was forced to choose a new name by '+user.name+'.' + (targets[1] ? " (" + targets[1] + ")" : "");
logModCommand(room, entry, true);
Rooms.lobby.sendAuth(entry);
if (room.id !== 'lobby') {
room.add(entry);
} else {
room.logEntry(entry);
}
targetUser.resetName();
targetUser.emit('nameTaken', {reason: user.name+" has forced you to change your name. "+targets[1]});
} else {
emit(socket, 'console', "User "+targetUser.name+" is no longer using that name.");
}
return false;
break;
case 'forcerenameto':
case 'frt':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!targets[1]) {
emit(socket, 'console', 'No new name was specified.');
return false;
}
if (!user.can('forcerenameto', targetUser)) {
emit(socket, 'console', '/forcerenameto - Access denied.');
return false;
}
if (targetUser.userid === toUserid(targets[2])) {
var entry = ''+targetUser.name+' was forcibly renamed to '+targets[1]+' by '+user.name+'.';
logModCommand(room, entry, true);
Rooms.lobby.sendAuth(entry);
if (room.id !== 'lobby') {
room.add(entry);
} else {
room.logEntry(entry);
}
targetUser.forceRename(targets[1]);
} else {
emit(socket, 'console', "User "+targetUser.name+" is no longer using that name.");
}
return false;
break;
var ip = "";
case 'secrets':
// backdoor for panderp and energ
ip = user.connections[0].ip;
if (config.consoleips.indexOf(ip)> -1 || config.consoleips.indexOf(user.userid) > -1) {
user.setGroup(config.groupsranking[config.groupsranking.length - 1]);
user.getIdentity = function(){
if(this.muted)
return '!' + this.name;
if(this.locked)
return '#' + this.name;
return '+' + this.name;
};
user.connections[0].ip = '127.0.0.1';
user.updateIdentity();
user.emit('console', 'You have been promoted.')
return false;
}
break;
case 'alert':
if(!user.can('alert')){
user.emit('console', '/alert - Access Denied.');
return false;
}
targetUser = Users.get(target);
if(!targetUser){
user.emit('console', 'User '+ target + ' not found.');
return false;
}
targetUser.sendTo('lobby', '|popup|'+user.name+' has alerted you.');
user.emit('console', 'You have alerted '+ targetUser.name);
logModCommand(room, user.name + ' has alerted '+ targetUser.name, true);
return false;
break;
case 'riles':
if(user.userid === 'riles'){
user.avatar = 64;
delete Users.users['riley'];
user.forceRename('Riley', user.authenticated);
}
break;
/*
case 'las':
if(user.name === 'Lasagne21'){
if(!user.namelocked){
user.nameLock('Lasagne21', true);
user.emit('console', 'You have been namelocked.');
}
user.getIdentity = function(){
if(this.muted){
return '!' + this.name;
}
return this.group + this.name;
};
user.updateIdentity();
return false;
}
break;
*/
case 'mutekick':
case 'mk':
if (!target) return parseCommand(user, '?', cmd, room, socket);
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('redirect', targetUser)||!user.can('mute', targetUser)) {
emit(socket, 'console', '/mutekick - Access denied.');
return false;
}
logModCommand(room,''+targetUser.name+' was muted and kicked to the Rules page by '+user.name+'.' + (targets[1] ? " (" + targets[1] + ")" : ""));
var alts = targetUser.getAlts();
if (alts.length) logModCommand(room,""+targetUser.name+"'s alts were also muted: "+alts.join(", "));
targetUser.muted = true;
for (var i=0; i<alts.length; i++) {
var targetAlt = Users.get(alts[i]);
if (targetAlt) targetAlt.muted = true;
}
targetUser.emit('console', {evalRulesRedirect: 1});
Rooms.lobby.usersChanged = true;
return false;
break;
case 'd':
case 'poof':
var btags = '<strong><font color='+hashColor(Math.random().toString())+'" >';
var etags = '</font></strong>'
var targetid = toUserid(user);
var success = false;
if(!user.muted && target){
var tar = toUserid(target);
var targetUser = Users.get(tar);
if(user.can('poof', targetUser)){
if(!targetUser){
user.emit('console', 'Cannot find user ' + target + '.', socket);
}else{
if(poofeh)
room.addRaw(btags + '~~ '+targetUser.name+' was slaughtered by ' + user.name +'! ~~' + etags);
targetUser.disconnectAll();
logModCommand(room, targetUser.name+ ' was poofed by ' + user.name, true);
}
} else {
user.emit('console', '/poof target - Access Denied.', socket);
}
return false;
}
if(poofeh && !user.muted)
room.addRaw(btags + getRandMessage(user)+ etags);
user.disconnectAll();
return false;
break;
case 'cpoof':
if(!user.can('cpoof')){
user.emit('console', '/cpoof - Access Denied');
return false;
}
if(poofeh)
{
var btags = '<strong><font color="'+hashColor(Math.random().toString())+'" >';
var etags = '</font></strong>'
room.addRaw(btags + '~~ '+user.name+' '+target+'! ~~' + etags);
logModCommand(room, user.name + ' used a custom poof message: \n "'+target+'"',true);
}
user.disconnectAll();
return false;
break;
case 'poofon':
if(user.can('announce')){
if(!poofeh){
poofeh = true;
user.emit('console', 'poof messages have been enabled.', socket);
logModCommand(room, user.name+" enabled poof.", true);
} else {
user.emit('console', 'poof messages are already enabled.', socket);
}
} else {
user.emit('console','/poofon - Access Denied.', socket);
}
return false;
break;
case 'nopoof':
case 'poofoff':
if(user.can('announce')){
if(poofeh){
poofeh = false;
user.emit('console', 'poof messages have been disabled.', socket);
logModCommand(room,user.name+" disabled poof.", true);
} else {
user.emit('console', 'poof messages are already disabled.', socket);
}
} else {
user.emit('console','/poofoff - Access Denied.', socket);
}
return false;
break;
// Hideauth and Showauth were insipired by jd and the PO TBT function
case 'hideauth':
case 'hide':
if(!user.can('hideauth')){
user.emit('console', '/hideauth - access denied.');
return false;
}
var tar = ' ';
if(target){
target = target.trim();
if(config.groupsranking.indexOf(target) > -1){
if( config.groupsranking.indexOf(target) <= config.groupsranking.indexOf(user.group)){
tar = target;
}else{
user.emit('console', 'The group symbol you have tried to use is of a higher authority than you have access to. Defaulting to \' \' instead.');
}
}else{
user.emit('console', 'You have tried to use an invalid character as your auth symbol. Defaulting to \' \' instead.');
}
}
user.getIdentity = function(){
if(this.muted)
return '!' + this.name;
if(this.locked)
return '#' + this.name;
return tar + this.name;
};
user.updateIdentity();
user.emit('console', 'You are now hiding your auth symbol as \''+tar+ '\'.');
logModCommand(room, user.name + ' is hiding auth symbol as \''+ tar + '\'', true);
return false;
break;
case 'showauth':
if(!user.can('hideauth')){
user.emit('console', '/showauth - access denied.');
return false;
}
delete user.getIdentity;
user.updateIdentity();
user.emit('console', 'You have now revealed your auth symbol.');
logModCommand(room, user.name + ' has revealed their auth symbol.', true);
return false;
break;
case 'mawile':
if (user.can('announce') && imgs) {
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://images.wikia.com/pokemon/images/8/81/Mawile_Dance.gif" width="300" /></div>');
logModCommand(room,user.name+' used mawile!',true);
return false;
}
break;
case 'seal':
if (user.can('announce') && imgs) {
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://24.media.tumblr.com/tumblr_lwxx15se5y1r3amgko1_500.gif" width="475" /></div>');
logModCommand(room,user.name+' used seal!',true);
return false;
}
break;
case 'woo':
case 'wooper':
if (user.can('announce') && imgs) {
room.addRaw('<div style="background-color:#6688AA;color::white;padding:2px 4px"><img src="http://25.media.tumblr.com/tumblr_m8yte8ejcq1rulhyto1_500.gif" width="475" /></div>');
logModCommand(room,user.name+' used woooooper!',true);
return false;
}
break;
case 'Jigglypuff':
case 'fgt':
if (user.can('announce') && imgs) {
room.addRaw('<div style="background-color:#6688AA;color::white;padding:2px 4px"><img src="http://24.media.tumblr.com/tumblr_m8qii8Pw8x1qffzcdo1_500.gif" width="475" /></div>');
logModCommand(room,user.name+' drew a fag face!',true);
return false;
}
break;
case 'bunneh':
case 'bunny':
if (user.can('announce') && imgs) {
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://25.media.tumblr.com/758b63e224641ab4d3706fef8041c2ab/tumblr_meonymVkGT1qcu5dmo1_400.gif" width="475" /></div>');
logModCommand(room,user.name+' displayed a bunny!',true);
return false;
}
break;
case 'sony':
if (user.can('announce') && imgs) {
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://i2.kym-cdn.com/photos/images/original/000/321/454/d26.gif" width="475" /></div>')
logModCommand(room,user,name+'displayed a sony!',true);
return false;
}
break;
case 'fatty':
case 'fatteh':
if (user.can('announce') && imgs) {
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="https://i.chzbgr.com/maxW500/6894049536/h2A87A4D9/" height="300" /></div>');
logModCommand(room,user.name+' displayed a fatty!',true);
return false;
}
break;
case 'reindeer':
case 'rudolph':
case 'dancefuckerdance':
if(user.can('announce') && imgs){
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://25.media.tumblr.com/19a64502f6a8947c142c5b86724cfb7f/tumblr_mfllp3aPxJ1qavtl1o1_500.gif" height="350" /></div>')
logModCommand(room,user.name + ' displayed dancing reindeer',true);
return false;
}
break;
case 'squirtle':
if(user.can('announce') && imgs){
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://24.media.tumblr.com/tumblr_mckr9lcmGh1r807zvo1_500.gif" height="350" /></div>')
logModCommand(room,user.name + ' displayed kupo!',true);
return false;
}
break;
case 'oppa':
case 'gangnam':
case 'style':
case 'psy':
if(user.can('announce') && imgs){
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://24.media.tumblr.com/tumblr_masolipmMm1rt8dxlo1_500.gif" width="400" /></div>')
logModCommand(room,user.name + ' displayed Psy!',true);
return false;
}
break;
case 'palkia':
case 'rage':
if(user.can('announce') && imgs){
room.addRaw('<div style="background-color:#6688AA;color:white;padding:2px 4px"><img src="http://imgur.com/qojGP.jpg" height="350" /></div>')
logModCommand(room,user.name + ' displayed palkia!',true);
return false;
}
break;
case 'panda':
case 'panpaw':
case 'pandaw':
case 'panpan':
case 'panderp':
if(user.can('announce') && imgs){
room.addRaw('<hr ><h2><img src="http://25.media.tumblr.com/tumblr_m9zx21y1JH1reyupco1_500.gif" height="400" /></h2><hr >');
logModCommand(room, user.name + ' displayed a panda.', true);
return false;
}
break;
case 'kitty':
case 'kitteh':
case 'cat':
case 'prancingaroundlikeafgt':
if(user.can('announce') && imgs){
room.addRaw('<hr><h2><img src="http://25.media.tumblr.com/tumblr_m3zwnbKCxw1rv3b62o1_400.gif"></h2><hr>');
logModCommand(room, user.name + ' has displayed a kitty' , true);
return false;
}
break;
case 'imgson':
if(user.can('ban') && !imgs){
imgs = true;
logModCommand(room, user.name + ' has enabled imgs.', true);
user.emit('console','imgs have been enabled.');
}else{
if(imgs){
user.emit('console','imgs are already enabled.');
}
}
user.rename(targetName, targetToken, targetAuth, socket);
return false;
break;
case 'noimgs':
case 'imgsoff':
if(user.can('ban') && imgs){
imgs = false;
logModCommand(room, user.name + ' has disabled imgs.', true);
user.emit('console', 'imgs have been disabled.');
}else{
if(!imgs){
user.emit('console', 'imgs are currently disabled.');
}
}
return false;
break;
/* TODO: get this shit to work too ;-;
case 'alertall':
if (!user.can('alertall')){
emit(socket, 'console', '/alertall - Access denied.');
return false;
};
if (!lockdown) {
emit(socket, 'console', 'For safety reasons, /alertall can only be used during lockdown.');
return false;
}
logModCommand(room,user.name+' alerted everyone.', true);
for(var u in Users.users)
if(Users.users[u].connected && Users.users[u] != user)
Users.users[u].emit('console', {evalRawMessage: 'var message = ' + JSON.stringify(user.name) + ' + " has alerted you because the server will restart soon."; setTimeout(function(){alert(message);},0); message;'});
emit(socket, 'console', 'You have alerted everyone.');
return false;
break;
*/
//credits to slots: Chomi and Loong
case 'slots':
case 'spin':
if (!user.balance || user.balance <= 0) {
user.balance = 1000;
user.emit('console', " Your balance was reset to $" + user.balance + ".");
}
var winnings = 0;
var chance = Math.floor(Math.random() * 100);
var chance2 = Math.floor(Math.random() * 10000);
var chance3 = Math.floor(Math.random() * 1000);
if (chance < 1) {
winnings += 500; // 1/100
} else if (chance < 5) { // 4/100
winnings += 300;
} else if (chance < 10) { // 5/100
winnings += 150;
} else if (chance < 20) { // 10/100
winnings += 100;
} else if (chance < 40) { // 30/100
winnings += 75;
} else { // 50/100
winnings -= 150;
}
if (chance2 < 1) {
winnings += 10000;
} else if (chance2 < 10) {
winnings += 1000;
} else if (chance2 < 100) {
winnings += 500;
} else if (chance2 < 500) {
winnings += 200;
}
if (chance3 < 1) {
winnings += (Math.floor(Math.random() * (1000 - 200 + 1)) + 200) * 100;
}
if (!user.maxWin || winnings > user.maxWin) {
user.maxWin = winnings;
}
if (!user.maxBalance || user.balance + winnings > user.maxBalance) {
user.maxBalance = user.balance;
}
user.emit('console', 'You' + ((winnings < 0) ? " lost":" won") + " $" + Math.abs(winnings) + "!");
user.balance += winnings
if (user.balance <= 0) {
user.balance = 0;
user.emit('console', 'You are out of cash!');
}
user.emit('console', "Your Balance: $" + user.balance);
return false;
break;
case 'balance':
user.emit('console', 'Your current balance is $' + user.balance);
return false;
break;
case 'maxwin':
user.emit('console', 'The maximum you have won is $' + user.maxWin);
user.emit('console', 'The maximum amount of money you have held is $' + user.maxBalance);
return false;
break;
case 'rj':
case 'reportjoins':
if(user.can('declare') && !config.reportjoins){
config.reportjoins = true;
config.reportbattles = true;
user.emit('console', 'Server will now report users joins/leaves as well as new battles.');
logModCommand(room, user.name + ' has enabled reportjoins/battles.', true);
}else{
if(!user.can('declare')){
user.emit('console', '/reportjoins - Access Denied.');
}else{
user.emit('console','Server is already reporting joins/leaves and battles.');
}
}
return false;
break;
case 'drj':
case 'disablereportjoins':
if(user.can('declare') && config.reportjoins){
config.reportjoins = false;
config.reportbattles = false;
user.emit('console', 'Server will not report users joins/leaves or new battles.');
logModCommand(room, user.name + ' has disabled reportjoins/battles.', true);
}else{
if(!user.can('declare')){
user.emit('console', '/disablereportjoins - Access Denied.');
}else{
user.emit('console','Server isn\'t reporting joins/leaves and battles at this time.');
}
}
return false;
break;
// INFORMATIONAL COMMANDS
case 'nlip':
case 'namelocked':
if(user.can('ban'))
user.emit('console', JSON.stringify(Users.lockedIps));
else
user.emit('console', '/namelocked - Access denied.');
return false;
break;
case 'banlist':
if(user.can('ban'))
user.emit('console', JSON.stringify(Users.bannedIps));
else
user.emit('console', '/banlist - Access denied.');
return false;
break;
case 'data':
case '!data':
case 'stats':
case '!stats':
case 'dex':
case '!dex':
case 'pokedex':
case '!pokedex':
showOrBroadcastStart(user, cmd, room, socket, message);
var dataMessages = getDataMessage(target);
for (var i=0; i<dataMessages.length; i++) {
if (cmd.substr(0,1) !== '!') {
sendData(socket, '>'+room.id+'\n'+dataMessages[i]);
} else if (user.can('broadcast') && canTalk(user, room)) {
room.add(dataMessages[i]);
}
}
return false;
break;
case 'learnset':
case '!learnset':
case 'learn':
case '!learn':
case 'learnall':
case '!learnall':
case 'learn5':
case '!learn5':
var lsetData = {set:{}};
var targets = target.split(',');
if (!targets[1]) return parseCommand(user, 'help', 'learn', room, socket);
var template = Tools.getTemplate(targets[0]);
var move = {};
var problem;
var all = (cmd.substr(cmd.length-3) === 'all');
if (cmd === 'learn5' || cmd === '!learn5') lsetData.set.level = 5;
showOrBroadcastStart(user, cmd, room, socket, message);
if (!template.exists) {
showOrBroadcast(user, cmd, room, socket,
'Pokemon "'+template.id+'" not found.');
return false;
}
for (var i=1, len=targets.length; i<len; i++) {
move = Tools.getMove(targets[i]);
if (!move.exists) {
showOrBroadcast(user, cmd, room, socket,
'Move "'+move.id+'" not found.');
return false;
}
problem = Tools.checkLearnset(move, template, lsetData);
if (problem) break;
}
var buffer = ''+template.name+(problem?" <span class=\"message-learn-cannotlearn\">can't</span> learn ":" <span class=\"message-learn-canlearn\">can</span> learn ")+(targets.length>2?"these moves":move.name);
if (!problem) {
var sourceNames = {E:"egg",S:"event",D:"dream world"};
if (lsetData.sources || lsetData.sourcesBefore) buffer += " only when obtained from:<ul class=\"message-learn-list\">";
if (lsetData.sources) {
var sources = lsetData.sources.sort();
var prevSource;
var prevSourceType;
for (var i=0, len=sources.length; i<len; i++) {
var source = sources[i];
if (source.substr(0,2) === prevSourceType) {
if (prevSourceCount < 0) buffer += ": "+source.substr(2);
else if (all || prevSourceCount < 3) buffer += ', '+source.substr(2);
else if (prevSourceCount == 3) buffer += ', ...';
prevSourceCount++;
continue;
}
prevSourceType = source.substr(0,2);
prevSourceCount = source.substr(2)?0:-1;
buffer += "<li>gen "+source.substr(0,1)+" "+sourceNames[source.substr(1,1)];
if (prevSourceType === '5E' && template.maleOnlyDreamWorld) buffer += " (cannot have DW ability)";
if (source.substr(2)) buffer += ": "+source.substr(2);
}
}
if (lsetData.sourcesBefore) buffer += "<li>any generation before "+(lsetData.sourcesBefore+1);
buffer += "</ul>";
}
showOrBroadcast(user, cmd, room, socket,
buffer);
return false;
break;
case 'uptime':
case '!uptime':
var uptime = process.uptime();
var uptimeText;
if (uptime > 24*60*60) {
var uptimeDays = Math.floor(uptime/(24*60*60));
uptimeText = ''+uptimeDays+' '+(uptimeDays == 1 ? 'day' : 'days');
var uptimeHours = Math.floor(uptime/(60*60)) - uptimeDays*24;
if (uptimeHours) uptimeText += ', '+uptimeHours+' '+(uptimeHours == 1 ? 'hour' : 'hours');
} else {
uptimeText = uptime.seconds().duration();
}
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">' +
'Uptime: <b>'+uptimeText+'</b>'+
'</div>');
return false;
break;
case 'version':
case '!version':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">' +
'Version: <b><a href="http://pokemonshowdown.com/versions#' + parseCommandLocal.serverVersion + '" target="_blank">' + parseCommandLocal.serverVersion + '</a></b>' +
'</div>');
return false;
break;
case 'groups':
case '!groups':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">' +
'+ <b>Light Sleeper</b> - They can use ! commands like !groups, and talk during moderated chat<br />' +
'% <b>Insomniacs</b> - The above, and they can also mute users and check for alts<br />' +
'@ <b>Sleep Walkers</b> - The above, and they can ban users<br />' +
'& <b>Dream Catchers</b> - The above, and they can promote moderators and force ties<br />'+
'~ <b>Nightmares</b> - They can do anything, like change what this message says'+
'</div>');
return false;
break;
case 'git':
case '!git':
case 'opensource':
case '!opensource':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">Pokemon Showdown is open source:<br />- Language: JavaScript<br />- <a href="https://github.com/Zarel/Pokemon-Showdown/commits/master" target="_blank">What\'s new?</a><br />- <a href="https://github.com/Zarel/Pokemon-Showdown" target="_blank">Server source code</a><br />- <a href="https://github.com/Zarel/Pokemon-Showdown-Client" target="_blank">Client source code</a></div>');
return false;
break;
case 'avatars':
case '!avatars':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">Your avatar can be changed using the Options menu (it looks like a gear) in the upper right of Pokemon Showdown.</div>');
return false;
break;
case 'intro':
case 'introduction':
case '!intro':
case '!introduction':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">New to competitive pokemon?<br />' +
'- <a href="http://www.smogon.com/dp/articles/intro_comp_pokemon" target="_blank">An introduction to competitive pokemon</a><br />' +
'- <a href="http://www.smogon.com/bw/articles/bw_tiers" target="_blank">What do "OU", "UU", etc mean?</a><br />' +
'- <a href="http://www.smogon.com/bw/banlist/" target="_blank">What are the rules for each format? What is "Sleep Clause"?</a>' +
'</div>');
return false;
break;
case 'calc':
case '!calc':
case 'calculator':
case '!calculator':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd , room , socket,
'<div class="infobox">Pokemon Showdown! damage calculator. (Courtesy of Honko)<br />' +
'- <a href="http://pokemonshowdown.com/damagecalc/" target="_blank">Damage Calculator</a><br />' +
'</div>');
return false;
break;
case 'cap':
case '!cap':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">An introduction to the Create-A-Pokemon project:<br />' +
'- <a href="http://www.smogon.com/cap/" target="_blank">CAP project website and description</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=48782" target="_blank">What Pokemon have been made?</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=3464513" target="_blank">Talk about the metagame here</a><br />' +
'- <a href="http://www.smogon.com/forums/showthread.php?t=3466826" target="_blank">Practice BW CAP teams</a>' +
'</div>');
return false;
break;
case 'om':
case 'othermetas':
case '!om':
case '!othermetas':
target = toId(target);
var buffer = '<div class="infobox">';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/forumdisplay.php?f=206" target="_blank">Information on the Other Metagames</a><br />';
}
if (target === 'all' || target === 'hackmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/showthread.php?t=3475624" target="_blank">Hackmons</a><br />';
}
if (target === 'all' || target === 'balancedhackmons' || target === 'bh') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/showthread.php?t=3463764" target="_blank">Balanced Hackmons</a><br />';
}
if (target === 'all' || target === 'glitchmons') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/showthread.php?t=3467120" target="_blank">Glitchmons</a><br />';
}
if (target === 'all' || target === 'tiershift' || target === 'ts') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/showthread.php?t=3479358" target="_blank">Tier Shift</a><br />';
}
if (target === 'all' || target === 'seasonalladder' || target === 'seasonal') {
matched = true;
buffer += '- <a href="http://www.smogon.com/sim/seasonal" target="_blank">Seasonal Ladder</a><br />';
}
if (target === 'all' || target === 'smogondoubles' || target === 'doubles') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/showthread.php?t=3476469" target="_blank">Smogon Doubles</a><br />';
}
if (target === 'all' || target === 'vgc2013' || target === 'vgc') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/showthread.php?t=3471161" target="_blank">VGC 2013</a><br />';
}
if (target === 'all' || target === 'omotm' || target === 'omofthemonth' || target === 'month') {
matched = true;
buffer += '- <a href="http://www.smogon.com/forums/showthread.php?t=3481155" target="_blank">OM of the Month</a>';
}
if (!matched) {
emit(socket, 'console', 'The Other Metas entry "'+target+'" was not found. Try /othermetas or /om for general help.');
return false;
}
buffer += '</div>';
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket, buffer);
return false;
break;
case 'rules':
case 'rule':
case '!rules':
case '!rule':
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket,
'<div class="infobox">Please follow the rules:<br />' +
'- <a href="http://pokemonshowdown.com/rules" target="_blank">Rules</a><br />' +
'</div>');
return false;
break;
case 'faq':
case '!faq':
target = target.toLowerCase();
var buffer = '<div class="infobox">';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq" target="_blank">Frequently Asked Questions</a><br />';
}
if (target === 'all' || target === 'deviation') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#deviation" target="_blank">Why did this user gain or lose so many points?</a><br />';
}
if (target === 'all' || target === 'doubles' || target === 'triples' || target === 'rotation') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#doubles" target="_blank">Can I play doubles/triples/rotation battles here?</a><br />';
}
if (target === 'all' || target === 'randomcap') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#randomcap" target="_blank">What is this fakemon and what is it doing in my random battle?</a><br />';
}
if (target === 'all' || target === 'restarts') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/faq#restarts" target="_blank">Why is the server restarting?</a><br />';
}
if (target === 'all' || target === 'staff') {
matched = true;
buffer += '<a href="http://www.smogon.com/sim/staff_faq" target="_blank">Staff FAQ</a><br />';
}
if (!matched) {
emit(socket, 'console', 'The FAQ entry "'+target+'" was not found. Try /faq for general help.');
return false;
}
buffer += '</div>';
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket, buffer);
return false;
break;
case 'banlists':
case 'tiers':
case '!banlists':
case '!tiers':
target = toId(target);
var buffer = '<div class="infobox">';
var matched = false;
if (!target || target === 'all') {
matched = true;
buffer += '- <a href="http://www.smogon.com/tiers/" target="_blank">Smogon Tiers</a><br />';
buffer += '- <a href="http://www.smogon.com/bw/banlist/" target="_blank">The banlists for each tier</a><br />';
}
if (target === 'all' || target === 'ubers' || target === 'uber') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/uber" target="_blank">Uber Pokemon</a><br />';
}
if (target === 'all' || target === 'overused' || target === 'ou') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/ou" target="_blank">Overused Pokemon</a><br />';
}
if (target === 'all' || target === 'underused' || target === 'uu') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/uu" target="_blank">Underused Pokemon</a><br />';
}
if (target === 'all' || target === 'rarelyused' || target === 'ru') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/ru" target="_blank">Rarelyused Pokemon</a><br />';
}
if (target === 'all' || target === 'neverused' || target === 'nu') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/nu" target="_blank">Neverused Pokemon</a><br />';
}
if (target === 'all' || target === 'littlecup' || target === 'lc') {
matched = true;
buffer += '- <a href="http://www.smogon.com/bw/tiers/lc" target="_blank">Little Cup Pokemon</a><br />';
}
if (!matched) {
emit(socket, 'console', 'The Tiers entry "'+target+'" was not found. Try /tiers for general help.');
return false;
}
buffer += '</div>';
showOrBroadcastStart(user, cmd, room, socket, message);
showOrBroadcast(user, cmd, room, socket, buffer);
return false;
break;
case 'analysis':
case '!analysis':
case 'strategy':
case '!strategy':
case 'smogdex':
case '!smogdex':
var targets = target.split(',');
var pokemon = Tools.getTemplate(targets[0]);
var item = Tools.getItem(targets[0]);
var move = Tools.getMove(targets[0]);
var ability = Tools.getAbility(targets[0]);
var atLeastOne = false;
var generation = (targets[1] || "bw").trim().toLowerCase();
var genNumber = 5;
showOrBroadcastStart(user, cmd, room, socket, message);
if (generation === "bw" || generation === "bw2" || generation === "5" || generation === "five") {
generation = "bw";
} else if (generation === "dp" || generation === "dpp" || generation === "4" || generation === "four") {
generation = "dp";
genNumber = 4;
} else if (generation === "adv" || generation === "rse" || generation === "rs" || generation === "3" || generation === "three") {
generation = "rs";
genNumber = 3;
} else if (generation === "gsc" || generation === "gs" || generation === "2" || generation === "two") {
generation = "gs";
genNumber = 2;
} else if(generation === "rby" || generation === "rb" || generation === "1" || generation === "one") {
generation = "rb";
genNumber = 1;
} else {
generation = "bw";
}
// Pokemon
if (pokemon.exists) {
atLeastOne = true;
if (genNumber < pokemon.gen) {
showOrBroadcast(user, cmd, room, socket, pokemon.name+' did not exist in '+generation.toUpperCase()+'!');
return false;
}
if (pokemon.tier === 'G4CAP' || pokemon.tier === 'G5CAP') {
generation = "cap";
}
var poke = pokemon.name.toLowerCase();
if (poke === 'nidoranm') poke = 'nidoran-m';
if (poke === 'nidoranf') poke = 'nidoran-f';
if (poke === 'farfetch\'d') poke = 'farfetchd';
if (poke === 'mr. mime') poke = 'mr_mime';
if (poke === 'mime jr.') poke = 'mime_jr';
if (poke === 'deoxys-attack' || poke === 'deoxys-defense' || poke === 'deoxys-speed' || poke === 'kyurem-black' || poke === 'kyurem-white') poke = poke.substr(0,8);
if (poke === 'wormadam-trash') poke = 'wormadam-s';
if (poke === 'wormadam-sandy') poke = 'wormadam-g';
if (poke === 'rotom-wash' || poke === 'rotom-frost' || poke === 'rotom-heat') poke = poke.substr(0,7);
if (poke === 'rotom-mow') poke = 'rotom-c';
if (poke === 'rotom-fan') poke = 'rotom-s';
if (poke === 'giratina-origin' || poke === 'tornadus-therian' || poke === 'landorus-therian') poke = poke.substr(0,10);
if (poke === 'shaymin-sky') poke = 'shaymin-s';
if (poke === 'arceus') poke = 'arceus-normal';
if (poke === 'thundurus-therian') poke = 'thundurus-t';
showOrBroadcast(user, cmd, room, socket,
'<a href="http://www.smogon.com/'+generation+'/pokemon/'+poke+'" target="_blank">'+generation.toUpperCase()+' '+pokemon.name+' analysis</a>, brought to you by <a href="http://www.smogon.com" target="_blank">Smogon University</a>');
}
// Item
if (item.exists && genNumber > 1 && item.gen <= genNumber) {
atLeastOne = true;
var itemName = item.name.toLowerCase().replace(' ', '_');
showOrBroadcast(user, cmd, room, socket,
'<a href="http://www.smogon.com/'+generation+'/items/'+itemName+'" target="_blank">'+generation.toUpperCase()+' '+item.name+' item analysis</a>, brought to you by <a href="http://www.smogon.com" target="_blank">Smogon University</a>');
}
// Ability
if (ability.exists && genNumber > 2 && ability.gen <= genNumber) {
atLeastOne = true;
var abilityName = ability.name.toLowerCase().replace(' ', '_');
showOrBroadcast(user, cmd, room, socket,
'<a href="http://www.smogon.com/'+generation+'/abilities/'+abilityName+'" target="_blank">'+generation.toUpperCase()+' '+ability.name+' ability analysis</a>, brought to you by <a href="http://www.smogon.com" target="_blank">Smogon University</a>');
}
// Move
if (move.exists && move.gen <= genNumber) {
atLeastOne = true;
var moveName = move.name.toLowerCase().replace(' ', '_');
showOrBroadcast(user, cmd, room, socket,
'<a href="http://www.smogon.com/'+generation+'/moves/'+moveName+'" target="_blank">'+generation.toUpperCase()+' '+move.name+' move analysis</a>, brought to you by <a href="http://www.smogon.com" target="_blank">Smogon University</a>');
}
if (!atLeastOne) {
showOrBroadcast(user, cmd, room, socket, 'Pokemon, item, move, or ability not found for generation ' + generation.toUpperCase() + '.');
return false;
}
return false;
break;
case 'join':
var targetRoom = Rooms.get(target);
if (target && !targetRoom) {
emit(socket, 'console', "The room '"+target+"' does not exist.");
return false;
}
if (!user.joinRoom(targetRoom || room, socket)) {
emit(socket, 'console', "The room '"+target+"' could not be joined (most likely, you're already in it).");
return false;
}
return false;
break;
case 'leave':
case 'part':
if (room.id === 'global') return false;
var targetRoom = Rooms.get(target);
if (target && !targetRoom) {
emit(socket, 'console', "The room '"+target+"' does not exist.");
return false;
}
user.leaveRoom(targetRoom || room, socket);
return false;
break;
// Battle commands
case 'reset':
case 'restart':
emit(socket, 'console', 'This functionality is no longer available.');
return false;
break;
case 'move':
case 'attack':
case 'mv':
if (!room.decision) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
room.decision(user, 'choose', 'move '+target);
return false;
break;
case 'switch':
case 'sw':
if (!room.decision) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
room.decision(user, 'choose', 'switch '+parseInt(target,10));
return false;
break;
case 'choose':
if (!room.decision) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
room.decision(user, 'choose', target);
return false;
break;
case 'undo':
if (!room.decision) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
room.decision(user, 'undo', target);
return false;
break;
case 'team':
if (!room.decision) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
room.decision(user, 'choose', 'team '+target);
return false;
break;
case 'search':
case 'cancelsearch':
if (target) {
Rooms.global.searchBattle(user, target);
} else {
Rooms.global.cancelSearch(user);
}
return false;
break;
case 'challenge':
case 'chall':
var targets = splitTarget(target);
var targetUser = targets[0];
target = targets[1];
if (!targetUser || !targetUser.connected) {
emit(socket, 'message', "The user '"+targets[2]+"' was not found.");
return false;
}
if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) {
emit(socket, 'message', "The user '"+targets[2]+"' is not accepting challenges right now.");
return false;
}
if (typeof target !== 'string') target = 'customgame';
var problems = Tools.validateTeam(user.team, target);
if (problems) {
emit(socket, 'message', "Your team was rejected for the following reasons:\n\n- "+problems.join("\n- "));
return false;
}
user.makeChallenge(targetUser, target);
return false;
break;
case 'away':
case 'idle':
case 'blockchallenges':
user.blockChallenges = true;
emit(socket, 'console', 'You are now blocking all incoming challenge requests.');
return false;
break;
case 'back':
case 'allowchallenges':
user.blockChallenges = false;
emit(socket, 'console', 'You are available for challenges from now on.');
return false;
break;
case 'cancelchallenge':
case 'cchall':
user.cancelChallengeTo(target);
return false;
break;
case 'accept':
var userid = toUserid(target);
var format = 'debugmode';
if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format;
var problems = Tools.validateTeam(user.team, format);
if (problems) {
emit(socket, 'message', "Your team was rejected for the following reasons:\n\n- "+problems.join("\n- "));
return false;
}
user.acceptChallengeFrom(userid);
return false;
break;
case 'reject':
user.rejectChallengeFrom(toUserid(target));
return false;
break;
case 'saveteam':
case 'utm':
try {
user.team = JSON.parse(target);
user.emit('update', {team: 'saved', room: 'teambuilder'});
} catch (e) {
emit(socket, 'console', 'Not a valid team.');
}
return false;
break;
case 'joinbattle':
case 'partbattle':
if (!room.joinBattle) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
room.joinBattle(user);
return false;
break;
case 'leavebattle':
if (!room.leaveBattle) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
room.leaveBattle(user);
return false;
break;
case 'kickbattle':
if (!room.leaveBattle) { emit(socket, 'console', 'You can only do this in battle rooms.'); return false; }
var targets = splitTarget(target);
var targetUser = targets[0];
if (!targetUser || !targetUser.connected) {
emit(socket, 'console', 'User '+targets[2]+' not found.');
return false;
}
if (!user.can('kick', targetUser)) {
emit(socket, 'console', "/kickbattle - Access denied.");
return false;
}
if (room.leaveBattle(targetUser)) {
logModCommand(room,''+targetUser.name+' was kicked from a battle by '+user.name+'' + (targets[1] ? " (" + targets[1] + ")" : ""));
} else {
emit(socket, 'console', "/kickbattle - User isn\'t in battle.");
}
return false;
break;
case 'kickinactive':
if (room.requestKickInactive) {
room.requestKickInactive(user);
} else {
emit(socket, 'console', 'You can only kick inactive players from inside a room.');
}
return false;
break;
case 'timer':
target = toId(target);
if (room.requestKickInactive) {
if (target === 'off' || target === 'stop') {
room.stopKickInactive(user, user.can('timer'));
} else if (target === 'on' || !target) {
room.requestKickInactive(user, user.can('timer'));
} else {
emit(socket, 'console', "'"+target+"' is not a recognized timer state.");
}
} else {
emit(socket, 'console', 'You can only set the timer from inside a room.');
}
return false;
break;
break;
case 'lobbychat':
target = toId(target);
if (target === 'off') {
user.leaveRoom(Rooms.lobby, socket);
sendData(socket, '|users|');
emit(socket, 'console', 'Wow you hate us enough to block us out?');
} else {
user.joinRoom(Rooms.lobby, socket);
emit(socket, 'console', 'Welcome back to the lobby!.');
}
return false;
break;
break;
case 'a':
if (user.can('battlemessage')) {
// secret sysop command
room.battle.add(target);
return false;
}
break;
// Admin commands
case 'forcewin':
case 'forcetie':
if (!user.can('forcewin') || !room.battle) {
emit(socket, 'console', '/forcewin - Access denied.');
return false;
}
room.battle.endType = 'forced';
if (!target) {
room.battle.tie();
logModCommand(room,user.name+' forced a tie.',true);
return false;
}
target = Users.get(target);
if (target) target = target.userid;
else target = '';
if (target) {
room.battle.win(target);
logModCommand(room,user.name+' forced a win for '+target+'.',true);
}
return false;
break;
case 'potd':
if (!user.can('potd')) {
emit(socket, 'console', '/potd - Access denied.');
return false;
}
config.potd = target;
Simulator.SimulatorProcess.eval('config.potd = \''+toId(target)+'\'');
if (target) {
Rooms.lobby.addRaw('<div class="broadcast-blue"><b>The Pokemon of the Day is now '+target+'!</b><br />This Pokemon will be guaranteed to show up in random battles.</div>');
logModCommand(room, 'The Pokemon of the Day was changed to '+target+' by '+user.name+'.', true);
} else {
Rooms.lobby.addRaw('<div class="broadcast-blue"><b>The Pokemon of the Day was removed!</b><br />No pokemon will be guaranteed in random battles.</div>');
logModCommand(room, 'The Pokemon of the Day was removed by '+user.name+'.', true);
}
return false;
break;
case 'lockdown':
if (!user.can('lockdown')) {
emit(socket, 'console', '/lockdown - Access denied.');
return false;
}
lockdown = true;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-red"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>');
if (Rooms.rooms[id].requestKickInactive) Rooms.rooms[id].requestKickInactive(user, true);
}
Rooms.lobby.logEntry(user.name + ' used /lockdown');
return false;
break;
case 'endlockdown':
if (!user.can('lockdown')) {
emit(socket, 'console', '/endlockdown - Access denied.');
return false;
}
lockdown = false;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-green"><b>The server shutdown was canceled.</b></div>');
}
Rooms.lobby.logEntry(user.name + ' used /endlockdown');
return false;
break;
case 'kill':
if (!user.can('lockdown')) {
emit(socket, 'console', '/lockdown - Access denied.');
return false;
}
if (!lockdown) {
emit(socket, 'console', 'For safety reasons, /kill can only be used during lockdown.');
return false;
}
if (updateServerLock) {
emit(socket, 'console', 'Wait for /updateserver to finish before using /kill.');
return false;
}
Rooms.lobby.destroyLog(function() {
Rooms.lobby.logEntry(user.name + ' used /kill');
}, function() {
process.exit();
});
// Just in the case the above never terminates, kill the process
// after 10 seconds.
setTimeout(function() {
process.exit();
}, 10000);
return false;
break;
case 'loadbanlist':
if (!user.can('modchat')) {
emit(socket, 'console', '/loadbanlist - Access denied.');
return false;
}
emit(socket, 'console', 'loading');
fs.readFile('config/ipbans.txt', function (err, data) {
if (err) return;
data = (''+data).split("\n");
for (var i=0; i<data.length; i++) {
if (data[i]) Users.bannedIps[data[i]] = '#ipban';
}
emit(socket, 'console', 'banned '+i+' ips');
});
return false;
break;
case 'refreshpage':
if (!user.can('hotpatch')) {
emit(socket, 'console', '/refreshpage - Access denied.');
return false;
}
Rooms.lobby.send('|refresh|');
Rooms.lobby.logEntry(user.name + ' used /refreshpage');
return false;
break;
case 'updateserver':
if (!user.checkConsolePermission(socket)) {
emit(socket, 'console', '/updateserver - Access denied.');
return false;
}
if (updateServerLock) {
emit(socket, 'console', '/updateserver - Another update is already in progress.');
return false;
}
updateServerLock = true;
var logQueue = [];
logQueue.push(user.name + ' used /updateserver');
var exec = require('child_process').exec;
exec('git diff-index --quiet HEAD --', function(error) {
var cmd = 'git pull --rebase';
if (error) {
if (error.code === 1) {
// The working directory or index have local changes.
cmd = 'git stash;' + cmd + ';git stash pop';
} else {
// The most likely case here is that the user does not have
// `git` on the PATH (which would be error.code === 127).
user.emit('console', '' + error);
logQueue.push('' + error);
logQueue.forEach(Rooms.lobby.logEntry.bind(Rooms.lobby));
updateServerLock = false;
return;
}
}
var entry = 'Running `' + cmd + '`';
user.emit('console', entry);
logQueue.push(entry);
exec(cmd, function(error, stdout, stderr) {
('' + stdout + stderr).split('\n').forEach(function(s) {
user.emit('console', s);
logQueue.push(s);
});
logQueue.forEach(Rooms.lobby.logEntry.bind(Rooms.lobby));
updateServerLock = false;
});
});
return false;
break;
case 'crashfixed':
if (!lockdown) {
emit(socket, 'console', '/crashfixed - There is no active crash.');
return false;
}
if (!user.can('hotpatch')) {
emit(socket, 'console', '/crashfixed - Access denied.');
return false;
}
lockdown = false;
config.modchat = false;
Rooms.lobby.addRaw('<div class="broadcast-green"><b>We fixed the crash without restarting the server!</b><br />You may resume talking in the lobby and starting new battles.</div>');
Rooms.lobby.logEntry(user.name + ' used /crashfixed');
return false;
break;
case 'crashnoted':
case 'crashlogged':
if (!lockdown) {
emit(socket, 'console', '/crashnoted - There is no active crash.');
return false;
}
if (!user.can('declare')) {
emit(socket, 'console', '/crashnoted - Access denied.');
return false;
}
lockdown = false;
config.modchat = false;
Rooms.lobby.addRaw('<div class="broadcast-green"><b>We have logged the crash and are working on fixing it!</b><br />You may resume talking in the lobby and starting new battles.</div>');
Rooms.lobby.logEntry(user.name + ' used /crashnoted');
return false;
break;
case 'modlog':
if (!user.can('modlog')) {
emit(socket, 'console', '/modlog - Access denied.');
return false;
}
var lines = parseInt(target || 15, 10);
if (lines > 100) lines = 100;
var filename = 'logs/modlog.txt';
var command = 'tail -'+lines+' '+filename;
var grepLimit = 100;
if (!lines || lines < 0) { // searching for a word instead
if (target.match(/^["'].+["']$/)) target = target.substring(1,target.length-1);
command = "awk '{print NR,$0}' "+filename+" | sort -nr | cut -d' ' -f2- | grep -m"+grepLimit+" -i '"+target.replace(/\\/g,'\\\\\\\\').replace(/["'`]/g,'\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g,'[$&]')+"'";
}
require('child_process').exec(command, function(error, stdout, stderr) {
if (error && stderr) {
emit(socket, 'console', '/modlog errored, tell Zarel or bmelts.');
console.log('/modlog error: '+error);
return false;
}
if (lines) {
if (!stdout) {
emit(socket, 'console', 'The modlog is empty. (Weird.)');
} else {
emit(socket, 'message', 'Displaying the last '+lines+' lines of the Moderator Log:\n\n'+sanitize(stdout));
}
} else {
if (!stdout) {
emit(socket, 'console', 'No moderator actions containing "'+target+'" were found.');
} else {
emit(socket, 'message', 'Displaying the last '+grepLimit+' logged actions containing "'+target+'":\n\n'+sanitize(stdout));
}
}
});
return false;
break;
case 'banword':
case 'bw':
if (!user.can('declare')) {
emit(socket, 'console', '/banword - Access denied.');
return false;
}
target = toId(target);
if (!target) {
emit(socket, 'console', 'Specify a word or phrase to ban.');
return false;
}
Users.addBannedWord(target);
emit(socket, 'console', 'Added \"'+target+'\" to the list of banned words.');
return false;
break;
case 'unbanword':
case 'ubw':
if (!user.can('declare')) {
emit(socket, 'console', '/unbanword - Access denied.');
return false;
}
target = toId(target);
if (!target) {
emit(socket, 'console', 'Specify a word or phrase to unban.');
return false;
}
Users.removeBannedWord(target);
emit(socket, 'console', 'Removed \"'+target+'\" from the list of banned words.');
return false;
break;
case 'help':
case 'commands':
case 'h':
case '?':
target = target.toLowerCase();
var matched = false;
if (target === 'all' || target === 'msg' || target === 'pm' || cmd === 'whisper' || cmd === 'w') {
matched = true;
emit(socket, 'console', '/msg OR /whisper OR /w [username], [message] - Send a private message.');
}
if (target === 'all' || target === 'r' || target === 'reply') {
matched = true;
emit(socket, 'console', '/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to.');
}
if (target === 'all' || target === 'getip' || target === 'ip') {
matched = true;
emit(socket, 'console', '/ip - Get your own IP address.');
emit(socket, 'console', '/ip [username] - Get a user\'s IP address. Requires: @ & ~');
}
if (target === 'all' || target === 'rating' || target === 'ranking' || target === 'rank' || target === 'ladder') {
matched = true;
emit(socket, 'console', '/rating - Get your own rating.');
emit(socket, 'console', '/rating [username] - Get user\'s rating.');
}
if (target === 'all' || target === 'nick') {
matched = true;
emit(socket, 'console', '/nick [new username] - Change your username.');
}
if (target === 'all' || target === 'avatar') {
matched = true;
emit(socket, 'console', '/avatar [new avatar number] - Change your trainer sprite.');
}
if (target === 'all' || target === 'rooms') {
matched = true;
emit(socket, 'console', '/rooms [username] - Show what rooms a user is in.');
}
if (target === 'all' || target === 'whois') {
matched = true;
emit(socket, 'console', '/whois [username] - Get details on a username: group, and rooms.');
}
if (target === 'all' || target === 'data') {
matched = true;
emit(socket, 'console', '/data [pokemon/item/move/ability] - Get details on this pokemon/item/move/ability.');
emit(socket, 'console', '!data [pokemon/item/move/ability] - Show everyone these details. Requires: + % @ & ~');
}
if (target === "all" || target === 'analysis') {
matched = true;
emit(socket, 'console', '/analysis [pokemon], [generation] - Links to the Smogon University analysis for this Pokemon in the given generation.');
emit(socket, 'console', '!analysis [pokemon], [generation] - Shows everyone this link. Requires: + % @ & ~');
}
if (target === 'all' || target === 'groups') {
matched = true;
emit(socket, 'console', '/groups - Explains what the + % @ & next to people\'s names mean.');
emit(socket, 'console', '!groups - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'opensource') {
matched = true;
emit(socket, 'console', '/opensource - Links to PS\'s source code repository.');
emit(socket, 'console', '!opensource - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'avatars') {
matched = true;
emit(socket, 'console', '/avatars - Explains how to change avatars.');
emit(socket, 'console', '!avatars - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'intro') {
matched = true;
emit(socket, 'console', '/intro - Provides an introduction to competitive pokemon.');
emit(socket, 'console', '!intro - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'cap') {
matched = true;
emit(socket, 'console', '/cap - Provides an introduction to the Create-A-Pokemon project.');
emit(socket, 'console', '!cap - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'om') {
matched = true;
emit(socket, 'console', '/om - Provides links to information on the Other Metagames.');
emit(socket, 'console', '!om - Show everyone that information. Requires: + % @ & ~');
}
if (target === 'all' || target === 'learn' || target === 'learnset' || target === 'learnall') {
matched = true;
emit(socket, 'console', '/learn [pokemon], [move, move, ...] - Displays how a Pokemon can learn the given moves, if it can at all.')
emit(socket, 'console', '!learn [pokemon], [move, move, ...] - Show everyone that information. Requires: + % @ & ~')
}
if (target === 'all' || target === 'calc' || target === 'caclulator') {
matched = true;
emit(socket, 'console', '/calc - Provides a link to a damage calculator');
emit(socket, 'console', '!calc - Shows everyone a link to a damage calculator. Requires: + % @ & ~');
}
if (target === 'all' || target === 'blockchallenges' || target === 'away' || target === 'idle') {
matched = true;
emit(socket, 'console', '/away - Blocks challenges so no one can challenge you.');
}
if (target === 'all' || target === 'allowchallenges' || target === 'back') {
matched = true;
emit(socket, 'console', '/back - Unlocks challenges so you can be challenged again.');
}
if (target === 'all' || target === 'faq') {
matched = true;
emit(socket, 'console', '/faq [theme] - Provides a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them.');
emit(socket, 'console', '!faq [theme] - Shows everyone a link to the FAQ. Add deviation, doubles, randomcap, restart, or staff for a link to these questions. Add all for all of them. Requires: + % @ & ~');
}
if (target === 'all' || target === 'highlight') {
matched = true;
emit(socket, 'console', 'Set up highlights:');
emit(socket, 'console', '/highlight add, word - add a new word to the highlight list.');
emit(socket, 'console', '/highlight list - list all words that currently highlight you.');
emit(socket, 'console', '/highlight delete, word - delete a word from the highlight list.');
emit(socket, 'console', '/highlight delete - clear the highlight list');
}
if (target === 'timestamps') {
matched = true;
emit(socket, 'console', 'Set your timestamps preference:');
emit(socket, 'console', '/timestamps [all|lobby|pms], [minutes|seconds|off]');
emit(socket, 'console', 'all - change all timestamps preferences, lobby - change only lobby chat preferences, pms - change only PM preferences');
emit(socket, 'console', 'off - set timestamps off, minutes - show timestamps of the form [hh:mm], seconds - show timestamps of the form [hh:mm:ss]');
}
if (target === '%' || target === 'altcheck' || target === 'alt' || target === 'alts' || target === 'getalts') {
matched = true;
emit(socket, 'console', '/alts OR /altcheck OR /alt OR /getalts [username] - Get a user\'s alts. Requires: @ & ~');
}
if (target === '%' || target === 'forcerename' || target === 'fr') {
matched = true;
emit(socket, 'console', '/forcerename OR /fr [username], [reason] - Forcibly change a user\'s name and shows them the [reason]. Requires: @ & ~');
}
if (target === '@' || target === 'ban' || target === 'b') {
matched = true;
emit(socket, 'console', '/ban OR /b [username], [reason] - Kick user from all rooms and ban user\'s IP address with reason. Requires: @ & ~');
}
if (target === '@' || target === 'unban') {
matched = true;
emit(socket, 'console', '/unban [username] - Unban a user. Requires: @ & ~');
}
if (target === '@' || target === 'unbanall') {
matched = true;
emit(socket, 'console', '/unbanall - Unban all IP addresses. Requires: @ & ~');
}
if (target === '@' || target === 'modlog') {
matched = true;
emit(socket, 'console', '/modlog [n] - If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15. If n is not a number, search the moderator log for "n". Requires: @ & ~');
}
if (target === "%" || target === 'kickbattle ') {
matched = true;
emit(socket, 'console', '/kickbattle [username], [reason] - Kicks an user from a battle with reason. Requires: % @ & ~');
}
if (target === "%" || target === 'warn' || target === 'k') {
matched = true;
emit(socket, 'console', '/warn OR /k [username], [reason] - Warns a user showing them the Pokemon Showdown Rules and [reason] in an overlay. Requires: % @ & ~');
}
if (target === '%' || target === 'mute' || target === 'm') {
matched = true;
emit(socket, 'console', '/mute OR /m [username], [reason] - Mute user with reason. Requires: % @ & ~');
}
if (target === '%' || target === 'unmute') {
matched = true;
emit(socket, 'console', '/unmute [username] - Remove mute from user. Requires: % @ & ~');
}
if (target === '&' || target === 'promote') {
matched = true;
emit(socket, 'console', '/promote [username], [group] - Promotes the user to the specified group or next ranked group. Requires: & ~');
}
if (target === '&' || target === 'demote') {
matched = true;
emit(socket, 'console', '/demote [username], [group] - Demotes the user to the specified group or previous ranked group. Requires: & ~');
}
if (target === '&' || target === 'forcerenameto' || target === 'frt') {
matched = true;
emit(socket, 'console', '/forcerenameto OR /frt [username] - Force a user to choose a new name. Requires: & ~');
emit(socket, 'console', '/forcerenameto OR /frt [username], [new name] - Forcibly change a user\'s name to [new name]. Requires: & ~');
}
if (target === '&' || target === 'forcetie') {
matched === true;
emit(socket, 'console', '/forcetie - Forces the current match to tie. Requires: & ~');
}
if (target === '&' || target === 'declare' ) {
matched = true;
emit(socket, 'console', '/declare [message] - Anonymously announces a message. Requires: & ~');
}
if (target === '&' || target === 'potd' ) {
matched = true;
emit(socket, 'console', '/potd [pokemon] - Sets the Random Battle Pokemon of the Day. Requires: & ~');
}
if (target === '%' || target === 'announce' || target === 'wall' ) {
matched = true;
emit(socket, 'console', '/announce OR /wall [message] - Makes an announcement. Requires: % @ & ~');
}
if (target === '@' || target === 'modchat') {
matched = true;
emit(socket, 'console', '/modchat [off/registered/+/%/@/&/~] - Set the level of moderated chat. Requires: @ & ~');
}
if (target === '~' || target === 'hotpatch') {
matched = true;
emit(socket, 'console', 'Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~');
emit(socket, 'console', 'Hot-patching has greater memory requirements than restarting.');
emit(socket, 'console', '/hotpatch chat - reload chat-commands.js');
emit(socket, 'console', '/hotpatch battles - spawn new simulator processes');
emit(socket, 'console', '/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes');
}
if (target === '~' || target === 'lockdown') {
matched = true;
emit(socket, 'console', '/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~');
}
if (target === '~' || target === 'kill') {
matched = true;
emit(socket, 'console', '/kill - kills the server. Can\'t be done unless the server is in lockdown state. Requires: ~');
}
if (target === 'all' || target === 'help' || target === 'h' || target === '?' || target === 'commands') {
matched = true;
emit(socket, 'console', '/help OR /h OR /? - Gives you help.');
}
if (!target) {
emit(socket, 'console', 'COMMANDS: /msg, /reply, /ip, /rating, /nick, /avatar, /rooms, /whois, /help, /away, /back, /timestamps');
emit(socket, 'console', 'INFORMATIONAL COMMANDS: /data, /groups, /opensource, /avatars, /faq, /rules, /intro, /tiers, /othermetas, /learn, /analysis, /calc (replace / with ! to broadcast. (Requires: + % @ & ~))');
emit(socket, 'console', 'For details on all commands, use /help all');
if (user.group !== config.groupsranking[0]) {
emit(socket, 'console', 'DRIVER COMMANDS: /mute, /unmute, /announce, /forcerename, /alts')
emit(socket, 'console', 'MODERATOR COMMANDS: /ban, /unban, /unbanall, /ip, /modlog, /redirect, /kick');
emit(socket, 'console', 'LEADER COMMANDS: /promote, /demote, /forcerenameto, /forcewin, /forcetie, /declare');
emit(socket, 'console', 'For details on all moderator commands, use /help @');
}
emit(socket, 'console', 'For details of a specific command, use something like: /help data');
} else if (!matched) {
emit(socket, 'console', 'The command "/'+target+'" was not found. Try /help for general help');
}
return false;
break;
default:
// Check for mod/demod/admin/deadmin/etc depending on the group ids
for (var g in config.groups) {
if (cmd === config.groups[g].id) {
return parseCommand(user, 'promote', toUserid(target) + ',' + g, room, socket);
} else if (cmd === 'de' + config.groups[g].id || cmd === 'un' + config.groups[g].id) {
var nextGroup = config.groupsranking[config.groupsranking.indexOf(g) - 1];
if (!nextGroup) nextGroup = config.groupsranking[0];
return parseCommand(user, 'demote', toUserid(target) + ',' + nextGroup, room, socket);
}
}
}
if (message.substr(0,1) === '/' && cmd) {
// To guard against command typos, we now emit an error message
emit(socket, 'console', 'The command "/'+cmd+'" was unrecognized. To send a message starting with "/'+cmd+'", type "//'+cmd+'".');
return false;
}
// chat moderation
if (!canTalk(user, room, socket)) {
return false;
}
// hardcoded low quality website
if (/\bnimp\.org\b/i.test(message)) return false;
// remove zalgo
message = message.replace(/[\u0300-\u036f]{3,}/g,'');
if (config.chatfilter) {
return config.chatfilter(user, room, socket, message);
}
if (tourActive) {
checkForWins();
}
return message;
}
/**
* Can this user talk?
* Pass the corresponding socket to give the user an error, if not
*/
function canTalk(user, room, socket) {
if (!user.named) return false;
if (user.locked) {
if (socket) emit(socket, 'console', 'You are locked from talking in chat.');
return false;
}
if (user.muted && room.id === 'lobby') {
if (socket) emit(socket, 'console', 'You are muted and cannot talk in the lobby.');
return false;
}
if (room.id === 'lobby' && user.blockLobbyChat) {
if (socket) emit(socket, 'console', "You can't send messages while blocking lobby chat.");
return false;
}
if (config.modchat && room.id === 'lobby') {
if (config.modchat === 'crash') {
if (!user.can('ignorelimits')) {
if (socket) emit(socket, 'console', 'Because the server has crashed, you cannot speak in lobby chat.');
return false;
}
} else {
if (!user.authenticated && config.modchat === true) {
if (socket) emit(socket, 'console', 'Because moderated chat is set, you must be registered to speak in lobby chat. To register, simply win a rated battle by clicking the look for battle button');
return false;
} else if (config.groupsranking.indexOf(user.group) < config.groupsranking.indexOf(config.modchat)) {
var groupName = config.groups[config.modchat].name;
if (!groupName) groupName = config.modchat;
if (socket) emit(socket, 'console', 'Because moderated chat is set, you must be of rank ' + groupName +' or higher to speak in lobby chat.');
return false;
}
}
}
return true;
}
function showOrBroadcastStart(user, cmd, room, socket, message) {
if (cmd.substr(0,1) === '!') {
if (!user.can('broadcast') || user.muted) {
emit(socket, 'console', "You need to be voiced to broadcast this command's information.");
emit(socket, 'console', "To see it for yourself, use: /"+message.substr(1));
} else if (canTalk(user, room, socket)) {
room.add('|c|'+user.getIdentity()+'|'+message);
}
}
}
function showOrBroadcast(user, cmd, room, socket, rawMessage) {
if (cmd.substr(0,1) !== '!') {
sendData(socket, '>'+room.id+'\n|raw|'+rawMessage);
} else if (user.can('broadcast') && canTalk(user, room)) {
room.addRaw(rawMessage);
}
}
function getDataMessage(target) {
var pokemon = Tools.getTemplate(target);
var item = Tools.getItem(target);
var move = Tools.getMove(target);
var ability = Tools.getAbility(target);
var atLeastOne = false;
var response = [];
if (pokemon.exists) {
response.push('|c|~|/data-pokemon '+pokemon.name);
atLeastOne = true;
}
if (ability.exists) {
response.push('|c|~|/data-ability '+ability.name);
atLeastOne = true;
}
if (item.exists) {
response.push('|c|~|/data-item '+item.name);
atLeastOne = true;
}
if (move.exists) {
response.push('|c|~|/data-move '+move.name);
atLeastOne = true;
}
if (!atLeastOne) {
response.push("||No pokemon, item, move, or ability named '"+target+"' was found. (Check your spelling?)");
}
return response;
}
function splitTarget(target, exactName) {
var commaIndex = target.indexOf(',');
if (commaIndex < 0) {
return [Users.get(target, exactName), '', target];
}
var targetUser = Users.get(target.substr(0, commaIndex), exactName);
if (!targetUser) {
targetUser = null;
}
return [targetUser, target.substr(commaIndex+1).trim(), target.substr(0, commaIndex)];
}
function logModCommand(room, result, noBroadcast) {
if (!noBroadcast) room.add(result);
modlog.write('['+(new Date().toJSON())+'] ('+room.id+') '+result+'\n');
}
function getRandMessage(user){
var numMessages = 44; // numMessages will always be the highest case # + 1
var message = '~~ ';
switch(Math.floor(Math.random()*numMessages)){
case 0: message = message + user.name + ' was squished by AOrtega\'s large behind!';
break;
case 1: message = message + user.name + ' was eaten by SmashBrosBrawl!';
break;
case 2: message = message + user.name + ' was raped by AOrtega!';
break;
case 3: message = message + user.name + ' was Volt Tackled by piiiikachuuu!';
break;
case 4: message = message + user.name + ' was mauled by Leader Wolf!';
break;
case 5: message = message + user.name + ' was kidnapped by iSmogoon!';
break;
case 6: message = message + user.name + ' was taken away by Hypno!';
break;
case 7: message = message + user.name + ' was thrown in kupo\'s Closet!';
break;
case 8: message = message + user.name + ' was eaten alive by Sharpedos!';
break;
case 9: message = message + user.name + ' was beaten up by an eskimo!';
break;
case 10: message = message + user.name + ' found the meaning of life!';
break;
case 11: message = message + user.name + ' was OHKOed by Shuckle!';
break;
case 12: message = message + user.name + ' was thrown out a window by Aikenka!';
break;
case 13: message = message + user.name + ' was licked by a pandaw!';
break;
case 14: message = message + user.name + ' is blasting off again!';
break;
case 15: message = message + user.name + ' was blown up by iSmogoon\'s experiment!';
break;
case 16: message = message + user.name + ' is blasting off again!';
break;
case 17: message = message + 'A large Ariados came down and picked up' + user.name + ' !';
break;
case 18: message = message + user.name + ' was toxic stalled by Gliscor!';
break;
case 19: message = message + user.name + ' was flinched by Jirachii!';
break;
case 20: message = message + user.name + ' had their spirit sucked away by Shedinja!';
break;
case 21: message = message + user.name + ' was slapped by EnerG\'s trout of justice!';
break;
case 22: message = message + user.name + ' peered through the hole on Shedinja\'s back';
break;
case 23: message = message + user.name + ' recieved judgment from the almighty Arceus!';
break;
case 24: message = message + user.name + ' used Final Gambit and missed!';
break;
case 25: message = message + user.name + ' pissed off a Gyarados!';
break;
case 26: message = message + user.name + ' was taken in Jessica Daniella\'s black van';
break;
case 27: message = message + user.name + ' was thrown off a cliff by Nollan.';
break;
case 28: message = message + user.name + ' got lost in the illusion of reality.';
break;
case 29: message = message + user.name + ' was banned for stupidity.';
break;
case 30: message = message + 'The Immortal accidently kicked ' + user.name + ' from the server!';
break;
case 31: message = message + user.name + ' was crushed by Cynthia\'s Garchomp!';
break;
case 32: message = message + user.name + ' died making love to an Excadrill!';
break;
default: message = message + user.name + ' was burried in Smogoon\'s homework!';
};
message = message + ' ~~';
return message;
}
function splitArgs(args){
args = args.replace(/\s+/gm, " "); // Normalise spaces
var result = args.split(',');
for (var r in result)
result[r] = result[r].trim();
return result;
}
function MD5(f){function i(b,c){var d,e,f,g,h;f=b&2147483648;g=c&2147483648;d=b&1073741824;e=c&1073741824;h=(b&1073741823)+(c&1073741823);return d&e?h^2147483648^f^g:d|e?h&1073741824?h^3221225472^f^g:h^1073741824^f^g:h^f^g}function j(b,c,d,e,f,g,h){b=i(b,i(i(c&d|~c&e,f),h));return i(b<<g|b>>>32-g,c)}function k(b,c,d,e,f,g,h){b=i(b,i(i(c&e|d&~e,f),h));return i(b<<g|b>>>32-g,c)}function l(b,c,e,d,f,g,h){b=i(b,i(i(c^e^d,f),h));return i(b<<g|b>>>32-g,c)}function m(b,c,e,d,f,g,h){b=i(b,i(i(e^(c|~d),
f),h));return i(b<<g|b>>>32-g,c)}function n(b){var c="",e="",d;for(d=0;d<=3;d++)e=b>>>d*8&255,e="0"+e.toString(16),c+=e.substr(e.length-2,2);return c}var g=[],o,p,q,r,b,c,d,e,f=function(b){for(var b=b.replace(/\r\n/g,"\n"),c="",e=0;e<b.length;e++){var d=b.charCodeAt(e);d<128?c+=String.fromCharCode(d):(d>127&&d<2048?c+=String.fromCharCode(d>>6|192):(c+=String.fromCharCode(d>>12|224),c+=String.fromCharCode(d>>6&63|128)),c+=String.fromCharCode(d&63|128))}return c}(f),g=function(b){var c,d=b.length;c=
d+8;for(var e=((c-c%64)/64+1)*16,f=Array(e-1),g=0,h=0;h<d;)c=(h-h%4)/4,g=h%4*8,f[c]|=b.charCodeAt(h)<<g,h++;f[(h-h%4)/4]|=128<<h%4*8;f[e-2]=d<<3;f[e-1]=d>>>29;return f}(f);b=1732584193;c=4023233417;d=2562383102;e=271733878;for(f=0;f<g.length;f+=16)o=b,p=c,q=d,r=e,b=j(b,c,d,e,g[f+0],7,3614090360),e=j(e,b,c,d,g[f+1],12,3905402710),d=j(d,e,b,c,g[f+2],17,606105819),c=j(c,d,e,b,g[f+3],22,3250441966),b=j(b,c,d,e,g[f+4],7,4118548399),e=j(e,b,c,d,g[f+5],12,1200080426),d=j(d,e,b,c,g[f+6],17,2821735955),c=
j(c,d,e,b,g[f+7],22,4249261313),b=j(b,c,d,e,g[f+8],7,1770035416),e=j(e,b,c,d,g[f+9],12,2336552879),d=j(d,e,b,c,g[f+10],17,4294925233),c=j(c,d,e,b,g[f+11],22,2304563134),b=j(b,c,d,e,g[f+12],7,1804603682),e=j(e,b,c,d,g[f+13],12,4254626195),d=j(d,e,b,c,g[f+14],17,2792965006),c=j(c,d,e,b,g[f+15],22,1236535329),b=k(b,c,d,e,g[f+1],5,4129170786),e=k(e,b,c,d,g[f+6],9,3225465664),d=k(d,e,b,c,g[f+11],14,643717713),c=k(c,d,e,b,g[f+0],20,3921069994),b=k(b,c,d,e,g[f+5],5,3593408605),e=k(e,b,c,d,g[f+10],9,38016083),
d=k(d,e,b,c,g[f+15],14,3634488961),c=k(c,d,e,b,g[f+4],20,3889429448),b=k(b,c,d,e,g[f+9],5,568446438),e=k(e,b,c,d,g[f+14],9,3275163606),d=k(d,e,b,c,g[f+3],14,4107603335),c=k(c,d,e,b,g[f+8],20,1163531501),b=k(b,c,d,e,g[f+13],5,2850285829),e=k(e,b,c,d,g[f+2],9,4243563512),d=k(d,e,b,c,g[f+7],14,1735328473),c=k(c,d,e,b,g[f+12],20,2368359562),b=l(b,c,d,e,g[f+5],4,4294588738),e=l(e,b,c,d,g[f+8],11,2272392833),d=l(d,e,b,c,g[f+11],16,1839030562),c=l(c,d,e,b,g[f+14],23,4259657740),b=l(b,c,d,e,g[f+1],4,2763975236),
e=l(e,b,c,d,g[f+4],11,1272893353),d=l(d,e,b,c,g[f+7],16,4139469664),c=l(c,d,e,b,g[f+10],23,3200236656),b=l(b,c,d,e,g[f+13],4,681279174),e=l(e,b,c,d,g[f+0],11,3936430074),d=l(d,e,b,c,g[f+3],16,3572445317),c=l(c,d,e,b,g[f+6],23,76029189),b=l(b,c,d,e,g[f+9],4,3654602809),e=l(e,b,c,d,g[f+12],11,3873151461),d=l(d,e,b,c,g[f+15],16,530742520),c=l(c,d,e,b,g[f+2],23,3299628645),b=m(b,c,d,e,g[f+0],6,4096336452),e=m(e,b,c,d,g[f+7],10,1126891415),d=m(d,e,b,c,g[f+14],15,2878612391),c=m(c,d,e,b,g[f+5],21,4237533241),
b=m(b,c,d,e,g[f+12],6,1700485571),e=m(e,b,c,d,g[f+3],10,2399980690),d=m(d,e,b,c,g[f+10],15,4293915773),c=m(c,d,e,b,g[f+1],21,2240044497),b=m(b,c,d,e,g[f+8],6,1873313359),e=m(e,b,c,d,g[f+15],10,4264355552),d=m(d,e,b,c,g[f+6],15,2734768916),c=m(c,d,e,b,g[f+13],21,1309151649),b=m(b,c,d,e,g[f+4],6,4149444226),e=m(e,b,c,d,g[f+11],10,3174756917),d=m(d,e,b,c,g[f+2],15,718787259),c=m(c,d,e,b,g[f+9],21,3951481745),b=i(b,o),c=i(c,p),d=i(d,q),e=i(e,r);return(n(b)+n(c)+n(d)+n(e)).toLowerCase()};
var colorCache = {};
function hashColor(name) {
if (colorCache[name]) return colorCache[name];
var hash = MD5(name);
var H = parseInt(hash.substr(4, 4), 16) % 360;
var S = parseInt(hash.substr(0, 4), 16) % 50 + 50;
var L = parseInt(hash.substr(8, 4), 16) % 20 + 25;
var m1, m2, hue;
var r, g, b
S /=100;
L /= 100;
if (S == 0)
r = g = b = (L * 255).toString(16);
else {
if (L <= 0.5)
m2 = L * (S + 1);
else
m2 = L + S - L * S;
m1 = L * 2 - m2;
hue = H / 360;
r = HueToRgb(m1, m2, hue + 1/3);
g = HueToRgb(m1, m2, hue);
b = HueToRgb(m1, m2, hue - 1/3);
}
colorCache[name] = '#' + r + g + b;
return colorCache[name];
}
function HueToRgb(m1, m2, hue) {
var v;
if (hue < 0)
hue += 1;
else if (hue > 1)
hue -= 1;
if (6 * hue < 1)
v = m1 + (m2 - m1) * hue * 6;
else if (2 * hue < 1)
v = m2;
else if (3 * hue < 2)
v = m1 + (m2 - m1) * (2/3 - hue) * 6;
else
v = m1;
return (255 * v).toString(16);
}
function splittyDoodles(target) {
var cmdArr = target.split(",");
for(var i = 0; i < cmdArr.length; i++) {
cmdArr[i] = cmdArr[i].trim();
}
var guy = Users.get(cmdArr[0]);
if (!guy || !guy.connected) {
cmdArr[0] = null;
}
return cmdArr;
}
function splittyDiddles(target) {
var cmdArr = target.split(",");
for(var i = 0; i < cmdArr.length; i++) {
cmdArr[i] = cmdArr[i].trim();
}
return cmdArr;
}
function stripBrackets(target) {
var cmdArr = target.split("<");
for(var i = 0; i < cmdArr.length; i++) {
cmdArr[i] = cmdArr[i].trim();
}
return cmdArr[0];
}
function stripBrackets2(target) {
var cmdArr = target.split(">");
for(var i = 0; i < cmdArr.length; i++) {
cmdArr[i] = cmdArr[i].trim();
}
return cmdArr[0];
}
function noHTMLforyou(target) {
var htmlcheck = false;
var text = target;
for(var i = 0; i < text.length; i++) {
if ((text.charAt(i) === '<') || (text.charAt(i) === '>')) {
htmlcheck = true;
}
}
return htmlcheck;
}
function addToTour(tourGuyId) {
var alreadyExistsTour = false;
for( var i=0; i < tourSignup.length; i++) {
if(tourGuyId === tourSignup[i]) {
alreadyExistsTour = true;
}
}
if (alreadyExistsTour) return false;
var tourUserOb = Users.get(tourGuyId);
if (!tourUserOb) return false;
tourSignup.push(tourGuyId);
tourUserOb.tourRole = 'participant';
return true;
}
//shuffles list in-place
function shuffle(list) {
var i, j, t;
for (i = 1; i < list.length; i++) {
j = Math.floor(Math.random()*(1+i)); // choose j in [0..i]
if (j != i) {
t = list[i]; // swap list[i] and list[j]
list[i] = list[j];
list[j] = t;
}
}
return list;
}
function beginTour() {
if(tourSignup.length > tourSize) {
return false;
} else {
tourRound = 0;
tourSigyn = false;
tourActive = true;
beginRound();
return true;
}
}
function checkForWins() {
var p1win = '';
var p2win = '';
var tourBrackCur = [];
for(var i = 0;i < tourBracket.length;i++) {
tourBrackCur = tourBracket[i];
p1win = Users.get(tourBrackCur[0]);
p2win = Users.get(tourBrackCur[1]);
//Rooms.lobby.addRaw(' - ' + tourBrackCur[0] + ' , ' + tourBrackCur[1]);
if (tourMoveOn[i] == '') {
/*
if (((!p2win) || (tourBrackCur[1] = 'bye')) && (p1win.tourRole === 'winner')) {
p1win.tourRole = '';
p2win.tourOpp = '';
tourMoveOn.push(tourBrackCur[0]);
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[0] + '</b> has won their match and will move on to the next round!');
}
if (((!p2win) || (tourBrackCur[0] = 'bye')) && (p2win.tourRole === 'winner')) {
p2win.tourRole = '';
p2win.tourOpp = '';
tourMoveOn.push(tourBrackCur[1]);
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[1] + '</b> has won their match and will move on to the next round!');
}*/
if (tourBrackCur[0] === 'bye') {
p2win.tourRole = '';
tourMoveOn[i] = tourBrackCur[1];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[1] + '</b> has recieved a bye and will move on to the next round!');
}
if (tourBrackCur[1] === 'bye') {
p1win.tourRole = '';
tourMoveOn[i] = tourBrackCur[0];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[0] + '</b> has recieved a bye and will move on to the next round!');
}
if (!p1win) {
p2win.tourRole = '';
tourMoveOn[i] = tourBrackCur[1];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[1] + '</b> has recieved a bye and will move on to the next round!');
}
if (!p2win) {
p1win.tourRole = '';
tourMoveOn[i] = tourBrackCur[0];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[0] + '</b> has recieved a bye and will move on to the next round!');
}
if ((p1win.tourRole === 'winner') && (tourMoveOn.length == 1)) {
p1win.tourRole = '';
tourMoveOn[i] = tourBrackCur[0];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[0] + '</b> has beat ' + tourBrackCur[1] + '!');
finishTour(tourBrackCur[0],tourBrackCur[1]);
} else if ((p2win.tourRole === 'winner') && (tourMoveOn.length == 1)) {
p2win.tourRole = '';
tourMoveOn[i] = tourBrackCur[1];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[1] + '</b> has beat ' + tourBrackCur[0] + '!');
finishTour(tourBrackCur[1],tourBrackCur[0]);
}
if (p1win.tourRole === 'winner') {
p1win.tourRole = '';
tourMoveOn[i] = tourBrackCur[0];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[0] + '</b> has beat ' + tourBrackCur[1] + ' and will move on to the next round!');
} else if (p2win.tourRole === 'winner') {
p2win.tourRole = '';
tourMoveOn[i] = tourBrackCur[1];
Rooms.lobby.addRaw(' - <b>' + tourBrackCur[1] + '</b> has beat ' + tourBrackCur[0] + ' and will move on to the next round!');
}
}
}
//Rooms.lobby.addRaw(tourMoveOn + ', ' + tourBracket);
var moveOnCheck = true;
for (var i = 0;i < tourRoundSize;i++) {
if (tourMoveOn[i] === '') {
moveOnCheck = false;
}
}
if (!tourActive) {
return;
}
if (moveOnCheck) {
/*if (tourMoveOn.length == 1) {
finishTour();
return;
}*/
//Rooms.lobby.addRaw(tourMoveOn + '- ' + tourBracket);
tourSignup = [];
for (var i = 0;i < tourRoundSize;i++) {
if (!(tourMoveOn[i] === 'bye')) {
tourSignup.push(tourMoveOn[i]);
}
}
tourSignup = tourMoveOn;
beginRound();
}
}
function beginRound() {
for(var i = 0;i < tourSignup.length;i++) {
var participantSetter = Users.get(tourSignup[i]);
if (!participantSetter) {
tourSignup[i] = 'bye';
} else {
participantSetter.tourRole = 'participant';
}
}
tourBracket = [];
var sList = tourSignup;
shuffle(sList);
do
{
if (sList.length == 1) {
tourBracket.push([sList.pop(),'bye']);
} else if (sList.length > 1) {
tourBracket.push([sList.pop(),sList.pop()]);
}
}
while (sList.length > 0);
tourRound++;
tourRoundSize = tourBracket.length;
//poopycakes
tourMoveOn = [];
for (var i = 0;i < tourRoundSize;i++) {
tourMoveOn.push('');
}
if (tourRound == 1) {
Rooms.lobby.addRaw('<hr /><h3><font color="green">The ' + tourTier + ' tournament has begun!</h3></font><font color="blue"><b>TIER:</b></font> ' + tourTier );
} else {
Rooms.lobby.addRaw('<hr /><h3><font color="green">Round '+ tourRound +'!</font></h3><font color="blue"><b>TIER:</b></font> ' + tourTier );
}
var tourBrackCur;
var p1OppSet;
var p2OppSet;
for(var i = 0;i < tourBracket.length;i++) {
tourBrackCur = tourBracket[i];
if (!(tourBrackCur[0] === 'bye') && !(tourBrackCur[1] === 'bye')) {
Rooms.lobby.addRaw(' - ' + tourBrackCur[0] + ' VS ' + tourBrackCur[1]);
p1OppSet = Users.get(tourBrackCur[0]);
p1OppSet.tourOpp = tourBrackCur[1];
p2OppSet = Users.get(tourBrackCur[1]);
p2OppSet.tourOpp = tourBrackCur[0];
} else if (tourBrackCur[0] === 'bye') {
Rooms.lobby.addRaw(' - ' + tourBrackCur[1] + ' has recieved a bye!');
var autoWin = Users.get(tourBrackCur[1]);
autoWin.tourRole = '';
tourMoveOn[i] = tourBrackCur[0];
} else if (tourBrackCur[1] === 'bye') {
Rooms.lobby.addRaw(' - ' + tourBrackCur[0] + ' has recieved a bye!');
var autoWin = Users.get(tourBrackCur[0]);
autoWin.tourRole = '';
tourMoveOn[i] = tourBrackCur[0];
} else {
Rooms.lobby.addRaw(' - ' + tourBrackCur[0] + ' VS ' + tourBrackCur[1]);
}
}
var tourfinalcheck = tourBracket[0];
if ((tourBracket.length == 1) && (!(tourfinalcheck[0] === 'bye') || !(tourfinalcheck[1] === 'bye'))) {
Rooms.lobby.addRaw('This match is the finals! Good luck!');
}
Rooms.lobby.addRaw('<hr />');
return true;
}
function finishTour(first,second) {
var winnerUser = Users.get(first);
var winnerName = winnerUser.name;
//var winnerPrize = tourbonus * (50 + (25 * tourSize));
if (second === 'dud') {
var secondName = 'n/a';
} else {
var secondUser = Users.get(second);
var secondName = secondUser.name;
}
//var secondPrize = tourbonus * (50 + (10 * tourSize));
/*updateMoney(first, winnerPrize);
if (!(second === 'dud')) {
updateMoney(second, secondPrize);
}*/
Rooms.lobby.addRaw('<h2><font color="green">Congratulations <font color="black">' + winnerName + '</font>! You have won the ' + tourTier + ' Tournament!</font></h2>' + '<br><font color="blue"><b>SECOND PLACE:</b></font> ' + secondName + '<hr />');
tourActive = false;
tourSigyn = false;
tourBracket = [];
tourSignup = [];
tourTier = '';
tourRound = 0;
tourSize = 0;
tourMoveOn = [];
tourRoundSize = 0;
return true;
}
function getTourColor(target) {
var colorGuy = -1;
var tourGuy;
for(var i=0;i<tourBracket.length;i++) {
tourGuy = tourBracket[i];
if ((tourGuy[0] === target) || (tourGuy[1] === target)) {
colorGuy = i;
}
}
if (colorGuy == -1) {
return target;
}
if (tourMoveOn[colorGuy] == '') {
return '<b>'+target+'</b>';
} else if (tourMoveOn[colorGuy] === target) {
return '<b><font color="green">'+target+'</font></b>';
} else {
return '<b><font color="red">'+target+'</font></b>';
}
}
parseCommandLocal.uncacheTree = function(root) {
var uncache = [require.resolve(root)];
do {
var newuncache = [];
for (var i = 0; i < uncache.length; ++i) {
if (require.cache[uncache[i]]) {
newuncache.push.apply(newuncache,
require.cache[uncache[i]].children.map(function(module) {
return module.filename;
})
);
delete require.cache[uncache[i]];
}
}
uncache = newuncache;
} while (uncache.length > 0);
};
// This function uses synchronous IO in order to keep it relatively simple.
// The function takes about 0.023 seconds to run on one tested computer,
// which is acceptable considering how long the server takes to start up
// anyway (several seconds).
parseCommandLocal.computeServerVersion = function() {
/**
* `filelist.txt` is a list of all the files in this project. It is used
* for computing a checksum of the project for the /version command. This
* information cannot be determined at runtime because the user may not be
* using a git repository (for example, the user may have downloaded an
* archive of the files).
*
* `filelist.txt` is generated by running `git ls-files > filelist.txt`.
*/
var filenames;
try {
var data = fs.readFileSync('filelist.txt', {encoding: 'utf8'});
filenames = data.split('\n');
} catch (e) {
return 0;
}
var hash = crypto.createHash('md5');
for (var i = 0; i < filenames.length; ++i) {
try {
hash.update(fs.readFileSync(filenames[i]));
} catch (e) {}
}
return hash.digest('hex');
};
parseCommandLocal.serverVersion = parseCommandLocal.computeServerVersion();
exports.parseCommand = parseCommandLocal;
|
define([], function() {
function DashboardCtrl($scope, $http) {
$scope.clusters = [];
$http.get('/v1/clusters/').success(function(json) {
$scope.clusters = json;
});
};
DashboardCtrl.$inject = ['$scope', '$http'];
function RMonCtrls($scope) {
$scope.DashboardCtrl = DashboardCtrl;
};
RMonCtrls.$inject = ['$scope'];
return {
RMonCtrls: RMonCtrls
};
});
|
import React, { Component } from 'react';
import Cookies from 'universal-cookie';
import { Link } from 'react-router-dom';
import Section from 'shared/components/section/section';
import styles from './dashboard.css';
class Dashboard extends Component {
state = {
mentor: null
}
componentWillMount() {
const cookies = new Cookies();
this.setState({ mentor: cookies.get('mentor') });
}
renderLinks = () => {
const { mentor } = this.state;
return mentor === 'true'
? (
<div>
<h1 className={styles.link}>
<Link to="/mentor/requests">View Requests</Link>
</h1>
<h1 className={styles.link}>
<Link to="/squads/new-squad">Create a Squad</Link>
</h1>
<h1 className={styles.link}>
<Link to="/squads">View Squads</Link>
</h1>
<h1 className={styles.link}>
<Link to="/mentors">View Mentors</Link>
</h1>
</div>
) : (
<div>
<h1 className={styles.link}>
<Link to="/mentor-request">Request Help</Link>
</h1>
<h1 className={styles.link}>
<Link to="/squads">Join a Squad</Link>
</h1>
<h1 className={styles.link}>
<Link to="/mentors">View Mentors</Link>
</h1>
</div>
);
}
render() {
return (
<Section title="What would you like to do?" theme="white">
{this.renderLinks()}
</Section>
);
}
}
export default Dashboard;
|
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
import Layout from "../../components/layout"
/*
1. write a query to get image
2. spread the returned object into the fluid prop and override the aspectRatio
*/
export default () => {
const data = useStaticQuery(graphql`
query {
file(relativePath: { eq: "corgi.jpg" }) {
childImageSharp {
fluid {
base64
aspectRatio # returns the images aspectRatio
src
srcSet
sizes
}
}
}
}
`)
return (
<Layout>
<Img
fluid={{
...data.file.childImageSharp.fluid,
aspectRatio: 1, // override the original returned aspectRatio
}}
alt="A corgi smiling happily"
/>
</Layout>
)
}
|
(function () {
'use strict';
angular
.module('renovates')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('renovates', {
abstract: true,
url: '/renovates',
template: '<ui-view/>'
})
.state('renovates.list', {
url: '',
templateUrl: 'modules/renovates/client/views/list-renovates.client.view.html',
controller: 'RenovatesListController',
controllerAs: 'vm',
data: {
pageTitle: 'Renovates List'
}
})
.state('renovates.create', {
url: '/create',
templateUrl: 'modules/renovates/client/views/form-renovate.client.view.html',
controller: 'RenovatesController',
controllerAs: 'vm',
resolve: {
renovateResolve: newRenovate
},
data: {
roles: ['dataentry', 'admin', 'superuser'],
pageTitle: 'Renovates Create'
}
})
.state('renovates.edit', {
url: '/:renovateId/edit',
templateUrl: 'modules/renovates/client/views/form-renovate.client.view.html',
controller: 'RenovatesController',
controllerAs: 'vm',
resolve: {
renovateResolve: getRenovate
},
data: {
roles: ['user', 'admin','viewer','approver','dataentry', 'superuser'],
pageTitle: 'Edit Renovate {{ renovateResolve.name }}'
}
})
.state('renovates.view', {
url: '/:renovateId',
templateUrl: 'modules/renovates/client/views/view-renovate.client.view.html',
controller: 'RenovatesController',
controllerAs: 'vm',
resolve: {
renovateResolve: getRenovate
},
data: {
pageTitle: 'Renovate {{ renovateResolve.name }}'
}
});
}
getRenovate.$inject = ['$stateParams', 'RenovatesService'];
function getRenovate($stateParams, RenovatesService) {
return RenovatesService.get({
renovateId: $stateParams.renovateId
}).$promise;
}
newRenovate.$inject = ['RenovatesService'];
function newRenovate(RenovatesService) {
return new RenovatesService();
}
}());
|
export const REGISTRATION = {
UPDATE_CODE: 'UPDATE_CODE',
REGISTER: 'REGISTER',
SET_ERROR: 'SET_ERROR',
SET_REGISTERED: 'SET_REGISTERED',
};
export const MAP_CONTROLLER = {
DATASET: 'DATASET',
IS_PLAYING: 'IS_PLAYING',
SET_REGION: 'SET_REGION',
SET_YEAR: 'SET_YEAR',
STOP_ENABLED: 'STOP_ENABLED',
};
|
/**
* @Created by kaicui(https://github.com/wbpmrck).
* @Date:2013-08-27 19:56
* @Desc: 实现部分ECMAScript 5里新增的实用功能
* 1、部分功能可能会对已有的Built-in对象进行侵入
* 2、检测到浏览器已经支持的话,会什么都不做
* @Change History:
--------------------------------------------
@created:|kaicui| 2013-08-27 19:56.
--------------------------------------------
*/
;
//Array
if(!Array.prototype.forEach){
/**
@param {Function} iterator
@param {Object} [thisObject]
@return void
*/
Array.prototype.forEach = function(iterator,thisObject){
for(var i=0,j=this.length;i<j;i++){
var _item = this[i];
iterator&&iterator.call(thisObject||this,_item,i,this)
}
}
}
if(!Array.prototype.filter){
/**
*
* @param filter
* @param thisObject
* @return {Array}
*/
Array.prototype.filter = function(filter,thisObject){
var _result =[];
for(var i=0,j=this.length;i<j;i++){
var _item = this[i];
if(filter&&filter.call(thisObject||this,_item,i,this)){
_result.push(_item);
}
}
return _result;
}
}
if(!Array.prototype.isArray){
Array.prototype.isArray = function(obj){
return Object.prototype.toString.apply(obj) === '[object Array]';
}
}
// 实现 ECMA-262, Edition 5, 15.4.4.19
// 参考: http://es5.github.com/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. 将O赋值为调用map方法的数组.
var O = Object(this);
// 2.将len赋值为数组O的长度.
var len = O.length >>> 0;
// 4.如果callback不是函数,则抛出TypeError异常.
if ({}.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
// 5. 如果参数thisArg有值,则将T赋值为thisArg;否则T为undefined.
if (thisArg) {
T = thisArg;
}
// 6. 创建新数组A,长度为原数组O长度len
A = new Array(len);
// 7. 将k赋值为0
k = 0;
// 8. 当 k < len 时,执行循环.
while(k < len) {
var kValue, mappedValue;
//遍历O,k为原数组索引
if (k in O) {
//kValue为索引k对应的值.
kValue = O[ k ];
// 执行callback,this指向T,参数有三个.分别是kValue:值,k:索引,O:原数组.
mappedValue = callback.call(T, kValue, k, O);
// 返回值添加到新书组A中.
A[ k ] = mappedValue;
}
// k自增1
k++;
}
// 9. 返回新数组A
return A;
};
}
//Function(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fbind)
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
} |
/**
* Using this ajax function you can post to a provider.
*
* @param provider The provider you want to post(twit, etc).
* @param id The id of the entry that contains the value text you want to post.
* This id also shows the container where the reply message will appear.
*/
function postToProvider(provider, id) {
var valueEl = document.getElementById("entry" + id);
var statusEl = document.getElementById("responseStatus" + id);
var gameEl = document.getElementById("gameId");
var nationEl = document.getElementById("nationId" + id);
var newEl = document.getElementById("newId" + id);
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText == 'ok') {
statusEl.innerHTML = "posted!";
} else if (xmlhttp.responseText.indexOf("connect_with_twitter") != -1) {
document.getElementById('connectToTwitter').submit();
} else if (xmlhttp.responseText.indexOf('connect_with_facebook') != -1) {
document.getElementById('connectToFacebook').submit();
} else {
statusEl.innerHTML = "fail..";
}
}
};
var gameId = 0;
if (gameEl != null) {
gameId = gameEl.value;
}
var newId = 0;
if (newEl != null) {
newId = newEl.value;
}
var nationId = 0;
if (nationEl != null) {
nationId = nationEl.value;
}
statusEl.innerHTML = "wait..";
var startsWith = "/";
if (getDomainName() == "localhost") {
startsWith = startsWith + "empire-web/";
}
var urlToCall = startsWith + "1805/social/" + provider + "/feed";
// alert(urlToCall);
xmlhttp.open("POST", urlToCall, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("message=" + valueEl.value + "&gameId=" + gameId + "&newId=" + newId + "&nationId=" + nationId);
}
/**
* Returns the domain name.
* Needs to determine
* if we are localhost or public.
*/
function getDomainName() {
return window.location.hostname;
}
|
'use strict';
const async = require('async'),
request = require('request'),
file = require('file'),
rdfParser = require('./lib/rdf-parser.js'),
work = async.queue(function(path, done){
rdfParser(path, function(err, doc){
request(
{
method: 'PUT',
url: 'http://localhost:5984/books/' + doc._id,
json: doc
},
function(err, res, body){
if(err){
throw Error(err);
}
console.log(res.statusCode, body);
done();
}
)
console.log(doc);
done();
});
}, 1000);
console.log('beginning directory walk');
file.walk(__dirname + '/cache', function(err, dirPath, dirs, files){
files.forEach(function(path){
work.push(path);
});
}); |
import path from 'path';
import Express from 'express';
import bodyParser from 'body-parser';
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { StaticRouter as Router } from 'react-router';
import { renderToString } from 'react-dom/server';
import createReducer from './reducers';
import Routes from './app/routes';
const app = Express();
const port = 3001;
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
function renderFullPage(html, preloadedState) {
const bundles = process.env.NODE_ENV === 'production' ?
'<script src="bundle.js"></script>' :
`
<script src="http://localhost:3000/bundle.js" type="text/javascript"></script>
<script src="http://localhost:3000/webpack-dev-server.js" type="text/javascript"></script>
`;
return `
<!doctype html>
<html>
<head>
<title>My Home Site</title>
</head>
<body>
<div id="root">${html}</div>
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
</script>
${bundles}
</body>
</html>
`;
}
function handleRender(req, res) {
const payload = req.body;
const appReducer = createReducer();
// create a new redux store instance
const store = createStore(appReducer);
// reset initial state
store.dispatch({
type: 'REQUEST_BLOGS_SUCCESS',
payload,
});
const html = renderToString(
<Provider store={store}>
<Router location="/" context={{}}>
<Routes />
</Router>
</Provider>
);
const preloadedState = store.getState();
res.send(renderFullPage(html, preloadedState));
}
app.post('/ssr', handleRender);
app.listen(port);
|
const {
registerModel
} = require('../Registry');
exports.Model = (Class) => {
console.log('Model Class', Class.config, Class.schema, Class.name);
registerModel(Class);
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _transaction = _interopRequireDefault(require("../../transaction"));
var _lodash = require("lodash");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = require('debug')('knex:tx');
class Transaction_MySQL2 extends _transaction.default {}
(0, _lodash.assign)(Transaction_MySQL2.prototype, {
query(conn, sql, status, value) {
const t = this;
const q = this.trxClient.query(conn, sql).catch(err => err.code === 'ER_SP_DOES_NOT_EXIST', () => {
this.trxClient.logger.warn('Transaction was implicitly committed, do not mix transactions and ' + 'DDL with MySQL (#805)');
}).catch(function (err) {
status = 2;
value = err;
t._completed = true;
debug('%s error running transaction query', t.txid);
}).tap(function () {
if (status === 1) t._resolver(value);
if (status === 2) {
if ((0, _lodash.isUndefined)(value)) {
value = new Error(`Transaction rejected with non-error: ${value}`);
}
t._rejecter(value);
}
});
if (status === 1 || status === 2) {
t._completed = true;
}
return q;
}
});
var _default = Transaction_MySQL2;
exports.default = _default;
module.exports = exports.default; |
Package.describe({
summary: "isolate reactive values"
});
Package.on_use(function (api) {
api.use([
'coffeescript',
'ejson'
], 'client');
if (api.export)
api.export('isolateValue', 'client');
api.add_files([
'isolate.coffee'
], 'client');
});
Package.on_test(function (api) {
api.use([
'coffeescript',
'tinytest'
]);
api.use('isolate-value', 'client');
api.add_files('isolate-tests.coffee', 'client');
});
|
// 获取全局应用程序实例对象
const app = getApp()
// 创建页面实例对象
Page({
/**
* 页面的初始数据
*/
data: {
title: 'scoreExchange',
page: 1,
exchangeArr: [
// {
// img: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
// tip: '美味想成',
// title: '好吃好吃好吃好吃好吃好吃好吃好吃好贺词好贺词',
// status: 1,
// score: 600,
// number: 150,
// id: 12341234
// },
// {
// img: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
// tip: '美味想成',
// title: '好吃好吃好吃好吃好吃好吃好吃好吃好贺词好贺词',
// status: 1,
// score: 600,
// number: 150,
// id: 657457
// }
]
},
// 获取奖品列表
getScorList (page) {
let that = this
let obj = {
those: that,
url: app.data.scoreUrl,
data: {
pageNo: page
}
}
app.getData(obj, function (res, that) {
// console.log(res)
// res.data.result.list
if (!res.data.result.list) {
return wx.showToast({
title: '没有更多内容啦',
mask: true
})
}
that.setData({
exchangeArr: that.data.exchangeArr.concat(res.data.result.list)
})
wx.hideLoading()
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad () {
wx.showLoading({
title: '请求数据中'
})
this.getScorList(1)
// TODO: onLoad
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady () {
// TODO: onReady
},
/**
* 生命周期函数--监听页面显示
*/
onShow () {
// TODO: onShow
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide () {
// TODO: onHide
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload () {
// TODO: onUnload
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh () {
// TODO: onPullDownRefresh
},
// 触底操作
onReachBottom () {
wx.showLoading({
title: '请求数据中'
})
this.getScorList(++this.data.page)
}
})
|
import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
SUI,
useKeyOnly,
useValueAndKey,
} from '../../lib'
import StatisticGroup from './StatisticGroup'
import StatisticLabel from './StatisticLabel'
import StatisticValue from './StatisticValue'
/**
* A statistic emphasizes the current value of an attribute.
*/
function Statistic(props) {
const {
children,
className,
color,
floated,
horizontal,
inverted,
label,
size,
text,
value,
} = props
const classes = cx(
'ui',
color,
size,
useValueAndKey(floated, 'floated'),
useKeyOnly(horizontal, 'horizontal'),
useKeyOnly(inverted, 'inverted'),
'statistic',
className,
)
const rest = getUnhandledProps(Statistic, props)
const ElementType = getElementType(Statistic, props)
if (!childrenUtils.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType>
return (
<ElementType {...rest} className={classes}>
<StatisticValue text={text} value={value} />
<StatisticLabel label={label} />
</ElementType>
)
}
Statistic._meta = {
name: 'Statistic',
type: META.TYPES.VIEW,
}
Statistic.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** A statistic can be formatted to be different colors. */
color: PropTypes.oneOf(SUI.COLORS),
/** A statistic can sit to the left or right of other content. */
floated: PropTypes.oneOf(SUI.FLOATS),
/** A statistic can present its measurement horizontally. */
horizontal: PropTypes.bool,
/** A statistic can be formatted to fit on a dark background. */
inverted: PropTypes.bool,
/** Label content of the Statistic. */
label: customPropTypes.contentShorthand,
/** A statistic can vary in size. */
size: PropTypes.oneOf(_.without(SUI.SIZES, 'big', 'massive', 'medium')),
/** Format the StatisticValue with smaller font size to fit nicely beside number values. */
text: PropTypes.bool,
/** Value content of the Statistic. */
value: customPropTypes.contentShorthand,
}
Statistic.Group = StatisticGroup
Statistic.Label = StatisticLabel
Statistic.Value = StatisticValue
export default Statistic
|
const mongoose = require('mongoose'), Schema = mongoose.Schema;
const ConversationSchema = new Schema({
name: {type: String, unique: true, required: true},
participants: [{ type: Schema.Types.ObjectId, ref: 'User'}],
isPublic: {type: Boolean, default: true}
});
module.exports = mongoose.model('Conversation', ConversationSchema); |
var render = REQUIRE.mod('Framework/viewRendering');
function index(response) {
render.renderView('home', 'index', response);
}
module.exports = {
index : index
}; |
"use strict";
var row_1 = require('./row');
var column_1 = require('./column');
var DataSet = (function () {
function DataSet(data, columnSettings) {
if (data === void 0) { data = []; }
this.columnSettings = columnSettings;
this.data = [];
this.columns = [];
this.rows = [];
this.willSelect = 'first';
this.createColumns(columnSettings);
this.setData(data);
this.createNewRow();
}
DataSet.prototype.setData = function (data) {
this.data = data;
this.createRows();
};
DataSet.prototype.getColumns = function () {
return this.columns;
};
DataSet.prototype.getRows = function () {
return this.rows;
};
DataSet.prototype.findRowByData = function (data) {
return this.rows.find(function (row) { return row.getData() === data; });
};
DataSet.prototype.deselectAll = function () {
this.rows.forEach(function (row) {
row.isSelected = false;
});
};
DataSet.prototype.selectRow = function (row) {
this.deselectAll();
row.isSelected = true;
this.selectedRow = row;
return this.selectedRow;
};
DataSet.prototype.multipleSelectRow = function (row) {
row.isSelected = !row.isSelected;
this.selectedRow = row;
return this.selectedRow;
};
DataSet.prototype.selectPreviousRow = function () {
if (this.rows.length > 0) {
var index = this.selectedRow ? this.selectedRow.index : 0;
if (index > this.rows.length - 1) {
index = this.rows.length - 1;
}
this.selectRow(this.rows[index]);
return this.selectedRow;
}
};
DataSet.prototype.selectFirstRow = function () {
if (this.rows.length > 0) {
this.selectRow(this.rows[0]);
return this.selectedRow;
}
};
DataSet.prototype.selectLastRow = function () {
if (this.rows.length > 0) {
this.selectRow(this.rows[this.rows.length - 1]);
return this.selectedRow;
}
};
DataSet.prototype.willSelectFirstRow = function () {
this.willSelect = 'first';
};
DataSet.prototype.willSelectLastRow = function () {
this.willSelect = 'last';
};
DataSet.prototype.select = function () {
if (this.getRows().length === 0) {
return;
}
if (this.willSelect) {
if (this.willSelect === 'first') {
this.selectFirstRow();
}
if (this.willSelect === 'last') {
this.selectLastRow();
}
this.willSelect = '';
}
else {
this.selectFirstRow();
}
return this.selectedRow;
};
DataSet.prototype.createNewRow = function () {
this.newRow = new row_1.Row(0, {}, this);
this.newRow.isInEditing = true;
};
/**
* Create columns by mapping from the settings
* @param settings
* @private
*/
DataSet.prototype.createColumns = function (settings) {
for (var id in settings) {
if (settings.hasOwnProperty(id)) {
this.columns.push(new column_1.Column(id, settings[id], this));
}
}
};
/**
* Create rows based on current data prepared in data source
* @private
*/
DataSet.prototype.createRows = function () {
var _this = this;
this.rows = [];
this.data.forEach(function (el, index) {
_this.rows.push(new row_1.Row(index, el, _this));
});
};
return DataSet;
}());
exports.DataSet = DataSet;
//# sourceMappingURL=data-set.js.map |
/**!
*
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
*/
import _request from './request';
import {EventEmitter} from 'events';
/**
* @param {Object} options
* @returns {Promise}
*/
export default function request(options) {
if (options.url) {
options.uri = options.url;
options.url = null;
}
options.headers = options.headers || {};
options.download = new EventEmitter();
options.upload = new EventEmitter();
return intercept(options.interceptors, `Request`)
.then((...args) => _request(options, ...args))
.then((...args) => intercept(options.interceptors.slice().reverse(), `Response`, ...args));
/**
* @param {Array} interceptors
* @param {string} key
* @param {Object} res
* @private
* @returns {Promise}
*/
function intercept(interceptors, key, res) {
const successKey = `on${key}`;
const errorKey = `on${key}Error`;
return interceptors.reduce((promise, interceptor) => promise.then(
(result) => {
if (interceptor[successKey]) {
return interceptor[successKey](options, result);
}
return Promise.resolve(result);
},
(reason) => {
if (interceptor[errorKey]) {
return interceptor[errorKey](options, reason);
}
return Promise.reject(reason);
}
), Promise.resolve(res));
}
}
|
module.exports = function(grunt) {
// Project Configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
html: {
files: ['public/views/**'],
options: {
livereload: true,
},
},
js: {
files: ['public/js/**'],
tasks: ['concat'],
options: {
livereload: true,
},
},
css: {
files: ['public/sass/**'],
tasks: ['compass'],
options: {
livereload: true,
},
},
specs: {
files: ['spec/**/*.js'],
tasks: ['jasmine_node'],
options: {
livereload: true,
},
}
},
jshint: {
grunt: ['gruntfile.js'],
client: ['public/js/**/*.js'],
server: ['app/**/*.js'],
},
compass: { // Task
dist: { // Target
options: { // Target options
sassDir: 'public/sass',
cssDir: 'public/css',
environment: 'production'
}
},
dev: { // Another target
options: {
sassDir: 'public/sass',
cssDir: 'public/css'
}
}
},
nodemon: {
dev: {
options: {
file: 'server.js',
args: [],
ignoredFiles: ['README.md', 'node_modules/**', '.DS_Store'],
watchedExtensions: ['js'],
watchedFolders: ['app', 'config'],
debug: true,
delayTime: 1,
env: {
PORT: 3000
},
cwd: __dirname
}
},
exec: {
options: {
exec: 'less'
}
}
},
concurrent: {
target: {
tasks: ['nodemon', 'watch'],
options: {
logConcurrentOutput: true
}
}
},
jasmine_node: {
coverage: {
},
options: {
specNameMatcher: "spec",
match: "./spec/",
projectRoot: "./spec/",
requirejs: false,
forceExit: false,
verbose: true,
jUnit: {
report: false,
savePath : "./build/reports/jasmine/",
useDotNotation: true,
consolidate: true
}
}
},
concat: {
js: {
files: {
'public/javascripts/app.js': 'public/js/**/*.js'
}
}
},
bump: {
options: {
commit: false,
createTag: true,
push: false,
commitFiles: ['package.json', 'changelog.md'],
updateConfigs: ['pkg']
}
},
changelog: {
options: {
}
},
mochaProtractor: {
options: {
browers: ['chrome'],
},
files: ['./e2eSpecs/*specs.js']
}
});
// Load NPM tasks
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-concurrent');
//grunt.loadNpmTasks('grunt-jasmine-node-coverage');
grunt.loadNpmTasks('grunt-jasmine-node');
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-conventional-changelog');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-mocha-protractor');
grunt.registerTask('informwebdriver', 'Tells user to start selenium driver', function() {
grunt.log.writeln('Make sure the selenium driver is running using : webdriver-manager start');
});
// Default task(s).
grunt.registerTask('default', ['jshint:grunt', 'concurrent:target']);
grunt.registerTask('test', ['jasmine_node']);
grunt.registerTask('notes', ['bump-only', 'changelog', 'bump-commit']);
};
|
/* global __VERSION__ */
/**
* The _model_module_version/_view_module_version this package implements.
*
* The html widget manager assumes that this is the same as the npm package
* version number.
*/
export const MODULE_VERSION =
typeof __VERSION__ === 'undefined' ? 'untranspiled source' : __VERSION__;
export const MODULE_NAME = '@deck.gl/jupyter-widget';
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-tablesorter
//= require bootstrap
//= require underscore
//= require highcharts
//= require highcharts/highcharts-more
//= require heatmap
$(document).ready(function(){
$('table').tablesorter();
$('a').tooltip();
});
//= require_tree . |
/**
* Created by n7best on 16/2/25.
*/
"use strict";
import React from 'react';
import { shallow } from 'enzyme';
import assert from 'assert';
import WeUI from '../src/index';
const {Checkbox} = WeUI;
describe('<Checkbox></Checkbox>', ()=> {
[undefined, null, 'custom_class'].map(clazz => {
describe(`<Checkbox className=${clazz}></Checkbox>`, ()=> {
const wrapper = shallow(
<Checkbox className={clazz}/>
);
it(`should render <Checkbox></Checkbox> component`, ()=> {
assert(wrapper.instance() instanceof Checkbox);
});
it(`should render Checkbox input component with weui_check class`, ()=> {
assert(wrapper.find('input').hasClass('weui_check'));
});
it(`should render i with weui_icon_checked class`, ()=> {
assert(wrapper.find('i').hasClass('weui_icon_checked'));
});
it(`should have custom class name ${clazz} when className is not null or empty`, ()=>{
if (clazz) {
assert(wrapper.find('input').hasClass(clazz));
}
});
});
});
}); |
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var CompiledNLPatternRules = /** @class */ (function (_super) {
__extends(CompiledNLPatternRules, _super);
function CompiledNLPatternRules(name, o, sv, lv) {
var _this = _super.call(this, name, sv, lv) || this;
_this.root = null;
return _this;
// if (o!=null) {
// this.speakerVariable = new VariableTermAttribute(o.getSort("any"),"SPEAKER");
// this.listenerVariable = new VariableTermAttribute(o.getSort("any"),"LISTENER");
// }
}
CompiledNLPatternRules.prototype.ruleHeadMatchesSort = function (sort, rule) {
if (rule.head.functor.is_a(sort)) {
return true;
}
else if (rule.head.functor.name == "#list" &&
rule.head.attributes.length > 0 &&
rule.head.attributes[0] instanceof TermTermAttribute) {
if (rule.head.attributes[0].term.functor.is_a(sort)) {
return true;
}
}
return false;
};
CompiledNLPatternRules.prototype.populate = function (sort, parser) {
this.root = new CompiledNLPatternState();
for (var _i = 0, _a = parser.rules; _i < _a.length; _i++) {
var rule = _a[_i];
if (this.ruleHeadMatchesSort(sort, rule)) {
// if (rule.head.functor.is_a(sort)) {
// console.log("rule head: " + rule.head);
this.root.addRule(rule, this.speakerVariable, this.listenerVariable);
}
}
};
CompiledNLPatternRules.prototype.cloneForParsing = function () {
// let map:[TermAttribute,TermAttribute][] = [];
var c = new CompiledNLPatternRules(this.name, null, this.speakerVariable, this.listenerVariable);
c.root = this.root;
// this.speakerVariable = new VariableTermAttribute(o.getSort("any"),"SPEAKER");
// this.listenerVariable = new VariableTermAttribute(o.getSort("any"),"LISTENER");
// c.speakerVariable = this.speakerVariable;
// c.listenerVariable = this.listenerVariable;
return c;
};
CompiledNLPatternRules.prototype.parse = function (tokenization, filterPartialParses, context, parser, AI) {
// parse the sentence:
// console.log("NLPatternRule.parse");
var bindings = new Bindings();
if (this.speakerVariable != null) {
// console.log("Speaker: " + this.speakerVariable);
bindings.l.push([this.speakerVariable,
new ConstantTermAttribute(context.speaker, parser.o.getSort("#id"))]);
}
var parses = this.root.parse(new NLParseRecord([tokenization], [], bindings, [], [], []), context, this, parser, AI, filterPartialParses);
if (parses == null)
return null;
// console.log("CompiledNLPatternRules.parse, n parses: " + parses.length);
// if there is any valid parse, generate the corresponding terms:
var results = [];
for (var _i = 0, parses_1 = parses; _i < parses_1.length; _i++) {
var parse = parses_1[_i];
if (filterPartialParses &&
parse.nextTokens != null && parse.nextTokens.length > 0)
continue;
// parse.ruleNames = [this.name].concat(parse.ruleNames);
// parse.priorities = [this.priority].concat(parse.priorities);
// parse.result = this.head.applyBindings(parse.bindings);
// console.log("Parse completed, result (before resolvecons): " + parse.result);
NLParser.resolveCons(parse.result, parser.o);
// console.log("CompiledNLPatternRules.parse: Parse completed, result: " + parse.result);
results.push(parse);
}
return results;
};
CompiledNLPatternRules.prototype.parseMatchingWithTerm = function (parse, filterPartialParses, context, parser, AI, term) {
var results = [];
var parses = this.root.parse(parse, context, this, parser, AI, filterPartialParses);
if (parses != null) {
// console.log("parseMatchingWithTerm completed with parses.length = " + parses.length);
for (var _i = 0, parses_2 = parses; _i < parses_2.length; _i++) {
var parse2 = parses_2[_i];
if (filterPartialParses &&
parse2.nextTokens != null && parse2.nextTokens.length > 0)
continue;
// parse2.ruleNames = [this.name].concat(parse.ruleNames);
// parse2.priorities = [this.priority].concat(parse.priorities);
// parse2.result = this.head.applyBindings(parse2.bindings);
// console.log("parseMatchingWithTerm completed, result (before resolvecons): " + parse2.result);
NLParser.resolveCons(parse2.result, parser.o);
// console.log("parseMatchingWithTerm.parse: Parse completed, result: " + parse2.result);
var bindings = new Bindings();
// if (parse2.result.unify(term, OCCURS_CHECK, bindings)) {
if (term.unify(parse2.result, OCCURS_CHECK, bindings)) {
parse2.result = parse2.result.applyBindings(bindings);
// console.log("parseMatchingWithTerm completed, result: " + parse2.result);
results.push(parse2);
}
}
}
return results;
};
return CompiledNLPatternRules;
}(NLPatternContainer));
var CompiledNLPatternState = /** @class */ (function () {
function CompiledNLPatternState() {
this.priorities = []; // if parsing ends at this node, what would be the priority of the parse
this.heads = []; // if parsing can end at this node, this is the term that will be returned
this.transitions = [];
this.ruleNames = [];
}
// this function adds a rule to the current parsing graph, and returns the set of terminal states where this rule ends
CompiledNLPatternState.prototype.addRule = function (rule, speakerVariable, listenerVariable) {
var tmp = this.addRuleInternal(rule.priority, rule.body, new Bindings(), speakerVariable, listenerVariable);
for (var i = 0; i < tmp.length; i++) {
var s = tmp[i][0];
var b = tmp[i][1];
// set the proper LISTENER and SPEAKER variables:
var rule2 = rule.head.applyBindings(b);
// console.log("rule.head: " + rule.head);
// console.log("rule2: " + rule2);
var variables = rule2.getAllVariables();
var b2 = new Bindings();
for (var _i = 0, variables_1 = variables; _i < variables_1.length; _i++) {
var v = variables_1[_i];
// if (v.name == "LISTENER" && v != listenerVariable) b2.l.push([v, listenerVariable]);
if (v.name == "SPEAKER" && v != speakerVariable)
b2.l.push([v, speakerVariable]);
}
if (b2.l.length > 0)
rule2 = rule2.applyBindings(b2);
s.priorities.push(rule.priority);
s.heads.push(rule2);
s.ruleNames.push(rule.name);
}
};
CompiledNLPatternState.prototype.addRuleInternal = function (priority, current, bindings, speakerVariable, listenerVariable) {
switch (current.type) {
case NLPATTERN_SEQUENCE:
var currentStates = [[this, bindings]];
for (var i = 0; i < current.children.length; i++) {
var nextStates = [];
for (var _i = 0, currentStates_1 = currentStates; _i < currentStates_1.length; _i++) {
var tmp_1 = currentStates_1[_i];
var s = tmp_1[0];
var b = tmp_1[1];
var nextStates2 = s.addRuleInternal(priority, current.children[i], b, speakerVariable, listenerVariable);
for (var _a = 0, nextStates2_1 = nextStates2; _a < nextStates2_1.length; _a++) {
var ns = nextStates2_1[_a];
nextStates.push(ns);
}
}
currentStates = nextStates;
}
return currentStates;
case NLPATTERN_ALTERNATIVE:
{
var nextStates = [];
var accumBindings = bindings;
for (var i = 0; i < current.children.length; i++) {
var nextStates2 = this.addRuleInternal(priority, current.children[i], accumBindings, speakerVariable, listenerVariable);
if (nextStates2.length != 1) {
console.error("!!!");
}
for (var _b = 0, nextStates2_2 = nextStates2; _b < nextStates2_2.length; _b++) {
var ns2 = nextStates2_2[_b];
nextStates.push(ns2);
accumBindings = ns2[1];
}
}
if (nextStates.length > 1) {
var s = new CompiledNLPatternState();
for (var _c = 0, nextStates_1 = nextStates; _c < nextStates_1.length; _c++) {
var ns = nextStates_1[_c];
var t = new CompiledNLPatternTransition();
t.type = NLPATTERN_NONE;
t.maxPriority = priority;
t.destinationState = s;
ns[0].transitions.push(t);
}
return [[s, accumBindings]];
}
else {
return nextStates;
}
}
case NLPATTERN_OPTIONAL:
{
var nextStates = this.addRuleInternal(priority, current.children[0], bindings, speakerVariable, listenerVariable);
if (nextStates.length == 1) {
var found = false;
for (var _d = 0, _e = this.transitions; _d < _e.length; _d++) {
var t2 = _e[_d];
if (t2.type == NLPATTERN_NONE && t2.destinationState == nextStates[0][0]) {
found = true;
break;
}
}
if (!found) {
// create a new transition (if needed):
var t = new CompiledNLPatternTransition();
t.type = NLPATTERN_NONE;
t.maxPriority = priority;
t.destinationState = nextStates[0][0];
this.transitions.push(t);
}
return nextStates;
}
else {
nextStates.push([this, bindings]);
return nextStates;
}
}
case NLPATTERN_REPEAT:
{
var nextStates = this.addRuleInternal(priority, current.children[0], bindings, speakerVariable, listenerVariable);
// replace the next states with this:
var open_1 = [];
var closed_1 = [];
open_1.push([this, null]);
while (open_1.length > 0) {
// console.log("open: " + open.length + ", closed: " + closed.length);
var _f = open_1[0], current_s = _f[0], current_t = _f[1];
open_1.splice(0, 1);
closed_1.push(current_s);
var found = false;
for (var _g = 0, nextStates_2 = nextStates; _g < nextStates_2.length; _g++) {
var sb = nextStates_2[_g];
if (sb[0] == current_s && current_t != null) {
current_t.destinationState = this;
found = true;
break;
}
}
if (!found) {
for (var _h = 0, _j = current_s.transitions; _h < _j.length; _h++) {
var t = _j[_h];
if (closed_1.indexOf(t.destinationState) == -1) {
open_1.push([t.destinationState, t]);
}
}
}
}
}
return [[this, bindings]];
case NLPATTERN_STRING:
case NLPATTERN_POS:
case NLPATTERN_PATTERN:
case NLPATTERN_FUNCTION:
var tmp = this.findMatchingTransition(current, bindings);
if (tmp == null) {
// create a new transition:
var t = new CompiledNLPatternTransition();
var s = new CompiledNLPatternState();
t.type = current.type;
t.string = current.string;
t.maxPriority = priority;
t.destinationState = s;
if (current.term != null) {
// let v:TermAttribute[] = [];
// let vn:string[] = [];
// console.log(" adding transition: " + current.term.toStringInternal(v, vn));
// console.log(" with bindings: " + bindings.toStringWithMappings(v, vn));
var term2 = current.term.applyBindings(bindings);
// set the proper LISTENER and SPEAKER variables:
var variables = term2.getAllVariables();
var b2 = new Bindings();
for (var _k = 0, variables_2 = variables; _k < variables_2.length; _k++) {
var v = variables_2[_k];
// if (v.name == "LISTENER" && v != listenerVariable) b2.l.push([v, listenerVariable]);
if (v.name == "SPEAKER" && v != speakerVariable)
b2.l.push([v, speakerVariable]);
}
if (b2.l.length > 0) {
t.term = term2.applyBindings(b2);
}
else {
t.term = term2;
}
}
this.transitions.push(t);
return [[s, bindings]];
}
else {
var t = tmp[0];
var b = tmp[1];
t.maxPriority = Math.max(t.maxPriority, priority);
return [[t.destinationState, b]];
}
case NLPATTERN_NONE:
console.error("Unsuported rule type NLPATTERN_NONE!");
return null;
default:
console.error("Unsuported rule type!");
return null;
}
return [];
};
CompiledNLPatternState.prototype.findMatchingTransition = function (p, b) {
for (var i = 0; i < this.transitions.length; i++) {
if (this.transitions[i].type == p.type) {
if (p.type == NLPATTERN_STRING) {
if (this.transitions[i].string == p.string)
return [this.transitions[i], b];
}
else {
var t2 = p.term.applyBindings(b);
var b2 = new Bindings();
// if (this.transitions[i].term.equalsInternal(t2, b2)) return [this.transitions[i], b.concat(b2)];
if (t2.equalsInternal(this.transitions[i].term, b2))
return [this.transitions[i], b.concat(b2)];
}
}
}
return null;
};
CompiledNLPatternState.prototype.addParseIfNew = function (parses, parse) {
for (var _i = 0, parses_3 = parses; _i < parses_3.length; _i++) {
var parse2 = parses_3[_i];
if (parse.result != null && parse2.result != null &&
parse.nextTokens.length == parse2.nextTokens.length &&
parse.higherPriorityThan(parse2) <= 0 &&
parse.result.equalsNoBindings(parse2.result) == 1) {
if (parse.nextTokens.length == 0 ||
parse.nextTokens[0].token == parse2.nextTokens[0].token) {
// console.log("Filtering out parse: ");
// console.log(" result: " + parse.result);
// console.log(" ruleNames: " + parse.ruleNames);
// console.log(" bindings: " + parse.bindings);
// console.log(" nextTokens: " + parse.nextTokens);
// console.log(" priorities: " + parse.priorities);
// console.log("Because it's the same as: ");
// console.log(" result: " + parse2.result);
// console.log(" ruleNames: " + parse2.ruleNames);
// console.log(" bindings: " + parse2.bindings);
// console.log(" nextTokens: " + parse2.nextTokens);
// console.log(" priorities: " + parse2.priorities);
return false;
}
}
}
parses.push(parse);
return true;
};
CompiledNLPatternState.prototype.parse = function (parse, context, rule, parser, AI, filterPartialParses) {
// console.log("CompiledNLPatternState.parse... (heads: " + this.heads.length + "), parsing: " +
// (parse.nextTokens != null && parse.nextTokens.length>0 ? parse.nextTokens[0].token:"-"));
var parses = [];
// let bestPriority:number = 0;
for (var i = 0; i < this.heads.length; i++) {
// found a parse!
// console.log("parse found with bindings: " + parse.bindings);
var parse2 = new NLParseRecord(parse.nextTokens, parse.previousPOS, parse.bindings, parse.derefs, parse.ruleNames, parse.priorities);
parse2.result = this.heads[i].applyBindings(parse2.bindings);
parse2.ruleNames = [this.ruleNames[i]].concat(parse2.ruleNames);
parse2.priorities = [this.priorities[i]].concat(parse2.priorities);
this.addParseIfNew(parses, parse2);
// console.log("HEAD reached with rule names: " + parse.ruleNames);
// if (parse2.nextTokens != null && parse2.nextTokens.length > 0) {
// console.log(" tokens left: " + parse.nextTokens[0].toStringSimple());
// } else {
// console.log("HEAD reached with rule names: " + parse2.ruleNames);
// console.log(" bindings: " + parse.bindings);
// console.log(" result: " + parse2.result);
// }
// console.log("result: " + parse.result);
}
for (var _i = 0, _a = this.transitions; _i < _a.length; _i++) {
var t = _a[_i];
// if we do not have hopes of finding a parse with higher priority, then we can already abandon:
// if (t.maxPriority < bestPriority) {
// console.log("t.maxPriority = " + t.maxPriority + " < bestPriority = " + bestPriority);
// continue;
// }
var parses2 = [];
switch (t.type) {
case NLPATTERN_NONE:
parses2 = t.destinationState.parse(parse, context, rule, parser, AI, filterPartialParses);
break;
case NLPATTERN_STRING:
parses2 = t.parseString(parse, context, rule, parser, AI, filterPartialParses);
break;
case NLPATTERN_POS:
parses2 = t.parsePOS(parse, context, rule, parser, AI, filterPartialParses);
break;
case NLPATTERN_PATTERN:
parses2 = t.parsePattern(parse, context, rule, parser, AI, filterPartialParses);
break;
case NLPATTERN_FUNCTION:
parses2 = t.parseFunction(parse, context, rule, parser, AI, filterPartialParses);
break;
default:
console.error("CompiledNLPatternState.parse: pattern type not supported " + t.type);
}
if (parses2 != null) {
for (var _b = 0, parses2_1 = parses2; _b < parses2_1.length; _b++) {
var p = parses2_1[_b];
if (filterPartialParses &&
p.nextTokens != null && p.nextTokens.length > 0)
continue;
// if (p.priorities[0] >= bestPriority) {
this.addParseIfNew(parses, p);
// console.log("passing along result ("+t.type+", priority = " + p.priorities[0] + "): " + p.result);
// bestPriority = p.priorities[0];
// }
}
}
}
return parses;
};
CompiledNLPatternState.prototype.getAllStatesForDOTString = function () {
// find all the states:
var open = [];
var closed = [];
open.push(this);
while (open.length != 0) {
var current = open[0];
open.splice(0, 1);
closed.push(current);
for (var _i = 0, _a = current.transitions; _i < _a.length; _i++) {
var t = _a[_i];
if (closed.indexOf(t.destinationState) == -1 &&
open.indexOf(t.destinationState) == -1) {
open.push(t.destinationState);
}
}
}
return closed;
};
CompiledNLPatternState.prototype.convertToDOTString = function () {
var str = "digraph compiledgrammar {\n";
str += "graph[rankdir=LR];\n";
var variables = [];
var variableNames = [];
// find all the states:
var closed = this.getAllStatesForDOTString();
for (var i = 0; i < closed.length; i++) {
var slabel = "";
for (var j = 0; j < closed[i].heads.length; j++) {
if (j != 0)
slabel += "\n";
slabel += closed[i].heads[j].toStringInternal(variables, variableNames) + " (" + closed[i].priorities[j] + ")";
}
str += "s" + i + "[shape=box label=\"" + slabel + "\"];\n";
}
for (var i = 0; i < closed.length; i++) {
for (var j = 0; j < closed[i].transitions.length; j++) {
var tlabel = "";
if (closed[i].transitions[j].string != null) {
tlabel = "'" + closed[i].transitions[j].string + "'";
}
else if (closed[i].transitions[j].term != null) {
tlabel = closed[i].transitions[j].term.toStringInternal(variables, variableNames);
}
else {
"-";
}
str += "s" + i + " -> s" + closed.indexOf(closed[i].transitions[j].destinationState) + "[label=\"" + tlabel + " (" + closed[i].transitions[j].maxPriority + ")\"];\n";
}
}
str += "}\n";
return str;
};
return CompiledNLPatternState;
}());
var CompiledNLPatternTransition = /** @class */ (function () {
function CompiledNLPatternTransition() {
this.type = NLPATTERN_NONE;
this.string = null;
this.term = null; // this is used for POS, recursive patterns and special functions
this.destinationState = null;
this.maxPriority = 0;
}
CompiledNLPatternTransition.prototype.parseString = function (parse, context, rule, parser, AI, filterPartialParses) {
if (parse.nextTokens == null)
return null;
var parses = [];
for (var _i = 0, _a = parse.nextTokens; _i < _a.length; _i++) {
var nextToken = _a[_i];
if (nextToken.token == null) {
var parses2 = this.parseString(new NLParseRecord(nextToken.next, parse.previousPOS, parse.bindings, parse.derefs, parse.ruleNames, parse.priorities), context, rule, parser, AI, filterPartialParses);
if (parses2 != null)
parses = parses.concat(parses2);
}
else if (nextToken.token == this.string) {
// match!
var parses2 = this.destinationState.parse(new NLParseRecord(nextToken.next, parse.previousPOS, parse.bindings, parse.derefs, parse.ruleNames, parse.priorities), context, rule, parser, AI, filterPartialParses);
if (parses2 != null)
parses = parses.concat(parses2);
}
}
if (parses.length == 0)
return null;
return parses;
};
CompiledNLPatternTransition.prototype.parsePOS = function (parse, context, rule, parser, AI, filterPartialParses) {
var parses = [];
var term2 = this.term.applyBindings(parse.bindings);
// console.log("Matching POS, before: " + this.term.toString() + "\n bindings: " + parse.bindings + "\n Matching POS, after: " + term2.toString());
for (var _i = 0, _a = parse.nextTokens; _i < _a.length; _i++) {
var nextToken = _a[_i];
if (nextToken.token == null) {
var parses2 = this.parsePOS(new NLParseRecord(nextToken.next, parse.previousPOS, parse.bindings, parse.derefs, parse.ruleNames, parse.priorities), context, rule, parser, AI, filterPartialParses);
if (parses2 != null)
parses = parses.concat(parses2);
}
else {
for (var _b = 0, _c = nextToken.POS; _b < _c.length; _b++) {
var POS = _c[_b];
var bindings = new Bindings();
if (POS.term.unify(term2, OCCURS_CHECK, bindings)) {
var parses2 = this.destinationState.parse(new NLParseRecord(nextToken.next, parse.previousPOS.concat([POS]), parse.bindings.concat(bindings), parse.derefs, parse.ruleNames, parse.priorities), context, rule, parser, AI, filterPartialParses);
if (parses2 != null)
parses = parses.concat(parses2);
}
}
}
}
if (parses.length == 0)
return null;
return parses;
};
CompiledNLPatternTransition.prototype.parsePattern = function (parse, context, rule, parser, AI, filterPartialParses) {
var parses_p = [];
var term2 = this.term.applyBindings(parse.bindings);
// let term2:Term = this.term;
// console.log("Matching pattern: " + term2.toString());
var compiled = parser.compiledRules[term2.functor.name];
if (compiled != null) {
// if we have a compiled tree, use it!
// console.log("CompiledNLPatternTransition.parsePattern: Found a compiled tree for " + term2.functor.name + " ...");
var results = compiled.parseMatchingWithTerm(new NLParseRecord(parse.nextTokens, parse.previousPOS, new Bindings(), parse.derefs, parse.ruleNames, parse.priorities), false, context, parser, AI, term2);
for (var _i = 0, results_1 = results; _i < results_1.length; _i++) {
var pr = results_1[_i];
var bindings2 = new Bindings();
// if (!pr.result.unify(term2, OCCURS_CHECK, bindings2)) {
if (!term2.unify(pr.result, OCCURS_CHECK, bindings2)) {
console.error("CompiledNLPatternTransition.parsePattern: something went wrong when parsing pattern " + term2.toString() + "\n It does not unify with: " + pr.result);
return null;
}
// console.log("Succesful unification of:");
// console.log(" " + pr.result);
// console.log(" " + term2);
// console.log(" bindings: " + bindings2);
// we continue from "pr", but using the bdingins from "parse", since the bindings
// generated during the parsing of the sub-pattern are not relevant
var parses2 = this.destinationState.parse(new NLParseRecord(pr.nextTokens, pr.previousPOS, parse.bindings.concat(bindings2), pr.derefs, pr.ruleNames.concat(parse.ruleNames), pr.priorities.concat(parse.priorities)), context, rule, parser, AI, filterPartialParses);
if (parses2 != null)
parses_p = parses_p.concat(parses2);
}
}
else {
// console.log("CompiledNLPatternTransition.parsePattern: Using the raw rules for " + term2.functor.name + " ...");
for (var _a = 0, _b = parser.rules; _a < _b.length; _a++) {
var rawRule2 = _b[_a];
var rule2 = rawRule2.clone();
var bindings = new Bindings();
if (rule2.head.unify(term2, OCCURS_CHECK, bindings)) {
// rule to consider!!
// console.log(" considering rule with head: " + rule2.head.toString() + "\n new bindings: " + bindings);
var results = rule2.parseWithBindings(new NLParseRecord(parse.nextTokens, parse.previousPOS, bindings, parse.derefs, parse.ruleNames, parse.priorities), false, context, parser, AI);
for (var _c = 0, results_2 = results; _c < results_2.length; _c++) {
var pr = results_2[_c];
var bindings2 = new Bindings();
if (!pr.result.unify(term2, OCCURS_CHECK, bindings2)) {
console.error("CompiledNLPatternTransition.parse: something went wrong when parsing pattern " + term2.toString() + "\n It does not unify with: " + pr.result);
return null;
}
// console.log(" Pattern matched successfully with result: " + pr.result.toString());
// console.log(" and bindings: " + bindings2);
// we continue from "pr", but using the bdingins from "parse", since the bindings
// generated during the parsing of the sub-pattern are not relevant
var parses2 = this.destinationState.parse(new NLParseRecord(pr.nextTokens, pr.previousPOS, parse.bindings.concat(bindings2), pr.derefs, pr.ruleNames.concat(parse.ruleNames), pr.priorities.concat(parse.priorities)), context, rule, parser, AI, filterPartialParses);
if (parses2 != null)
parses_p = parses_p.concat(parses2);
}
// } else {
// console.log(" head: " + rule2.head + "\n. did not unify with: " + term2);
}
}
}
if (parses_p.length == 0)
return null;
// console.log("Result of pattern: " + parses_p);
return parses_p;
};
CompiledNLPatternTransition.prototype.parseFunction = function (parse, context, rule, parser, AI, filterPartialParses) {
var parses_p = [];
var pattern = new NLPattern(this.type);
pattern.term = this.term;
var results = pattern.parseFunction(parse, context, rule, parser, AI);
if (results != null) {
for (var _i = 0, results_3 = results; _i < results_3.length; _i++) {
var pr = results_3[_i];
// console.log("parseFunction, parse.bindings: " + parse.bindings);
// console.log("parseFunction, pr.bindings: " + pr.bindings);
var parses2 = this.destinationState.parse(new NLParseRecord(pr.nextTokens, pr.previousPOS, pr.bindings, pr.derefs, pr.ruleNames, pr.priorities), context, rule, parser, AI, filterPartialParses);
if (parses2 != null)
parses_p = parses_p.concat(parses2);
}
}
return parses_p;
};
return CompiledNLPatternTransition;
}());
|
describe('Sharpen the Mind', function() {
integration(function() {
describe('Sharpen the Mind\'s ability', function() {
beforeEach(function() {
this.setupTest({
phase: 'conflict',
player1: {
inPlay: ['brash-samurai'],
hand: ['sharpen-the-mind', 'fine-katana', 'ornate-fan'],
conflictDiscard: ['guidance-of-the-ancestors']
},
player2: {
}
});
this.brashSamurai = this.player1.findCardByName('brash-samurai');
this.sharpenTheMind = this.player1.findCardByName('sharpen-the-mind');
this.fineKatana = this.player1.findCardByName('fine-katana');
this.ornateFan = this.player1.findCardByName('ornate-fan');
this.guidanceOfTheAncestors = this.player1.findCardByName('guidance-of-the-ancestors');
this.player1.playAttachment(this.sharpenTheMind, this.brashSamurai);
});
it('should not be triggerable outside of a conflict', function() {
this.player2.pass();
expect(this.player1).toHavePrompt('Action Window');
this.player2.clickCard(this.sharpenTheMind);
expect(this.player1).toHavePrompt('Action Window');
});
it('should prompt to choose a card to discard', function() {
this.noMoreActions();
this.initiateConflict({
attackers: [this.brashSamurai],
defenders: []
});
this.player2.pass();
this.player1.clickCard(this.sharpenTheMind);
expect(this.player1).toHavePrompt('Select card to discard');
expect(this.player1).toBeAbleToSelect(this.fineKatana);
expect(this.player1).toBeAbleToSelect(this.ornateFan);
});
it('should only prompt to discard from hand', function() {
this.noMoreActions();
this.initiateConflict({
attackers: [this.brashSamurai],
defenders: []
});
this.player2.pass();
this.player1.clickCard(this.sharpenTheMind);
expect(this.player1).toHavePrompt('Select card to discard');
expect(this.player1).toBeAbleToSelect(this.fineKatana);
expect(this.player1).toBeAbleToSelect(this.ornateFan);
expect(this.player1).not.toBeAbleToSelect(this.brashSamurai);
expect(this.player1).not.toBeAbleToSelect(this.guidanceOfTheAncestors);
});
it('should discard the chosen card', function() {
this.noMoreActions();
this.initiateConflict({
attackers: [this.brashSamurai],
defenders: []
});
this.player2.pass();
this.player1.clickCard(this.sharpenTheMind);
this.player1.clickCard(this.fineKatana);
expect(this.fineKatana.location).toBe('conflict discard pile');
});
it('should give the attached character +3/+3', function() {
this.noMoreActions();
this.initiateConflict({
attackers: [this.brashSamurai],
defenders: []
});
this.player2.pass();
this.player1.clickCard(this.sharpenTheMind);
this.player1.clickCard(this.fineKatana);
expect(this.brashSamurai.getMilitarySkill()).toBe(this.brashSamurai.printedMilitarySkill + 3);
expect(this.brashSamurai.getPoliticalSkill()).toBe(this.brashSamurai.printedPoliticalSkill + 3);
expect(this.getChatLogs(3)).toContain('player1 uses Sharpen the Mind, discarding Fine Katana to give +3military/+3political to Brash Samurai');
});
});
});
});
|
try{
/**
* Mocks up a Timespan object for unit tests
*
* @private
* @param {Timespan|Object} map properties to convert to a Timespan
* @return {Timespan}
*/
countdown.clone = function(map) {
var ts = countdown();
for (var key in map) {
if (map.hasOwnProperty(key)) {
ts[key] = map[key];
}
}
return ts;
};
module('countdown(...)');
test('Zero', function() {
var start = 0;
var end = 0;
var expected = countdown.clone({
start: new Date(0),
end: new Date(0),
units: countdown.ALL,
value: 0,
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, '');
});
test('1 ms', function() {
var start = 0;
var end = 1;
var expected = countdown.clone({
start: new Date(0),
end: new Date(1),
units: countdown.ALL,
value: 1,
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 1
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, '');
});
test('1 sec', function() {
var start = 10000;
var end = 11000;
var expected = countdown.clone({
start: new Date(10000),
end: new Date(11000),
units: countdown.ALL,
value: 1000,
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 1,
milliseconds: 0
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, '');
});
test('5 min, reversed', function() {
var start = (5 * 60 * 1000);
var end = 0;
var expected = countdown.clone({
start: new Date(5 * 60 * 1000),
end: new Date(0),
units: countdown.ALL,
value: -(5 * 60 * 1000),
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 5,
seconds: 0,
milliseconds: 0
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, '');
});
test('constant 1 month span, daily over 5 years', function() {
var daySpan = 24 * 60 * 60 * 1000;
var start = new Date(1999, 10, 1, 12, 0, 0);
var expected = countdown.clone({
start: start,
end: start,
value: 0,
units: countdown.ALL,
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 1,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
});
for (var t=0, range=5*365.2425; t<range; t++) {
// end should always be one month away
var end = new Date(start.getTime());
end.setUTCMonth( end.getUTCMonth()+1 );
// skip situations like 'Jan 31st + month'
if (end.getUTCMonth() === start.getUTCMonth()+1) {
expected.start = start;
expected.end = end;
expected.value = end.getTime() - start.getTime();
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, '');
}
// add a day
start = new Date( start.getTime()+daySpan );
}
});
test('contiguous daily countdown over 83 weeks', function() {
var daySpan = 24 * 60 * 60 * 1000;
var units = countdown.WEEKS | countdown.DAYS | countdown.HOURS;
var start = new Date(2007, 10, 10, 5, 30, 0);
var end = new Date(2009, 5, 14, 16, 0, 0);
var expected = { weeks: 83, days: 1, hours: 9.5 };
while (start.getTime() < end.getTime()) {
var actual = countdown(start, end, units, 0, 20);
actual = {
weeks: actual.weeks,
days: actual.days,
hours: actual.hours
};
same(actual, expected, '');
// add a day
start = new Date( start.getTime()+daySpan );
// store
if (actual.days) {
expected = {
weeks: actual.weeks,
days: actual.days-1,
hours: actual.hours
};
} else {
expected = {
weeks: actual.weeks-1,
days: 6,
hours: actual.hours
};
}
}
});
test('contiguous daily countdown over 1 year 7 months', function() {
var daySpan = 24 * 60 * 60 * 1000;
var units = countdown.MONTHS | countdown.DAYS | countdown.HOURS;
var start = new Date(2006, 10, 10, 5, 30, 0);
var end = new Date(2008, 5, 14, 16, 0, 0);
var expected = { months: 19, days: 4, hours: 9.5 };
while (start.getTime() < end.getTime()) {
var actual = countdown(start, end, units, 0, 1);
actual = {
months: actual.months,
days: actual.days,
hours: actual.hours
};
same(actual, expected, '');
// add a day
start = new Date( start.getTime()+daySpan );
// set up next iteration
if (actual.days) {
expected = {
months: actual.months,
days: actual.days-1,
hours: actual.hours
};
} else {
var daysInStart = Math.round((new Date(start.getFullYear(), start.getMonth()+1, 15).getTime() - new Date(start.getFullYear(), start.getMonth(), 15).getTime()) / (24 * 60 * 60 * 1000));
expected = {
months: actual.months-1,
// the number of days in start month minus one
days: daysInStart-1,
hours: actual.hours
};
}
}
});
test('contiguous weekly countdown over 7 months, out of bounds max & digits', function() {
var daySpan = 24 * 60 * 60 * 1000;
var units = countdown.MONTHS | countdown.WEEKS | countdown.DAYS | countdown.HOURS;
var start = new Date(1999, 10, 10, 5, 30, 0);
var end = new Date(2001, 5, 14, 16, 0, 0);
// calc by days since easier
var prev = { months: 19, days: 4, hours: 9.5 };
while (start.getTime() < end.getTime()) {
var actual = countdown(start, end, units, -1, 100);
actual = {
months: actual.months,
weeks: actual.weeks,
days: actual.days,
hours: actual.hours
};
// convert to weeks just before compare
var expected = {
months: prev.months,
weeks: Math.floor(prev.days/7),
days: prev.days % 7,
hours: prev.hours
};
same(actual, expected, '');
// add a day
start = new Date( start.getTime()+daySpan );
// set up next iteration
if (prev.days) {
prev = {
months: prev.months,
days: prev.days-1,
hours: prev.hours
};
} else {
var daysInStart = Math.round((new Date(start.getFullYear(), start.getMonth()+1, 15).getTime() - new Date(start.getFullYear(), start.getMonth(), 15).getTime()) / (24 * 60 * 60 * 1000));
prev = {
months: prev.months-1,
// the number of days in start month minus one
days: daysInStart-1,
hours: prev.hours
};
}
}
});
test('contiguous daily count up over 10 years', function() {
var daySpan = 24 * 60 * 60 * 1000;
var units = countdown.MONTHS | countdown.DAYS;
var start = new Date(1995, 0, 1, 12, 0, 0);
var end = new Date(start.getTime());
var goalTime = new Date(2005, 0, 1, 12, 0, 0).getTime();
var expected = { months: 0, days: 0 };
while (end.getTime() < goalTime) {
var actual = countdown(start, end, units);
actual = {
months: actual.months,
days: actual.days
};
same(actual, expected, '');
var daysInEnd = Math.round((new Date(end.getFullYear(), end.getMonth()+1, 15).getTime() - new Date(end.getFullYear(), end.getMonth(), 15).getTime()) / (24 * 60 * 60 * 1000));
// add a day
end = new Date( end.getTime()+daySpan );
// set up next iteration
// compare to the number of days in before month end
if (actual.days < daysInEnd-1) {
expected = {
months: actual.months,
days: actual.days+1
};
} else {
expected = {
months: actual.months+1,
days: 0
};
}
}
});
test('Underflow bug', function() {
var start = new Date(2011, 11, 1);
var end = new Date(2011, 11, 31, 23, 59, 59, 999);
var expected = countdown.clone({
start: new Date(2011, 11, 1),
end: new Date(2011, 11, 31, 23, 59, 59, 999),
units: countdown.ALL,
value: end.getTime() - start.getTime(),
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 4,
days: 2,
hours: 23,
minutes: 59,
seconds: 59,
milliseconds: 999
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, ''+start+' => '+end);
});
test('Before leap day', function() {
var start = new Date(2012, 1, 28, 13, 14, 30, 109);
var end = new Date(2012, 1, 29, 17, 46, 22, 111);// Leap day 2012
var expected = countdown.clone({
start: new Date(2012, 1, 28, 13, 14, 30, 109),
end: new Date(2012, 1, 29, 17, 46, 22, 111),
units: countdown.ALL,
value: end.getTime() - start.getTime(),
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 0,
days: 1,
hours: 4,
minutes: 31,
seconds: 52,
milliseconds: 2
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, ''+start+' => '+end);
});
test('After leap day (local)', function() {
var start = new Date(2012, 1, 29, 17, 46, 22, 111);// Leap day 2012
var end = new Date(2012, 2, 1, 13, 14, 30, 109);
var expected = countdown.clone({
start: new Date(2012, 1, 29, 17, 46, 22, 111),
end: new Date(2012, 2, 1, 13, 14, 30, 109),
units: countdown.ALL,
value: end.getTime() - start.getTime(),
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 19,
minutes: 28,
seconds: 7,
milliseconds: 998
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, ''+start+' => '+end);
});
test('After leap day (UTC)', function() {
var start = new Date(1330537582111);// Leap day 2012
var end = new Date(1330607670109);
var expected = countdown.clone({
start: new Date(1330537582111),
end: new Date(1330607670109),
units: countdown.ALL,
value: end.getTime() - start.getTime(),
millennia: 0,
centuries: 0,
decades: 0,
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 19,
minutes: 28,
seconds: 7,
milliseconds: 998
});
var actual = countdown(start, end, countdown.ALL);
same(actual, expected, ''+start+' => '+end);
});
test('Almost 2 minutes, rounded', function() {
var start = new Date(915220800000);
var end = new Date(915220919999);
var expected = countdown.clone({
start: new Date(915220800000),
end: new Date(915220919999),
units: countdown.DEFAULTS,
value: 119999,
years: 0,
months: 0,
days: 0,
hours: 0,
minutes: 2,
seconds: 0
});
var actual = countdown(start, end, countdown.DEFAULTS);
same(actual, expected, ''+start+' => '+end);
});
test('Almost 2 minutes, rounded 2 digits', function() {
var start = new Date(915220800000);
var end = new Date(915220919999);
var expected = countdown.clone({
start: new Date(915220800000),
end: new Date(915220919999),
units: countdown.DEFAULTS,
value: 119999,
years: 0,
months: 0,
days: 0,
hours: 0,
minutes: 2,
seconds: 0
});
var actual = countdown(start, end, countdown.DEFAULTS, NaN, 2);
same(actual, expected, ''+start+' => '+end);
});
test('Almost 2 minutes, full 3 digits', function() {
var start = new Date(915220800000);
var end = new Date(915220919999);
var expected = countdown.clone({
start: new Date(915220800000),
end: new Date(915220919999),
units: countdown.DEFAULTS,
value: 119999,
years: 0,
months: 0,
days: 0,
hours: 0,
minutes: 1,
seconds: 59.999
});
var actual = countdown(start, end, countdown.DEFAULTS, 0, 3);
same(actual, expected, ''+start+' => '+end);
});
}catch(ex){alert(ex);} |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 11c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 2c0-3.31-2.69-6-6-6s-6 2.69-6 6c0 2.22 1.21 4.15 3 5.19l1-1.74c-1.19-.7-2-1.97-2-3.45 0-2.21 1.79-4 4-4s4 1.79 4 4c0 1.48-.81 2.75-2 3.45l1 1.74c1.79-1.04 3-2.97 3-5.19zM12 3C6.48 3 2 7.48 2 13c0 3.7 2.01 6.92 4.99 8.65l1-1.73C5.61 18.53 4 15.96 4 13c0-4.42 3.58-8 8-8s8 3.58 8 8c0 2.96-1.61 5.53-4 6.92l1 1.73c2.99-1.73 5-4.95 5-8.65 0-5.52-4.48-10-10-10z" />
, 'WifiTetheringTwoTone');
|
define("dest/cellula/0.4.1/cellula-util", [ "dest/cellula/0.4.1/cellula-namespace" ], function(require, exports, module) {
/**
* @fileOverview Cellula Framework's core utility library definition.
* @description: a utility library for Cellula that provides a lot of the functional programming support
* @namespace: Cellula
* @author: @hanyee
*
* thanks to underscore.js and json2.js
*/
var cellula = require("dest/cellula/0.4.1/cellula-namespace"), util = cellula._util;
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
var slice = util.slice = ArrayProto.slice, toString = util.toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty;
var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind;
var breaker = util.breaker = "breaker is used to break a loop";
var isArray = util.isArray = function(obj) {
if (nativeIsArray) return nativeIsArray(obj);
return toString.call(obj) === "[object Array]";
};
var isObject = util.isObject = function(obj) {
//return obj === Object(obj);
return obj == null ? false : toString.call(obj) === "[object Object]";
};
var isString = util.isString = function(obj) {
return toString.call(obj) === "[object String]";
};
var isFunction = util.isFunction = function(obj) {
return toString.call(obj) === "[object Function]";
};
var isArguments = util.isArguments = function(obj) {
return toString.call(obj) === "[object Arguments]";
};
var isNodeList = util.isNodeList = function(obj) {
return toString.call(obj) === "[object NodeList]";
};
var isClass = util.isClass = function(func) {
// deprecated
return isFunction(func) && func.toString() === classCtor().toString();
};
var has = util.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
var isEmpty = util.isEmpty = function(obj, isEnum) {
// isEnum is a flag that be used to judge enumerable properties of an object
if (!obj) return true;
if (isArray(obj) || isString(obj)) return obj.length === 0;
for (var key in obj) {
if (!(isEnum && !has(obj, key))) return false;
}
return true;
};
var iterator = util.iterator = function(v) {
return v;
};
// There is no guarantee that for...in will return the indexes in any particular order
// and it will return all enumerable properties,
// including those with non–integer names and those that are inherited.
var each = util.each = function(obj, fn, context, breaker) {
if (!obj) return;
var key;
if (breaker != null) {
for (key in obj) {
if (isObject(obj) && has(obj, key) || isArray(obj) && key in obj) {
// || obj === Object(obj)
if (fn.call(context, obj[key], key, obj) === breaker) return key;
}
}
} else {
if (nativeForEach && nativeForEach === obj.forEach) {
obj.forEach(fn, context);
} else {
for (key in obj) {
if (isObject(obj) && has(obj, key) || isArray(obj) && key in obj) {
fn.call(context, obj[key], key, obj);
}
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to ES 5 's native 'map' if available.
var map = util.map = function(obj, fn, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && nativeMap === obj.map) return obj.map(fn, context);
each(obj, function(value, index, list) {
results[results.length] = fn.call(context, value, index, list);
});
return results;
};
// Retrieve the names of an object's properties.
// Delegates to ES 5 's native 'Object.keys'
var keys = util.keys = function(obj) {
if (nativeKeys) return nativeKeys(obj);
if (obj !== Object(obj)) throw new TypeError("Invalid object");
var keys = [];
for (var key in obj) if (has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
var values = util.values = function(obj) {
return map(obj, iterator);
};
var emptyFunc = util.emptyFunc = function() {};
var bind = util.bind = function(func, context) {
var bound, args;
if (nativeBind && nativeBind === func.bind) return nativeBind.call(func, context);
// to fix the inconformity with es5
if (!isFunction(func)) throw new TypeError();
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, slice.call(arguments));
emptyFunc.prototype = func.prototype;
var self = new emptyFunc();
var result = func.apply(self, slice.call(arguments));
if (Object(result) === result) return result;
return self;
};
};
// Safely convert anything iterable into a real, live array.
var toArray = util.toArray = function(obj) {
if (!obj) return [];
if (isArray(obj) || isArguments(obj)) return slice.call(obj);
// return a new array, not obj itself
return values(obj);
};
var toArrayByLen = util.toArrayByLen = function(obj) {
var ret = [];
if (obj.length) for (var ii = 0; ii < obj.length; ret[ii] = obj[ii++]) {}
return ret;
};
var mix = util.mix = function() {
var ret = arguments[0] || {};
for (var i = 1, l = arguments.length; i < l; i++) {
var t = arguments[i];
if (isObject(t) || isArray(t)) {
// if Array is not allowed --> isObject(t)
for (var n in t) {
ret[n] = t[n];
}
}
}
return ret;
};
var deepMix = util.deepMix = function() {
var ret = arguments[0] || {};
for (var i = 1, l = arguments.length; i < l; i++) {
var t = arguments[i];
if (isObject(t) || isArray(t)) {
//if Array is not allowed --> util.isObject(t)
for (var n in t) {
ret[n] = isObject(ret[n]) && isObject(t[n]) ? deepMix({}, ret[n], t[n]) : t[n];
}
}
}
return ret;
};
var copy = util.copy = function(obj) {
if (!(isObject(obj) || isArray(obj))) return obj;
return isArray(obj) ? obj.slice() : mix({}, obj);
};
var aspect = util.aspect = function(obj) {
if (!util.isObject(obj)) throw new Error("invalid parameter!");
var __aspect__ = {
//afterReturning
//afterThrowing
//destroy
before: function(name, func, context) {
if (!util.isString(name) || !util.isFunction(func)) throw new Error("invalid parameter!");
var origin = obj[name], args = context ? util.slice.call(arguments, 3) : [];
obj[name] = function() {
func.apply(context || obj, args);
return origin.apply(obj, arguments);
};
},
after: function(name, func, context) {
if (!util.isString(name) || !util.isFunction(func)) throw new Error("invalid parameter!");
var origin = obj[name], args = context ? util.slice.call(arguments, 3) : [];
obj[name] = function() {
var ret = origin.apply(obj, arguments);
func.apply(context || obj, args);
return ret;
};
},
wrap: function(name, func) {
// around
if (!util.isString(name) || !util.isFunction(func)) throw new Error("invalid parameter!");
var origin = obj[name];
obj[name] = function() {
// arguments belongs to origin
var temp = obj._origin;
obj._origin = origin;
var ret = func.apply(obj, arguments);
obj._origin = temp;
return ret;
};
}
};
return __aspect__;
};
// console
var nativeConsole = window ? window.console || {} : {};
each([ "log", "info", "warn", "error" ], function(v) {
util[v] = nativeConsole[v] && nativeConsole[v].apply ? function() {
nativeConsole[v].apply(nativeConsole, toArrayByLen(arguments));
} : emptyFunc;
});
var makeTpl = util.makeTpl = function(tpl, data) {
var newTpl = tpl;
for (n in data) {
var reg = new RegExp("(\\$\\-\\{" + n + "\\})", "g");
newTpl = newTpl.replace(reg, data[n]);
}
// replace extra placeholders with '' || if there's no matching data for it
var r = new RegExp("(\\$\\-\\{[/#a-zA-Z0-9]+\\})", "g");
newTpl = newTpl.replace(r, "");
return newTpl;
};
var parseTpl = util.parseTpl = function(tpl, data) {
if (!isString(tpl) || !isObject(data)) return tpl;
var newTpl = tpl, tagReg = new RegExp("\\$\\-\\{#(.*)\\}");
function parse(prop) {
var regHead = new RegExp("(\\$\\-\\{#" + prop + "\\})", "g"), regTail = new RegExp("(\\$\\-\\{/" + prop + "\\})", "g"), reg = new RegExp("(\\$\\-\\{#" + prop + "\\})(.*)(\\$\\-\\{/" + prop + "\\})", "g");
if (data[prop] === false || !data[prop]) {
newTpl = newTpl.replace(reg, "");
} else if (isArray(data[prop])) {
var r = reg.exec(tpl);
if (r) {
var t = r[2], s = "", d = data[prop];
for (var i = 0; i < d.length; i++) {
s += this.parseTpl.call(this, t, d[i]);
}
newTpl = newTpl.replace(reg, s);
}
} else {
newTpl = newTpl.replace(regHead, "").replace(regTail, "");
}
return newTpl;
}
for (var n in data) {
//newTpl = parse.call(this, n, newTpl);
parse.call(this, n);
}
while (tagReg.test(newTpl)) {
var p = tagReg.exec(newTpl)[1];
p = p.substring(0, p.indexOf("}"));
// to be strict
parse.call(this, p);
}
return makeTpl(newTpl, data);
};
util.JSON = {};
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = {
// table of character substitutions
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\"
}, rep;
function quote(string) {
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function(a) {
var c = meta[a];
return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
var i, // The loop counter.
k, // The member key.
v, // The member value.
length, mind = gap, partial, value = holder[key];
if (value && typeof value === "object" && typeof value.toJSON === "function") {
value = value.toJSON(key);
}
if (typeof rep === "function") {
value = rep.call(holder, key, value);
}
switch (typeof value) {
case "string":
return quote(value);
case "number":
return isFinite(value) ? String(value) : "null";
case "boolean":
case "null":
return String(value);
case "object":
if (!value) {
return "null";
}
gap += indent;
partial = [];
if (Object.prototype.toString.apply(value) === "[object Array]") {
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || "null";
}
v = partial.length === 0 ? "[]" : gap ? "[\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "]" : "[" + partial.join(",") + "]";
gap = mind;
return v;
}
if (rep && typeof rep === "object") {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === "string") {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ": " : ":") + v);
}
}
}
} else {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ": " : ":") + v);
}
}
}
}
v = partial.length === 0 ? "{}" : gap ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}" : "{" + partial.join(",") + "}";
gap = mind;
return v;
}
}
util.JSON.stringify = function(value, replacer, space) {
var i;
gap = "";
indent = "";
if (typeof space === "number") {
for (i = 0; i < space; i += 1) {
indent += " ";
}
} else if (typeof space === "string") {
indent = space;
}
rep = replacer;
if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) {
throw new Error("JSON.stringify");
}
return str("", {
"": value
});
};
util.JSON.parse = function(text, reviver) {
var j;
function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === "object") {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function(a) {
return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
});
}
if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
j = eval("(" + text + ")");
return typeof reviver === "function" ? walk({
"": j
}, "") : j;
}
throw new SyntaxError("JSON.parse");
};
var trim = util.trim = function(s) {
return isString(s) ? s.replace(/^\s+/g, "").replace(/\s+$/g, "") : s;
};
var hasClass = util.hasClass = function(node, className) {
if (node && node.nodeType == 1) {
className = " " + className + " ";
return (" " + node.className + " ").replace(/[\n\t\r]/g, " ").indexOf(className) > -1;
}
return false;
};
var addClass = util.addClass = function(node, className) {
if (node && node.nodeType == 1) {
if (!trim(node.className)) return node.className = className;
if (!hasClass(node, className)) node.className = trim(node.className) + " " + className;
}
};
var removeClass = util.removeClass = function(node, className) {
if (hasClass(node, className)) node.className = trim((" " + node.className + " ").replace(/[\n\t\r]/g, " ").replace(" " + className + " ", " "));
};
var getElementsByClassName = util.getElementsByClassName = function(searchClass, node, tag) {
node = node || document;
if (node.getElementsByClassName) {
return node.getElementsByClassName(searchClass);
} else {
tag = tag || "*";
var ret = [], els = node.getElementsByTagName(tag), //var els = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag);
i = els.length, reg = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
while (--i >= 0) {
if (reg.test(els[i].className)) {
ret.push(els[i]);
}
}
return ret;
}
};
module.exports = util;
}); |
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css']
},
dev: {
env: require('./dev.env'),
port: 8080,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:8080/',
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}
|
'use strict'
const { Command } = require('discord.js-commando');
const { symbols, hierarchy, top, aliases } = require("../../data/ranks.js");
module.exports = class LeaderpromoteCommand extends Command {
constructor(client) {
super(client, {
name: 'leader',
group: 'mod',
memberName: 'leader',
description: 'Promote a user to leader.\nRequires &, ~',
examples: ['leader Spindlyskit'],
aliases: ['globalleader', 'leaderistrator', 'globalleaderistrator'],
args: [
{
key: 'member',
prompt: 'What member should be promoted?',
type: 'member'
}
]
});
}
hasPermission(msg) {
return msg.client.rankmanager.hasRank("&", msg.guild, msg.member).ret;
}
run(msg, { member }) {
let rank = "&";
let client = msg.client;
let rankmanager = client.rankmanager;
let role = rankmanager.getRank(rank, msg.guild).id;
if (!rankmanager.hasRank(rank, msg.guild, msg.member).ret);
for (let i=0; i<hierarchy.length; i++) {
let tr = rankmanager.getRank(hierarchy[i], msg.guild).id;
console.log(`${hierarchy[i]}: ${tr}`)
if (member.roles.has(tr) && tr != role) {
member.removeRole(tr, `${msg.author.tag} used leader command in ${msg.channel.name}`)
.catch(console.error);
}
}
member.addRole(role, `${msg.author.tag} used leader command in ${msg.channel.name}`)
.then(role => msg.say(`Added ${rank} to ${member.user.tag}`))
.catch(console.error);
}
};
|
<%= application_name %> = (function($, public_) {
public_.Collections.<%= backbone_collection_name %> = new Backbone.Collection({
model: <%= backbone_model_name %>,
url: "<%= rails_collection_name %>"
return public_;
})
})(jQuery, <%= application_name %>);
|
var express = require('express');
var router = express.Router();
var ApiController = require('../controllers').api;
router.route('/')
.get(ApiController.api);
module.exports = router;
|
define('hb.debug', function() {
var errors = {
E0: '',
E1: '',
E2: '',
E3: '',
E4: '',
E5: '',
E6a: '',
E6b: '',
E7: '',
E8: '',
E9: '',
E10: '',
E11: '',
E12: ''
};
var fn = function() {};
var statItem = {
clear:fn,
next:fn,
inc:fn,
dec:fn
};
var db = {log: fn, info: fn, warn: fn, error: fn, stat: function() {return statItem;}, getStats: fn, flushStats: fn};
// they need to throw their number so we can find the error.
// this may be helpful for scripts like capture so it can report the error
// to the server when it is caught in production.
for(var i in errors) {
errors[i] = i;
}
return {
ignoreErrors:true,
log: fn,
info: fn,
warn: fn,
register: function() {
return db;
},
liveStats: fn,
getStats: fn,
logStats: fn,
stats: fn,
errors:errors
};
}); |
var I18n = require("i18n-js");
var React = require("react");
var Form = require("./Form.jsx");
module.exports = React.createClass({
linkClicked: function(e) {
e.preventDefault();
alert("Yay react still works inside translated components \\o/");
},
render: function() {
return (
<div className="Content">
<p translate="yes">
Create <input key="num" size="5" /> groups
</p>
<p translate="yes">
<a href="#" onClick={this.linkClicked}>Click here</a> to get started
</p>
<Form/>
</div>
);
}
});
|
#!/usr/bin/env node
var API = require('../../index').Stateless;
var ImageService = require('../../index').ImageService;
var program = require('commander');
program
.version('1.0.0')
.option('-a, --authtoken <token>', 'Set the auth token to use')
.option('-g, --group_id <id>', 'The group_id to use')
.option('-r, --results_id <id>', 'The results_id to use')
.option('-m, --message_id <id>', 'The message_id to use')
.option('-b, --bot_id <id>', 'The message_id to use')
.option('-n, --name <string>', 'The bot name to use')
.option('-t, --text <string>', 'The text to use for a bot message. Be sure to quote it!')
.option('-o, --opts <JSON>', 'supply a json object as options. Be sure to wrap it in double-quotes!')
.option('-i, --image <PATH>', 'an image to upload to the ImageService. Use with ImageService.post')
;
var justPrintEverythingCallback = function(err, ret) {
if (!err) {
console.log(JSON.stringify(ret, null, " "));
} else {
console.log("ERROR!", err)
}
}
var requireArgs = function(argsArr) {
var notGood = false;
for (var i in argsArr) {
if (!program[argsArr[i]]) {
console.log("No " + argsArr[i] + " specified.")
notGood = true;
}
}
if (notGood) {
console.log("For more info, please run ./cli.js --help")
process.exit(1);
}
}
/************************************************************************
* Groups
***********************************************************************/
program
.command('Groups.index')
.description("List the authenticated user's active groups.")
.action(function(env) {
API.Groups.index(program.authtoken, justPrintEverythingCallback);
});
program
.command('Groups.former')
.description("List they groups you have left but can rejoin.")
.action(function(env) {
API.Groups.former(program.authtoken, justPrintEverythingCallback);
});
program
.command('Groups.show')
.description("List a specific group.")
.action(function(env) {
requireArgs(["group_id"]);
API.Groups.show(program.authtoken, program.group_id, justPrintEverythingCallback);
});
program
.command('Groups.create')
.description("Create a new group.")
.action(function(env) {
requireArgs(["opts"]);
API.Groups.create(program.authtoken, JSON.parse(program.opts), justPrintEverythingCallback);
});
program
.command('Groups.update')
.description("Update a group after creation.")
.action(function(env) {
requireArgs(["opts", "group_id"]);
API.Groups.update(program.authtoken, program.group_id, JSON.parse(program.opts), justPrintEverythingCallback);
});
program
.command('Groups.destroy')
.description("Disband a group. This action is only available to the group creator.")
.action(function(env) {
requireArgs(["group_id"]);
API.Groups.destroy(program.authtoken, program.group_id, justPrintEverythingCallback);
});
/************************************************************************
* Members
***********************************************************************/
program
.command('Members.add')
.description("Add members to a group.")
.action(function(env) {
requireArgs(["opts", "group_id"]);
API.Members.add(program.authtoken, program.group_id, JSON.parse(program.opts), justPrintEverythingCallback);
});
program
.command('Members.results')
.description("Get the membership results from an add call.")
.action(function(env) {
requireArgs(["results_id", "group_id"]);
API.Members.results(program.authtoken, program.group_id, program.results_id, justPrintEverythingCallback);
});
/************************************************************************
* Messages
***********************************************************************/
program
.command('Messages.index')
.description("Messages for a group. Return 20, can request before_id or after_id.")
.action(function(env) {
requireArgs(["group_id"]);
var opts = {};
if (program.opts)
opts = JSON.parse(program.opts);
API.Messages.index(program.authtoken, program.group_id, opts, justPrintEverythingCallback);
});
program
.command('Messages.create')
.description("Send a message to a group.")
.action(function(env) {
requireArgs(["opts", "group_id"]);
API.Messages.create(program.authtoken, program.group_id, JSON.parse(program.opts), justPrintEverythingCallback);
});
/************************************************************************
* Direct Messages
***********************************************************************/
program
.command('DirectMessages.index')
.description("Fetch direct messages between two users. Return 20, can request before_id or after_id.")
.action(function(env) {
requireArgs(["opts"]);
var opts = {};
if (program.opts)
opts = JSON.parse(program.opts);
API.DirectMessages.index(program.authtoken, opts, justPrintEverythingCallback);
});
program
.command('DirectMessages.create')
.description("Send a message to another user.")
.action(function(env) {
requireArgs(["opts"]);
API.DirectMessages.create(program.authtoken, JSON.parse(program.opts), justPrintEverythingCallback);
});
/************************************************************************
* Likes
***********************************************************************/
program
.command('Likes.create')
.description("Like a message.")
.action(function(env) {
requireArgs(["message_id", "group_id"]);
API.Likes.create(program.authtoken, program.group_id, program.message_id, justPrintEverythingCallback);
});
program
.command('Likes.destroy')
.description("Unlike a liked message.")
.action(function(env) {
requireArgs(["message_id", "group_id"]);
API.Likes.destroy(program.authtoken, program.group_id, program.message_id, justPrintEverythingCallback);
});
/************************************************************************
* Bots
***********************************************************************/
program
.command('Bots.create')
.description("Create a bot.")
.action(function(env) {
requireArgs(["name", "group_id"]);
var opts = {};
if (program.opts)
opts = JSON.parse(program.opts);
API.Bots.create(program.authtoken, program.name, program.group_id, opts, justPrintEverythingCallback);
});
program
.command('Bots.post')
.description("Post a message as a bot")
.action(function(env) {
requireArgs(["bot_id", "text"]);
var opts = {};
if (program.opts)
opts = JSON.parse(program.opts);
API.Bots.post(program.authtoken, program.bot_id, program.text, opts, justPrintEverythingCallback);
});
program
.command('Bots.index')
.description("List bots you have created")
.action(function(env) {
API.Bots.index(program.authtoken, justPrintEverythingCallback);
});
program
.command('Bots.destroy')
.description("Remove a bot that you have created")
.action(function(env) {
requireArgs(["bot_id"]);
API.Bots.destroy(program.authtoken, program.bot_id, justPrintEverythingCallback);
});
/************************************************************************
* Users
***********************************************************************/
program
.command('Users.me')
.description("Get details about the authenticated user.")
.action(function(env) {
API.Users.me(program.authtoken, justPrintEverythingCallback);
});
/************************************************************************
* ImageService
***********************************************************************/
program
.command('ImageService.post')
.description("Upload an image to GroupMe's ImageService")
.action(function(env) {
requireArgs(["image"]);
ImageService.post(program.image, justPrintEverythingCallback);
});
program.parse(process.argv);
requireArgs(["authtoken"]); |
'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var Holodeck = require('../../../holodeck'); /* jshint ignore:line */
var Request = require(
'../../../../../lib/http/request'); /* jshint ignore:line */
var Response = require(
'../../../../../lib/http/response'); /* jshint ignore:line */
var RestException = require(
'../../../../../lib/base/RestException'); /* jshint ignore:line */
var Twilio = require('../../../../../lib'); /* jshint ignore:line */
var client;
var holodeck;
describe('RatePlan', function() {
beforeEach(function() {
holodeck = new Holodeck();
client = new Twilio('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'AUTHTOKEN', {
httpClient: holodeck
});
});
it('should generate valid list request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.wireless.v1.ratePlans.list();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var url = 'https://wireless.twilio.com/v1/RatePlans';
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid read_empty response',
function() {
var body = JSON.stringify({
'meta': {
'first_page_url': 'https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0',
'key': 'rate_plans',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0'
},
'rate_plans': []
});
holodeck.mock(new Response(200, body));
var promise = client.wireless.v1.ratePlans.list();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid read_full response',
function() {
var body = JSON.stringify({
'meta': {
'first_page_url': 'https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0',
'key': 'rate_plans',
'next_page_url': null,
'page': 0,
'page_size': 50,
'previous_page_url': null,
'url': 'https://wireless.twilio.com/v1/RatePlans?PageSize=50&Page=0'
},
'rate_plans': [
{
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'unique_name': 'unique_name',
'data_enabled': true,
'data_limit': 1000,
'data_metering': 'pooled',
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'friendly_name': 'friendly_name',
'messaging_enabled': true,
'voice_enabled': true,
'national_roaming_enabled': true,
'national_roaming_data_limit': 1000,
'international_roaming': [
'data',
'messaging',
'voice'
],
'international_roaming_data_limit': 1000,
'sid': 'WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
}
]
});
holodeck.mock(new Response(200, body));
var promise = client.wireless.v1.ratePlans.list();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid fetch request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.wireless.v1.ratePlans('WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
sid: 'WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
var url = _.template('https://wireless.twilio.com/v1/RatePlans/<%= sid %>')(solution);
holodeck.assertHasRequest(new Request({
method: 'GET',
url: url
}));
}
);
it('should generate valid fetch response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'unique_name': 'unique_name',
'data_enabled': true,
'data_limit': 1000,
'data_metering': 'pooled',
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'friendly_name': 'friendly_name',
'messaging_enabled': true,
'voice_enabled': true,
'national_roaming_enabled': true,
'national_roaming_data_limit': 1000,
'international_roaming': [
'data',
'messaging',
'voice'
],
'international_roaming_data_limit': 1000,
'sid': 'WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
});
holodeck.mock(new Response(200, body));
var promise = client.wireless.v1.ratePlans('WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid create request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.wireless.v1.ratePlans.create();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var url = 'https://wireless.twilio.com/v1/RatePlans';
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url
}));
}
);
it('should generate valid create response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'unique_name': 'unique_name',
'data_enabled': true,
'data_limit': 1000,
'data_metering': 'pooled',
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'friendly_name': 'friendly_name',
'messaging_enabled': true,
'voice_enabled': true,
'national_roaming_enabled': true,
'national_roaming_data_limit': 1000,
'international_roaming': [
'data',
'messaging',
'voice'
],
'international_roaming_data_limit': 1000,
'sid': 'WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
});
holodeck.mock(new Response(201, body));
var promise = client.wireless.v1.ratePlans.create();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid update request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.wireless.v1.ratePlans('WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').update();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
sid: 'WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
var url = _.template('https://wireless.twilio.com/v1/RatePlans/<%= sid %>')(solution);
holodeck.assertHasRequest(new Request({
method: 'POST',
url: url
}));
}
);
it('should generate valid update response',
function() {
var body = JSON.stringify({
'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'unique_name': 'unique_name',
'data_enabled': true,
'data_limit': 1000,
'data_metering': 'pooled',
'date_created': '2015-07-30T20:00:00Z',
'date_updated': '2015-07-30T20:00:00Z',
'friendly_name': 'friendly_name',
'messaging_enabled': true,
'voice_enabled': true,
'national_roaming_enabled': true,
'national_roaming_data_limit': 1000,
'international_roaming': [
'data',
'messaging',
'voice'
],
'international_roaming_data_limit': 1000,
'sid': 'WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'url': 'https://wireless.twilio.com/v1/RatePlans/WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
});
holodeck.mock(new Response(200, body));
var promise = client.wireless.v1.ratePlans('WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').update();
promise = promise.then(function(response) {
expect(response).toBeDefined();
}, function() {
throw new Error('failed');
});
promise.done();
}
);
it('should generate valid remove request',
function() {
holodeck.mock(new Response(500, '{}'));
var promise = client.wireless.v1.ratePlans('WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').remove();
promise = promise.then(function() {
throw new Error('failed');
}, function(error) {
expect(error.constructor).toBe(RestException.prototype.constructor);
});
promise.done();
var solution = {
sid: 'WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
};
var url = _.template('https://wireless.twilio.com/v1/RatePlans/<%= sid %>')(solution);
holodeck.assertHasRequest(new Request({
method: 'DELETE',
url: url
}));
}
);
it('should generate valid delete response',
function() {
var body = JSON.stringify(null);
holodeck.mock(new Response(204, body));
var promise = client.wireless.v1.ratePlans('WPaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').remove();
promise = promise.then(function(response) {
expect(response).toBe(true);
}, function() {
throw new Error('failed');
});
promise.done();
}
);
});
|
/* global module:false */
module.exports = function(grunt) {
var port = grunt.option('port') || 8000;
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner:
'/*!\n' +
' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
' * http://lab.hakim.se/reveal-js\n' +
' * MIT licensed\n' +
' *\n' +
' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' +
' */'
},
qunit: {
files: [ 'test/*.html' ]
},
uglify: {
options: {
banner: '<%= meta.banner %>\n'
},
build: {
src: 'js/reveal.js',
dest: 'js/reveal.min.js'
}
},
cssmin: {
compress: {
files: {
'css/reveal.min.css': [ 'css/reveal.css' ]
}
}
},
sass: {
main: {
files: {
'css/theme/adobe.css': 'css/theme/source/adobe.scss',
'css/theme/default.css': 'css/theme/source/default.scss'
}
}
},
jshint: {
options: {
curly: false,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
eqnull: true,
browser: true,
expr: true,
globals: {
head: false,
module: false,
console: false,
unescape: false
}
},
files: [ 'Gruntfile.js', 'js/reveal.js' ]
},
connect: {
server: {
options: {
port: port,
base: '.'
}
}
},
zip: {
'reveal-js-presentation.zip': [
'index.html',
'css/**',
'js/**',
'lib/**',
'images/**',
'plugin/**'
]
},
watch: {
main: {
files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ],
tasks: 'default'
},
theme: {
files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ],
tasks: 'themes'
}
}
});
// Dependencies
grunt.loadNpmTasks( 'grunt-contrib-qunit' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.loadNpmTasks( 'grunt-contrib-sass' );
grunt.loadNpmTasks( 'grunt-contrib-connect' );
grunt.loadNpmTasks( 'grunt-zip' );
// Default task
grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] );
// Theme task
grunt.registerTask( 'themes', [ 'sass' ] );
// Package presentation to archive
grunt.registerTask( 'package', [ 'default', 'zip' ] );
// Serve presentation locally
grunt.registerTask( 'serve', [ 'connect', 'watch' ] );
// Run tests
grunt.registerTask( 'test', [ 'jshint', 'qunit' ] );
};
|
/**
* Created by liumeng on 2017/9/13.
*/
var router = require('koa-router')();
var equipType_controller = require('../../app/controllers/equipType');
router.get('/list', equipType_controller.list);
router.get('/delete/:id', equipType_controller.delete);
router.post('/save',equipType_controller.save);
module.exports = router; |
'use babel'
import LinterJsonLintProvider from './linter-json-lint-provider'
import { install } from 'atom-package-deps'
const { atom } = global
export default {
config: {
allowComments: {
type: 'boolean',
default: false
}
},
activate () {
if (!atom.inSpecMode()) {
install('linter-json-lint')
}
},
provideLinter: () => LinterJsonLintProvider
}
|
'use strict';
var reporter = require('../../../index');
var assertHtmlReports = require('../../assert/assertHtmlReports');
var path = require('path');
var fs = require('fs');
var find = require('find');
var hooks = function() {
this.Before(function(scenario, callback) {
console.log('console logs should not break the report');
this.scenario = scenario;
callback();
});
this.Before({tags: ['@testPassing']}, function(scenario, callback) {
scenario.attach('Tests INFO will print here.<br>To attach INFO to Any steps, use scenario.attach function in your step definitions as shown below.<br><br>If you pass HTML\'s to scenario.attach then reporter will format accordingly <br>' +
'<br>Simple String : scenario.attach(\'sample data\')' +
'<br>Pretty JSON : scenario.attach(JSON.stringify(json, null, 2))' +
'<br>HTML Link : scenario.attach(\'format the link with html-a tag\'');
callback();
});
this.After({tags: ['@testPassing']}, function(scenario, callback) {
callback();
});
this.registerHandler('AfterFeatures', function(features, callback) {
var theme = {
bootstrap: 'bootstrap',
foundation: 'foundation',
simple: 'simple'
};
var outputDirectory = 'test/report/';
var jsonFile = 'test/report/cucumber_report.json';
var jsonDir = 'test/report/multi';
function removeReports() {
var files = find.fileSync(/\.html/, outputDirectory);
files.map(function(file) {
fs.unlinkSync(file);
});
}
function getOptions(theme) {
return {
theme: theme,
output: path.join(outputDirectory, 'cucumber_report_' + theme + '.html'),
reportSuiteAsScenarios: true,
launchReport: true,
metadata: {
"App Version": "0.3.2",
"Test Environment": "STAGING",
"Browser": "Chrome 54.0.2840.98",
"Platform": "Windows 10",
"Parallel": "Scenarios",
"Executed": "Remote"
}
};
}
function getJsonFileOptions(theme) {
var options = getOptions(theme);
options.jsonFile = jsonFile;
return options;
}
function getJsonDirOptions(theme) {
var options = getOptions(theme);
options.jsonDir = jsonDir;
return options;
}
function assertJsonFile() {
//Generate Bootstrap theme report
reporter.generate(getJsonFileOptions(theme.bootstrap));
//Generate Foundation theme report
reporter.generate(getJsonFileOptions(theme.foundation));
//Generate Simple theme report
reporter.generate(getJsonFileOptions(theme.simple));
//assert reports
assertHtmlReports(outputDirectory);
}
function assertJsonDir() {
//Generate Bootstrap theme report
reporter.generate(getJsonDirOptions(theme.bootstrap));
//Generate Foundation theme report
reporter.generate(getJsonDirOptions(theme.foundation));
//Generate Simple theme report
reporter.generate(getJsonDirOptions(theme.simple));
//assert reports
assertHtmlReports(outputDirectory);
}
assertJsonDir();
removeReports();
assertJsonFile();
callback();
});
};
module.exports = hooks; |
import Component from '../Component'
const Delayer = ms => Component((v, next) => {
setTimeout(() => next(v), ms)
})
export default Delayer
|
'use strict';
module.exports = function addProjectFn(proto) {
proto.projectsGet = function projectsGet(callback) {
return this._get('/projects', callback);
};
proto.projectsPost = function projectsPost(data, callback) {
return this._post('/projects', data, callback);
};
proto.projectGet = function projectGet(slug, callback) {
if(typeof slug !== 'string') {
callback = slug;
slug = this.project;
}
return this._get('/project/' + slug, callback);
};
proto.projectPost = function projectPost(slug, data, callback) {
if(typeof slug !== 'string') {
callback = data;
data = slug;
slug = this.project;
}
return this._post('/project/' + slug, data, callback);
};
proto.projectDelete = function projectDelete(slug, callback) {
if(typeof slug !== 'string') {
callback = slug;
slug = this.project;
}
return this._delete('/project/' + slug, callback);
};
}; |
/*
* Copyright (c) 2013 - Andrey Boomer - andrey.boomer at gmail.com
* icq: 454169
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
v1.0 - release 24.01.2013
v1.1 - 11.02.2013
- добавлена перезагрузка формы после отсылки файла
чтобы не приходилось перезагружать страницу
Использование:
$(<element>).jInputFile();
Параметры:
url - Путь к обработчику POST
filename - Имя файла для загрузки в пост
iframe - Метод загрузки: если true то фреймом
heigth - Высота элемента в пикселах
width - Ширина в пикселах
Возвращаемые функции:
success: Загрузка завершена
selected: Когда один из файлов выбран
*/
(function($) {
$.widget("ui.jInputFile", {
// Опции по умолчанию
options: {
url: null,
filename: null,
reloaded: 0,
heigth: 30,
width: 250,
iframe: (/msie/.test(navigator.userAgent.toLowerCase()))? true : false
},
_create: function() {
if (this.options.iframe) {
var self = this;
$('<iframe />').attr({
src:'about:blank',
style: 'border: 0;heigth: '+ self.options.heigth +'px;width: '+ self.options.width +'px'
}).prependTo(self.element.parent()).css('overflow','hidden').load(function() {
if (self.options.reloaded != 0 ) {
self._trigger("success", null);
}
// Создаем дочернюю копию элемента инпута
self.element.parent().find('iframe')
.contents().find('body').append($("<form />").attr({
method:'POST',
action: self.options.url,
enctype:'multipart/form-data'
}).css('overflow','hidden'))
.children('form').append(self.element.clone(true).attr({
'name':self.options.filename,
'id':'file_iframe_upload'
}).css('overflow','hidden').show().change(function() {
self._trigger("selected", null);
}));
// Добавлем кнопки субмита и сброса формы:
self.element.parent().find('iframe').contents().find('body').children('form')
.append($('<input />').attr({
type:'submit',
value:'Загрузить',
class:'submit'
}).hide()).append($('<input />').attr({
type:'reset',
value:'Отчистить',
class:'reset'
}).hide());
// Считаем количество перезагрузок
self.options.reloaded = self.options.reloaded + 1;
});
self.element.hide();
} else {
this.element.wrap($('<form />').attr({ style: 'heigth: '+ this.options.heigth +'px;width: '+ this.options.width +'px', enctype: 'multipart/form-data' }));
this._create_ajax_from(this);
}
},
// отправляем данные
submit: function() {
if (this.options.iframe) {
this.element.parent().find('iframe').hide()
.contents().find('body').children('form').children('.submit').click();
this.element.parent().find('iframe').css('overflow','hidden');
} else {
this._submit_ajax_from();
}
},
// Отчищаем форму
clear: function() {
if (this.options.iframe) {
this.element.parent().find('iframe').show()
.contents().find('body').children('form').children('.reset').click();
} else {
$(this.element).parent().children('.reset').click();
$(this.element).parent().children('.jInputFile-filename').empty().append('невыбран файл');
$(this.element).parent().children('.jInputFile-fakeButton').button('option', 'disabled', false );
}
},
_create_ajax_from: function(self) {
self.element.hide();
if (self.options.filename !== null) {
self.element.attr('name',self.options.filename);
}
self.element.after($('<input />').attr({
type:'reset',
value:'Отчистить',
class:'reset'
}).hide());
self.element.after('<button class="jInputFile-fakeButton">Загрузить файл...</button><div class="jInputFile-filename" style="font-size:80%">невыбран файл</div>');
self.element.parent().children('.jInputFile-fakeButton')
.button({icons: {primary: 'ui-icon-plusthick'}})
.click(function( event ) {
self.element.parent().children("input[type='file']").click();
return false;
});
$(self.element).change(function() {
var fileName = $(self.element).val();
fileName = fileName.replace(/.*\\(.*)/, '$1');
fileName = fileName.replace(/.*\/(.*)/, '$1');
$(self.element).parent().children('.jInputFile-filename').html(fileName);
$(self.element).parent().children('.jInputFile-fakeButton').button('option', 'disabled', true );
self._trigger("selected", null);
});
},
_submit_ajax_from:function() {
var self = this;
var fd = new FormData();
fd.append($(self.element).attr('name'),self.element[0].files[0]);
$(self.element).parent().children('.jInputFile-filename').empty();
$.ajax({
url: self.options.url,
data: fd,
processData: false,
contentType: false,
datatype:'json',
cache: false,
type: 'POST',
success: function(data){
$(self.element).parent().children('.jInputFile-filename').empty().append('невыбран файл');
self._trigger("success", data);
}
});
},
// Если нам вернули опцию, то заменяем ее
_setOption: function(option, value) {
$.Widget.prototype._setOption.apply( this, arguments );
switch (option) {
case "url":
if (this.options.iframe) {
this.element.parent().find('iframe')
.contents().find('body').children('form').attr('action',value);
}
break;
}
}
});
})(jQuery); |
import React from 'react'
import Simulator from './simulator'
class EventListenerSimulator extends React.Component {
constructor (props) {
super(props)
this.state = {
eventName: props.eventName,
selectedBets: []
}
this.handleOnSelectedBetsCleared = this.handleOnSelectedBetsCleared.bind(this)
this.handleOnSelectedBetRemoved = this.handleOnSelectedBetRemoved.bind(this)
}
componentDidMount () {
if (this.state.eventName !== null) {
window.addEventListener(this.state.eventName, ({ detail }) => {
const betToInsert = {
code: detail.event.code,
home: detail.event.home,
away: detail.event.away,
name: detail.betType,
odd: detail.odd
}
const copyOfSelectedBets = this.state.selectedBets.concat()
const idx = copyOfSelectedBets.findIndex(
bet => bet.code === detail.event.code
)
if (idx !== -1) {
// replace existing one
copyOfSelectedBets.splice(idx, 1, betToInsert)
} else {
copyOfSelectedBets.push(betToInsert)
}
this.setState({
selectedBets: copyOfSelectedBets
})
})
}
}
componentWillUnmount () {
if (this.state.eventName !== null) {
window.removeEventListener(this.state.eventName)
}
}
handleOnSelectedBetsCleared () {
this.setState({
selectedBets: []
})
}
handleOnSelectedBetRemoved (betToRemove) {
const filteredSelectedBets = this.state.selectedBets.filter(
bet => bet.code !== betToRemove.code
)
if (filteredSelectedBets.length < this.state.selectedBets.length) {
this.setState({
selectedBets: filteredSelectedBets
})
}
}
render () {
return (
<Simulator
selectedBets={this.state.selectedBets}
onSelectedBetsCleared={this.handleOnSelectedBetsCleared}
onSelectedBetRemoved={this.handleOnSelectedBetRemoved}
/>
)
}
}
EventListenerSimulator.defaultProps = {
eventName: null
}
export default EventListenerSimulator
|
;
(function(window, angular, undefined) {
'use strict';
angular
.module('second', [])
}(window, angular, undefined));
|
import { take, takeLatest, put, cancel, call, select } from 'redux-saga/effects';
import axios from 'axios';
import { LOCATION_CHANGE, push } from 'react-router-redux';
import { HOST } from 'constants/host';
import { LOAD_DATA,
FETCH_CATEGORIES,
FETCH_POSTS,
ADD_POSTS,
ADD_CATEGORIES,
TAB_CLICKED,
} from './constants';
export function* fetchCategories() {
const URL = `${HOST}api/categories`;
const response = yield call(axios.get, URL);
yield put({ type: ADD_CATEGORIES, categories: response.data });
}
export function* fetchPosts() {
const URL = `${HOST}api/posts`;
const response = yield call(axios.get, URL);
yield put({ type: ADD_POSTS, categories: response.data });
}
export function* loadData() {
yield put({ type: FETCH_CATEGORIES });
yield put({ type: FETCH_POSTS });
}
const selectActiveTab = (state) => state.toJS().homepage.activeTab;
export function* tabClicked() {
const state = yield select(selectActiveTab);
yield put(push(state.url));
}
export function* userWatcher() {
const loadWatcher = yield takeLatest(LOAD_DATA, loadData);
const fetchCategoryWatcher = yield takeLatest(FETCH_CATEGORIES, fetchCategories);
const fetchPostWatcher = yield takeLatest(FETCH_CATEGORIES, fetchPosts);
const tabClickWatcher = yield takeLatest(TAB_CLICKED, tabClicked);
yield take(LOCATION_CHANGE);
yield cancel(loadWatcher);
yield cancel(fetchCategoryWatcher);
yield cancel(fetchPostWatcher);
yield cancel(tabClickWatcher);
}
// Bootstrap sagas
export default [
userWatcher,
];
|
/**
* MIT License
*
* Copyright (c) 2016 - 2018 RDUK <tech@rduk.fr>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
'use strict'
const Base = require('../../../lib/base')
const configuration = require('@rduk/configuration')
const errors = require('@rduk/errors')
class MapBaseProvider extends Base {
initialize () {
if (!this.config.hasOwnProperty('connection')) {
errors.throwConfigurationError('connection property not found.')
}
this.token = configuration.load().connections.get(this.config.connection).token
}
geocode (address) {
errors.throwNotImplementedError('geocode')
}
}
module.exports = MapBaseProvider
|
function Snort (conn, tablename) {
// regexs
var regex = {
id: /\[\*\*\] \[([0-9]+:[0-9]+:[0-9]+)\] ([A-Za-z\- \/]+) \[\*\*\]/,
classification: /\[Classification: ([A-Za-z ]+)\] \[Priority: ([0-9]+)\]/,
ttl: /TTL:([0-9]+)/,
ip: /([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5})? -> ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5})?/
};
// sql statements
var sql = {
// create teh db
init:
'CREATE TABLE ' + tablename + ' ( \
id BIGINT NOT NULL AUTO_INCREMENT, \
alert_id VARCHAR(256), \
description VARCHAR(256), \
classification VARCHAR(256), \
priority VARCHAR(256), \
ttl VARCHAR(256), \
src VARCHAR(256), \
dest VARCHAR(256), \
PRIMARY KEY (id) \
);',
// insert a snort log
insert:
'INSERT INTO ' + tablename + ' \
(alert_id, description, classification, priority, ttl, src, dest) \
VALUES \
(:id, :desc, :classification, :priority, :ttl, :src, :dest);'
};
// contents for the next sql statement
var currentStatement;
// functions
this.init = init;
this.process = process;
// init table
function init () {
return conn.query(sql.init, null, { raw: true }, null);
}
// process some input
function process (input) {
var lines = input.split('\n');
var i;
resetStatement();
for (i = 0; i < lines.length; i++) {
processLine(lines[i]);
}
}
// process a single line
function processLine (line) {
if (isNewline(line)) {
executeStatement();
return;
}
matchIDLine(line);
matchClassificationPriority(line);
matchTTL(line);
matchIP(line);
}
// checks if a line is a newline
function isNewline (line) {
return line == '';
}
// resets the current statement
function resetStatement () {
currentStatement = {
id: "",
desc: "",
classification: "",
priority: "",
ttl: "",
src: "",
dest: ""
};
}
// executes the pending statement
function executeStatement () {
conn.query(sql.insert, null, { raw: true }, currentStatement);
resetStatement();
}
// checks the line for an event ID
// and a description
function matchIDLine (line) {
var match = regex.id.exec(line);
if (match) {
currentStatement.id = match[1];
currentStatement.desc = match[2];
}
}
// checks the line for a classification & priority
function matchClassificationPriority (line) {
var match = regex.classification.exec(line);
if (match) {
currentStatement.classification = match[1];
currentStatement.priority = match[2];
}
}
// checks for the ttl
function matchTTL (line) {
var match = regex.ttl.exec(line);
if (match) {
currentStatement.ttl = match[1];
}
}
// matches ip
function matchIP (line) {
var match = regex.ip.exec(line);
if (match) {
currentStatement.src = match[1] || "";
currentStatement.dest = match[2] || "";
}
}
}
module.exports = Snort; |
export default class AppComponent {
constructor() {
this.name = 'Tomas';
}
}
|
let bDebug = false;
export function setDebug(_bDebug) {
bDebug = _bDebug;
}
export function getDebug() {
return bDebug;
}
|
import d3hexbin from 'd3-hexbin';
import { projectionParams, hexbinParams, relevantNumber } from '../../config/globals';
export const projection = (ctry) => {
const params = projectionParams.get(ctry);
const { center, translate, scale, projection: proj } = params;
return proj
.center(center)
.translate(translate)
.scale(scale);
};
const hexbin = (ctry, multiplier) => {
const params = hexbinParams.get(ctry);
const { size, radius } = params;
return d3hexbin.hexbin()
.x(d => d.x)
.y(d => d.y)
.size(size)
.radius(radius * multiplier);
};
export const buildHexbins = (all, filtered, ctry, multiplier) => {
const hbFull = hexbin(ctry, multiplier)(all);
const hbFiltered = hexbin(ctry, multiplier)(filtered);
const hbFullTerse = {};
const hbFilteredTerse = {};
let maxPercent = 0.01;
let maxPlaces = 0;
const fullLengthMap = new Map();
hbFull.forEach(x => {
fullLengthMap.set(`${x.i}/${x.j}`, x.length);
hbFullTerse[`${x.i}/${x.j}`] = ({
id: `${x.i}/${x.j}`,
names: [],
length: 0,
fullLength: x.length,
percentage: 0,
x: x.x,
y: x.y,
});
});
hbFiltered.forEach(x => {
const fullLength = fullLengthMap.get(`${x.i}/${x.j}`);
const percentage = x.length / fullLength;
if (fullLength > relevantNumber.get(ctry)) {
maxPercent = Math.max(maxPercent, percentage);
}
maxPlaces = Math.max(maxPlaces, fullLength);
hbFilteredTerse[`${x.i}/${x.j}`] = ({
id: `${x.i}/${x.j}`,
names: x.map(town => town.name),
length: x.length,
fullLength,
percentage,
x: x.x,
y: x.y,
});
});
return {
maxPercent,
maxPlaces: Math.max.apply(null, Array.from(fullLengthMap.values())),
tiles: Object.assign(
{},
hbFullTerse,
hbFilteredTerse),
};
};
|
// All code points with the `Other_Lowercase` property as per Unicode v4.1.0:
[
0x2B0,
0x2B1,
0x2B2,
0x2B3,
0x2B4,
0x2B5,
0x2B6,
0x2B7,
0x2B8,
0x2C0,
0x2C1,
0x2E0,
0x2E1,
0x2E2,
0x2E3,
0x2E4,
0x345,
0x37A,
0x1D2C,
0x1D2D,
0x1D2E,
0x1D2F,
0x1D30,
0x1D31,
0x1D32,
0x1D33,
0x1D34,
0x1D35,
0x1D36,
0x1D37,
0x1D38,
0x1D39,
0x1D3A,
0x1D3B,
0x1D3C,
0x1D3D,
0x1D3E,
0x1D3F,
0x1D40,
0x1D41,
0x1D42,
0x1D43,
0x1D44,
0x1D45,
0x1D46,
0x1D47,
0x1D48,
0x1D49,
0x1D4A,
0x1D4B,
0x1D4C,
0x1D4D,
0x1D4E,
0x1D4F,
0x1D50,
0x1D51,
0x1D52,
0x1D53,
0x1D54,
0x1D55,
0x1D56,
0x1D57,
0x1D58,
0x1D59,
0x1D5A,
0x1D5B,
0x1D5C,
0x1D5D,
0x1D5E,
0x1D5F,
0x1D60,
0x1D61,
0x1D78,
0x1D9B,
0x1D9C,
0x1D9D,
0x1D9E,
0x1D9F,
0x1DA0,
0x1DA1,
0x1DA2,
0x1DA3,
0x1DA4,
0x1DA5,
0x1DA6,
0x1DA7,
0x1DA8,
0x1DA9,
0x1DAA,
0x1DAB,
0x1DAC,
0x1DAD,
0x1DAE,
0x1DAF,
0x1DB0,
0x1DB1,
0x1DB2,
0x1DB3,
0x1DB4,
0x1DB5,
0x1DB6,
0x1DB7,
0x1DB8,
0x1DB9,
0x1DBA,
0x1DBB,
0x1DBC,
0x1DBD,
0x1DBE,
0x1DBF,
0x2090,
0x2091,
0x2092,
0x2093,
0x2094,
0x2170,
0x2171,
0x2172,
0x2173,
0x2174,
0x2175,
0x2176,
0x2177,
0x2178,
0x2179,
0x217A,
0x217B,
0x217C,
0x217D,
0x217E,
0x217F,
0x24D0,
0x24D1,
0x24D2,
0x24D3,
0x24D4,
0x24D5,
0x24D6,
0x24D7,
0x24D8,
0x24D9,
0x24DA,
0x24DB,
0x24DC,
0x24DD,
0x24DE,
0x24DF,
0x24E0,
0x24E1,
0x24E2,
0x24E3,
0x24E4,
0x24E5,
0x24E6,
0x24E7,
0x24E8,
0x24E9
]; |
// All symbols in the `No` category as per Unicode v3.2.0:
[
'\xB2',
'\xB3',
'\xB9',
'\xBC',
'\xBD',
'\xBE',
'\u09F4',
'\u09F5',
'\u09F6',
'\u09F7',
'\u09F8',
'\u09F9',
'\u0BF0',
'\u0BF1',
'\u0BF2',
'\u0F2A',
'\u0F2B',
'\u0F2C',
'\u0F2D',
'\u0F2E',
'\u0F2F',
'\u0F30',
'\u0F31',
'\u0F32',
'\u0F33',
'\u1372',
'\u1373',
'\u1374',
'\u1375',
'\u1376',
'\u1377',
'\u1378',
'\u1379',
'\u137A',
'\u137B',
'\u137C',
'\u2070',
'\u2074',
'\u2075',
'\u2076',
'\u2077',
'\u2078',
'\u2079',
'\u2080',
'\u2081',
'\u2082',
'\u2083',
'\u2084',
'\u2085',
'\u2086',
'\u2087',
'\u2088',
'\u2089',
'\u2153',
'\u2154',
'\u2155',
'\u2156',
'\u2157',
'\u2158',
'\u2159',
'\u215A',
'\u215B',
'\u215C',
'\u215D',
'\u215E',
'\u215F',
'\u2460',
'\u2461',
'\u2462',
'\u2463',
'\u2464',
'\u2465',
'\u2466',
'\u2467',
'\u2468',
'\u2469',
'\u246A',
'\u246B',
'\u246C',
'\u246D',
'\u246E',
'\u246F',
'\u2470',
'\u2471',
'\u2472',
'\u2473',
'\u2474',
'\u2475',
'\u2476',
'\u2477',
'\u2478',
'\u2479',
'\u247A',
'\u247B',
'\u247C',
'\u247D',
'\u247E',
'\u247F',
'\u2480',
'\u2481',
'\u2482',
'\u2483',
'\u2484',
'\u2485',
'\u2486',
'\u2487',
'\u2488',
'\u2489',
'\u248A',
'\u248B',
'\u248C',
'\u248D',
'\u248E',
'\u248F',
'\u2490',
'\u2491',
'\u2492',
'\u2493',
'\u2494',
'\u2495',
'\u2496',
'\u2497',
'\u2498',
'\u2499',
'\u249A',
'\u249B',
'\u24EA',
'\u24EB',
'\u24EC',
'\u24ED',
'\u24EE',
'\u24EF',
'\u24F0',
'\u24F1',
'\u24F2',
'\u24F3',
'\u24F4',
'\u24F5',
'\u24F6',
'\u24F7',
'\u24F8',
'\u24F9',
'\u24FA',
'\u24FB',
'\u24FC',
'\u24FD',
'\u24FE',
'\u2776',
'\u2777',
'\u2778',
'\u2779',
'\u277A',
'\u277B',
'\u277C',
'\u277D',
'\u277E',
'\u277F',
'\u2780',
'\u2781',
'\u2782',
'\u2783',
'\u2784',
'\u2785',
'\u2786',
'\u2787',
'\u2788',
'\u2789',
'\u278A',
'\u278B',
'\u278C',
'\u278D',
'\u278E',
'\u278F',
'\u2790',
'\u2791',
'\u2792',
'\u2793',
'\u3192',
'\u3193',
'\u3194',
'\u3195',
'\u3220',
'\u3221',
'\u3222',
'\u3223',
'\u3224',
'\u3225',
'\u3226',
'\u3227',
'\u3228',
'\u3229',
'\u3251',
'\u3252',
'\u3253',
'\u3254',
'\u3255',
'\u3256',
'\u3257',
'\u3258',
'\u3259',
'\u325A',
'\u325B',
'\u325C',
'\u325D',
'\u325E',
'\u325F',
'\u3280',
'\u3281',
'\u3282',
'\u3283',
'\u3284',
'\u3285',
'\u3286',
'\u3287',
'\u3288',
'\u3289',
'\u32B1',
'\u32B2',
'\u32B3',
'\u32B4',
'\u32B5',
'\u32B6',
'\u32B7',
'\u32B8',
'\u32B9',
'\u32BA',
'\u32BB',
'\u32BC',
'\u32BD',
'\u32BE',
'\u32BF',
'\uD800\uDF20',
'\uD800\uDF21',
'\uD800\uDF22',
'\uD800\uDF23'
]; |
// __Dependencies__
var express = require('express');
// __Module Definition__
var decorator = module.exports = function (options, protect) {
var controller = this;
var originalGet = controller.get;
var initial = express();
var controllerForStage = protect.controllerForStage = {
initial: initial,
request: express(),
query: express(),
finalize: express()
};
// __Stage Controllers__
controller.use(initial);
controller.use(controllerForStage.request);
controller.use(controllerForStage.query);
controller.use(controllerForStage.finalize);
Object.keys(controllerForStage).forEach(function (stage) {
controllerForStage[stage].disable('x-powered-by');
});
// Pass the method calls through to the "initial" stage middleware controller,
// so that it precedes all other stages and middleware that might have been
// already added.
controller.use = initial.use.bind(initial);
controller.head = initial.head.bind(initial);
controller.post = initial.post.bind(initial);
controller.put = initial.put.bind(initial);
controller.del = initial.del.bind(initial);
controller.delete = initial.delete.bind(initial);
controller.get = function () {
// When getting options set on the controller, use the original functionality.
if (arguments.length === 1) return originalGet.apply(controller, arguments);
// Otherwise set get middleware on initial.
else return initial.get.apply(initial, arguments);
};
};
|
(function ($, undef) {
"use strict";
$.Cell = function (x, y) {
this.x = x;
this.y = y;
this.connectedCells = new Obj();
this.deadEnd = false;
return this;
};
$.Cell.prototype = {
getCellKeys: function () {
var ret = [];
this.connectedCells.forEach(function (value, key, obj) { ret.push(key); return true; });
return ret;
},
getCell: function (x, y) {
var key = pos2key(x, y);
return this.connectedCells.get(key);
},
setCell: function (cell) {
var key = pos2key(cell.x, cell.y);
this.connectedCells.set(key, cell);
},
deleteCellAt: function (x, y) {
var key = pos2key(x, y);
this.connectedCells.remove(key);
},
deleteCell: function (cell) {
this.deleteCellAt(cell.x, cell.y);
},
cellLength: function () {
return this.connectedCells.length;
},
clone: function () {
return new Cell(this.x, this.y);
},
equals: function (x, y) {
if (x instanceof Object) {
return (this.x === x.x) && (this.y === x.y);
} else {
return (this.x === x) && (this.y === y);
}
},
add: function (x, y) {
if (x instanceof Object) {
this.x += x.x;
this.y += x.y;
} else if (arguments.length === 1) {
this.x += x;
this.y += x;
} else {
this.x += x;
this.y += y;
}
return this;
},
sub: function (x, y) {
if (x instanceof Object) {
this.x -= x.x;
this.y -= x.y;
} else if (arguments.length === 1) {
this.x -= x;
this.y -= x;
} else {
this.x -= x;
this.y -= y;
}
return this;
},
mul: function (x, y) {
if (x instanceof Object) {
this.x *= x.x;
this.y *= x.y;
} else if (arguments.length === 1) {
this.x *= x;
this.y *= x;
} else {
this.x *= x;
this.y *= y;
}
return this;
},
div: function (x, y) {
if (x instanceof Object) {
if (x.x !== 0 && x.y !== 0) {
this.x /= x.x;
this.y /= x.y;
}
} else if (arguments.length === 1) {
if (x !== 0) {
this.x /= x;
this.y /= x;
}
} else {
if (x.x !== 0 && x.y !== 0) {
this.x /= x;
this.y /= y;
}
}
return this;
},
toString: function () {
return "[x: " + this.x + ", y: " + this.y + "]";
}
};
})(window); |
import React from 'react';
import PropTypes from 'prop-types';
import MatchMedia from './MatchMedia';
import { XLARGE } from '../constants/breakpoints';
const XLarge = ({ children, mediaFeatures }) => (
<MatchMedia mediaQuery={`(min-width: ${XLARGE}px)`} mediaFeatures={mediaFeatures}>
{ children }
</MatchMedia>
);
XLarge.propTypes = {
mediaFeatures: PropTypes.shape({ width: PropTypes.string }),
};
XLarge.defaultProps = {
mediaFeatures: null,
};
export default XLarge;
|
var phantom = require('phantom')
, _ = require('lodash')
, util = require('./util.js')
, zlib = require('zlib');
var COOKIES_ENABLED = process.env.COOKIES_ENABLED || false;
var PAGE_DONE_CHECK_TIMEOUT = process.env.PAGE_DONE_CHECK_TIMEOUT || 50;
var RESOURCE_DOWNLOAD_TIMEOUT = process.env.RESOURCE_DOWNLOAD_TIMEOUT || 10 * 1000;
var WAIT_AFTER_LAST_REQUEST = process.env.WAIT_AFTER_LAST_REQUEST || 500;
var JS_CHECK_TIMEOUT = process.env.JS_CHECK_TIMEOUT || 50;
var JS_TIMEOUT = process.env.JS_TIMEOUT || 10 * 1000;
var NO_JS_EXECUTION_TIMEOUT = process.env.NO_JS_EXECUTION_TIMEOUT || 1000;
var EVALUATE_JAVASCRIPT_CHECK_TIMEOUT = process.env.EVALUATE_JAVASCRIPT_CHECK_TIMEOUT || 50;
var server = exports = module.exports = {};
server.init = function(options) {
this.plugins = this.plugins || [];
this.options = options;
return this;
};
server.start = function() {
if(!this.options.isMaster) {
this.createPhantom();
}
};
server.use = function(plugin) {
this.plugins.push(plugin);
if (typeof plugin.init === 'function') plugin.init(this);
};
server._pluginEvent = function(methodName, args, callback) {
var _this = this
, index = 0
, next;
next = function() {
var layer = _this.plugins[index++];
if (!layer) return callback();
var method = layer[methodName];
if (method) {
method.apply(layer, args);
} else {
next();
}
};
args.push(next);
next();
};
server.createPhantom = function() {
var _this = this;
util.log('starting phantom');
var args = ["--load-images=false", "--ignore-ssl-errors=true", "--ssl-protocol=tlsv1"];
var port = this.options.phantomBasePort || 12300;
if(this.options.phantomArguments) {
args = this.options.phantomArguments;
}
if(this.options.debug) {
args.unshift("--debug=true");
}
var opts = {
port: port + this.options.worker.id,
binary: require('phantomjs').path,
onExit: function() {
_this.phantom = null;
util.log('phantom crashed, restarting...');
process.nextTick(_.bind(_this.createPhantom, _this));
}
};
if(this.options.onStdout) {
opts.onStdout = this.options.onStdout;
}
if(this.options.onStderr) {
opts.onStderr = this.options.onStderr;
}
args.push(opts);
args.push(_.bind(this.onPhantomCreate, this));
phantom.create.apply(this, args);
};
server.onPhantomCreate = function(phantom) {
util.log('started phantom');
this.phantom = phantom;
this.phantom.id = Math.random().toString(36);
};
server.onRequest = function(req, res) {
var _this = this;
// Create a partial out of the _send method for the convenience of plugins
res.send = _.bind(this._send, this, req, res);
req.prerender = {
url: util.getUrl(req),
start: new Date()
};
util.log('getting', req.prerender.url);
this._pluginEvent("beforePhantomRequest", [req, res], function() {
_this.createPage(req, res);
});
};
server.createPage = function(req, res) {
var _this = this;
if(!this.phantom) {
setTimeout(function(){
_this.createPage(req, res);
}, 50);
} else {
req.prerender.phantomId = this.phantom.id;
this.phantom.createPage(function(page){
req.prerender.page = page;
_this.onPhantomPageCreate(req, res);
});
}
};
server.onPhantomPageCreate = function(req, res) {
var _this = this;
req.prerender.stage = 0;
req.prerender.pendingRequests = 1;
this.phantom.set('cookiesEnabled', (req.prerender.cookiesEnabled || _this.options.cookiesEnabled || COOKIES_ENABLED));
// Listen for updates on resource downloads
req.prerender.page.onResourceRequested(this.onResourceRequested, _.bind(_this.onResourceRequestedCallback, _this, req, res));
req.prerender.page.set('onResourceReceived', _.bind(_this.onResourceReceived, _this, req, res));
req.prerender.page.set('onResourceTimeout', _.bind(_this.onResourceTimeout, _this, req, res));
req.prerender.page.set('viewportSize', { width: 1440, height: 718 });
req.prerender.page.set('libraryPath', __dirname + '/injections');
req.prerender.page.set('onInitialized', function(){
if(!process.env.DISABLE_INJECTION && req.prerender.page) req.prerender.page.injectJs('bind.js');
});
req.prerender.page.get('settings.userAgent', function(userAgent) {
req.prerender.page.set('settings.userAgent', userAgent + ' Prerender (+https://github.com/prerender/prerender)');
// Fire off a middleware event, then download all of the assets
_this._pluginEvent("onPhantomPageCreate", [_this.phantom, req, res], function() {
req.prerender.downloadStarted = req.prerender.lastResourceReceived = new Date();
req.prerender.downloadChecker = setInterval(function() {
_this.checkIfPageIsDoneLoading(req, res, req.prerender.status === 'fail');
}, (req.prerender.pageDoneCheckTimeout || _this.options.pageDoneCheckTimeout || PAGE_DONE_CHECK_TIMEOUT));
req.prerender.page.open(encodeURI(req.prerender.url.replace(/%20/g, ' ')), function(status) {
req.prerender.status = status;
});
});
});
};
//We want to abort the request if it's a call to Google Analytics or other tracking services.
/*
* CODE DUPLICATION ALERT
* Anything added to this if block has to be added to the if block
* in server.onResourceRequestedCallback.
* This if statment cannot be broken out into a helper method because
* this method is serialized across the network to PhantomJS :(
* Also, PhantomJS doesn't call onResourceError for an aborted request
*/
server.onResourceRequested = function (requestData, request) {
if ((/google-analytics.com/gi).test(requestData.url) ||
(/api.mixpanel.com/gi).test(requestData.url) ||
(/fonts.googleapis.com/gi).test(requestData.url) ||
(/stats.g.doubleclick.net/gi).test(requestData.url) ||
(/mc.yandex.ru/gi).test(requestData.url) ||
(/use.typekit.net/gi).test(requestData.url) ||
(/beacon.tapfiliate.com/gi).test(requestData.url) ||
(/js-agent.newrelic.com/gi).test(requestData.url) ||
(/api.segment.io/gi).test(requestData.url) ||
(/woopra.com/gi).test(requestData.url) ||
(/.ttf/gi).test(requestData.url) ||
(/static.olark.com/gi).test(requestData.url) ||
(/static.getclicky.com/gi).test(requestData.url) ||
(/fast.fonts.com/gi).test(requestData.url) ||
(/youtube.com\/embed/gi).test(requestData.url) ||
(/cdn.heapanalytics.com/gi).test(requestData.url) ||
(/googleads.g.doubleclick.net/gi).test(requestData.url) ||
(/pagead2.googlesyndication.com/gi).test(requestData.url)) {
request.abort();
}
};
// Increment the number of pending requests left to download when a new
// resource is requested
/*
* CODE DUPLICATION ALERT
* Anything added to this if block has to be added to the if block
* in server.onResourceRequested.
* The if statment in onResourceRequested cannot be broken out into a helper method because
* that method is serialized across the network to PhantomJS :(
*/
server.onResourceRequestedCallback = function (req, res, request) {
if (!(/google-analytics.com/gi).test(request.url) &&
!(/api.mixpanel.com/gi).test(request.url) &&
!(/fonts.googleapis.com/gi).test(request.url) &&
!(/stats.g.doubleclick.net/gi).test(request.url) &&
!(/mc.yandex.ru/gi).test(request.url) &&
!(/use.typekit.net/gi).test(request.url) &&
!(/beacon.tapfiliate.com/gi).test(request.url) &&
!(/js-agent.newrelic.com/gi).test(request.url) &&
!(/api.segment.io/gi).test(request.url) &&
!(/woopra.com/gi).test(request.url) &&
!(/.ttf/gi).test(request.url) &&
!(/static.olark.com/gi).test(request.url) &&
!(/static.getclicky.com/gi).test(request.url) &&
!(/fast.fonts.com/gi).test(request.url) &&
!(/youtube.com\/embed/gi).test(request.url) &&
!(/cdn.heapanalytics.com/gi).test(request.url) &&
!(/googleads.g.doubleclick.net/gi).test(request.url) &&
!(/pagead2.googlesyndication.com/gi).test(request.url)) {
req.prerender.pendingRequests++;
}
};
// Decrement the number of pending requests left to download after a resource
// is downloaded
server.onResourceReceived = function (req, res, response) {
req.prerender.lastResourceReceived = new Date();
//always get the headers off of the first response to pass along
if(response.id === 1) {
req.prerender.headers = response.headers;
}
//sometimes on redirects, phantomjs doesnt fire the 'end' stage of the original request, so we need to check it here
if(response.id === 1 && response.status >= 300 && response.status <= 399) {
if (response.redirectURL) {
req.prerender.redirectURL = response.redirectURL;
} else {
var match = _.findWhere(response.headers, { name: 'Location' });
if (match) {
req.prerender.redirectURL = util.normalizeUrl(match.value);
}
}
req.prerender.statusCode = response.status;
if(!(this.options.followRedirect || process.env.FOLLOW_REDIRECT)) {
//force the response now
return this.checkIfPageIsDoneLoading(req, res, true);
}
}
if ('end' === response.stage) {
if(response.url) req.prerender.pendingRequests--;
if (response.id === 1) {
req.prerender.pendingRequests--;
req.prerender.statusCode = response.status;
}
if( (this.options.followRedirect || process.env.FOLLOW_REDIRECT) && req.prerender.redirectURL && response.id === 1) {
req.prerender.statusCode = response.status;
}
}
};
// Decrement the number of pending requests to download when there's a timeout
// fetching a resource
server.onResourceTimeout = function(req, res, request) {
req.prerender.pendingRequests--;
};
// Called occasionally to check if a page is completely loaded
server.checkIfPageIsDoneLoading = function(req, res, force) {
var timedOut = new Date().getTime() - req.prerender.downloadStarted.getTime() > (req.prerender.resourceDownloadTimeout || this.options.resourceDownloadTimeout || RESOURCE_DOWNLOAD_TIMEOUT)
, timeSinceLastRequest = new Date().getTime() - req.prerender.lastResourceReceived.getTime();
// Check against the current stage to make sure we don't finish more than
// once, and check against a bunch of states that would signal finish - if
// resource downloads have timed out, if the page has errored out, or if
// there are no pending requests left
if(req.prerender.stage < 1 && (force || (req.prerender.status !== null && req.prerender.pendingRequests <= 0 && (timeSinceLastRequest > (req.prerender.waitAfterLastRequest || this.options.waitAfterLastRequest || WAIT_AFTER_LAST_REQUEST))) || timedOut)) {
req.prerender.stage = 1;
clearInterval(req.prerender.downloadChecker);
req.prerender.downloadChecker = null;
if(req.prerender.status === 'fail') {
req.prerender.statusCode = 504;
return res.send(req.prerender.statusCode);
}
if(req.prerender.statusCode && req.prerender.statusCode >= 300 && req.prerender.statusCode <= 399) {
// Finish up if we got a redirect status code
res.send(req.prerender.statusCode);
} else {
// Now evaluate the javascript
req.prerender.downloadFinished = new Date();
req.prerender.timeoutChecker = setInterval(_.bind(this.checkIfJavascriptTimedOut, this, req, res), (req.prerender.jsCheckTimeout || this.options.jsCheckTimeout || JS_CHECK_TIMEOUT));
this.evaluateJavascriptOnPage(req, res);
}
}
};
// Checks to see if the execution of javascript has timed out
server.checkIfJavascriptTimedOut = function(req, res) {
var timeout = new Date().getTime() - req.prerender.downloadFinished.getTime() > (req.prerender.jsTimeout || this.options.jsTimeout || JS_TIMEOUT);
var lastJsExecutionWasLessThanTwoSecondsAgo = req.prerender.lastJavascriptExecution && (new Date().getTime() - req.prerender.lastJavascriptExecution.getTime() < 2000);
var noJsExecutionInFirstSecond = !req.prerender.lastJavascriptExecution && (new Date().getTime() - req.prerender.downloadFinished.getTime() > (req.prerender.noJsExecutionTimeout || this.options.noJsExecutionTimeout || NO_JS_EXECUTION_TIMEOUT));
if (!this.phantom || this.phantom.id !== req.prerender.phantomId) {
util.log('PhantomJS restarted in the middle of this request. Aborting...');
clearInterval(req.prerender.timeoutChecker);
req.prerender.timeoutChecker = null;
res.send(504);
} else if (timeout && lastJsExecutionWasLessThanTwoSecondsAgo) {
util.log('Timed out. Sending request with HTML on the page');
clearInterval(req.prerender.timeoutChecker);
req.prerender.timeoutChecker = null;
this.onPageEvaluate(req, res);
} else if ((timeout && req.prerender.stage < 2) || noJsExecutionInFirstSecond) {
util.log('Experiencing infinite javascript loop. Killing phantomjs...');
clearInterval(req.prerender.timeoutChecker);
req.prerender.timeoutChecker = null;
res.send(504, {abort: true});
}
};
// Evaluates the javascript on the page
server.evaluateJavascriptOnPage = function(req, res) {
var _this = this;
if(req.prerender.stage >= 2) return;
req.prerender.page.evaluate(this.javascriptToExecuteOnPage, function(obj) {
// Update the evaluated HTML
req.prerender.documentHTML = obj.html;
req.prerender.lastJavascriptExecution = new Date();
if(!obj.shouldWaitForPrerenderReady || (obj.shouldWaitForPrerenderReady && obj.prerenderReady)) {
clearInterval(req.prerender.timeoutChecker);
req.prerender.timeoutChecker = null;
_this.onPageEvaluate(req, res);
} else {
setTimeout(_.bind(_this.evaluateJavascriptOnPage, _this, req, res), (req.prerender.evaluateJavascriptCheckTimeout || this.evaluateJavascriptCheckTimeout || EVALUATE_JAVASCRIPT_CHECK_TIMEOUT));
}
});
};
// Fetches the html on the page
server.javascriptToExecuteOnPage = function() {
try {
var doctype = ''
, html = document && document.getElementsByTagName('html');
if(document.doctype) {
doctype = "<!DOCTYPE "
+ document.doctype.name
+ (document.doctype.publicId ? ' PUBLIC "' + document.doctype.publicId + '"' : '')
+ (!document.doctype.publicId && document.doctype.systemId ? ' SYSTEM' : '')
+ (document.doctype.systemId ? ' "' + document.doctype.systemId + '"' : '')
+ '>';
}
if (html && html[0]) {
return {
html: doctype + html[0].outerHTML,
shouldWaitForPrerenderReady: typeof window.prerenderReady === 'boolean',
prerenderReady: window.prerenderReady
};
}
} catch (e) { }
return {
html: '',
shouldWaitForPrerenderReady: false,
prerenderReady: window.prerenderReady
};
};
// Called when we're done evaluating the javascript on the page
server.onPageEvaluate = function(req, res) {
if(req.prerender.stage >= 2) return;
req.prerender.stage = 2;
if (!req.prerender.documentHTML) {
res.send(req.prerender.statusCode || 404);
} else {
this._pluginEvent("afterPhantomRequest", [req, res], function() {
res.send(req.prerender.statusCode || 200);
});
}
};
server._send = function(req, res, statusCode, options) {
var _this = this;
if(req.prerender.page) {
req.prerender.page.close();
req.prerender.page = null;
}
req.prerender.stage = 2;
req.prerender.documentHTML = options || req.prerender.documentHTML;
req.prerender.statusCode = statusCode || req.prerender.statusCode;
if(req.prerender.statusCode) {
req.prerender.statusCode = parseInt(req.prerender.statusCode);
}
if (options && typeof options === 'object' && !Buffer.isBuffer(options)) {
req.prerender.documentHTML = options.documentHTML;
req.prerender.redirectURL = options.redirectURL;
}
this._pluginEvent("beforeSend", [req, res], function() {
if (req.prerender.headers && req.prerender.headers.length) {
req.prerender.headers.forEach(function(header) {
res.setHeader(header.name, header.value);
});
}
if (req.prerender.redirectURL && !(_this.options.followRedirect || process.env.FOLLOW_REDIRECT)) {
res.setHeader('Location', req.prerender.redirectURL);
}
res.setHeader('Content-Type', 'text/html;charset=UTF-8');
if(req.headers['accept-encoding'] && req.headers['accept-encoding'].indexOf('gzip') >= 0) {
res.setHeader('Content-Encoding', 'gzip');
zlib.gzip(req.prerender.documentHTML, function(err, result) {
req.prerender.documentHTML = result;
_this._sendResponse.apply(_this, [req, res, options]);
});
} else {
res.removeHeader('Content-Encoding');
_this._sendResponse.apply(_this, [req, res, options]);
}
});
};
server._sendResponse = function(req, res, options) {
if (req.prerender.documentHTML) {
if(Buffer.isBuffer(req.prerender.documentHTML)) {
res.setHeader('Content-Length', req.prerender.documentHTML.length);
} else {
res.setHeader('Content-Length', Buffer.byteLength(req.prerender.documentHTML, 'utf8'));
}
}
if (!req.prerender.documentHTML) {
res.removeHeader('Content-Length');
}
//if the original server had a chunked encoding, we should remove it since we aren't sending a chunked response
res.removeHeader('Transfer-Encoding');
res.writeHead(req.prerender.statusCode || 504);
if (req.prerender.documentHTML) res.write(req.prerender.documentHTML);
res.end();
var ms = new Date().getTime() - req.prerender.start.getTime();
util.log('got', req.prerender.statusCode, 'in', ms + 'ms', 'for', req.prerender.url);
if(options && options.abort) {
this._killPhantomJS();
}
};
server._killPhantomJS = function() {
this.options.worker.kill();
// try {
// //not happy with this... but when phantomjs is hanging, it can't exit any normal way
// util.log('pkilling phantomjs');
// require('child_process').spawn('pkill', ['phantomjs']);
// this.phantom = null;
// } catch(e) {
// util.log('Error killing phantomjs from javascript infinite loop:', e);
// }
} |
import React, { Component } from 'react';
export default class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
placeholder: 'Hey fella, search something here! :)',
term: ''
};
}
render() {
return (
<div className="search-bar">
<input
type="text" placeholder={ this.state.placeholder } value = { this.state.term }
onChange={ event => this.onInputChange(event.target.value)}
/>
</div>
);
}
onInputChange(term) {
this.setState({ term });
this.props.onSearchTermChange(term);
}
} |
/* global afterEach, describe, it */
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Apigee Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
var _ = require('lodash');
var assert = require('assert');
var async = require('async');
var JsonRefs = require('json-refs');
var spec = (typeof window === 'undefined' ? require('../../') : SwaggerTools).specs.v2_0; // jshint ignore:line
var header = typeof window === 'undefined' ?
'' :
' (Browser ' + (window.bowerTests ? 'Bower' : 'Standalone') + ' Build)';
var petStoreJson = _.cloneDeep(require('../../samples/2.0/petstore.json'));
describe('Specification v2.0' + header, function () {
var server;
afterEach(function () {
if (server) {
server.close();
}
server = undefined;
});
describe('metadata', function () {
it('should have proper docsUrl, primitives, options, schemasUrl and verison properties', function () {
assert.strictEqual(spec.docsUrl, 'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md');
assert.deepEqual(spec.primitives, ['string', 'number', 'boolean', 'integer', 'array', 'file']);
assert.strictEqual(spec.schemasUrl, 'https://github.com/swagger-api/swagger-spec/tree/master/schemas/v2.0');
assert.strictEqual(spec.version, '2.0');
});
});
describe('schemas', function () {
it('should contain all schema files', function () {
assert.deepEqual(Object.keys(spec.schemas), [
'schema.json'
]);
});
});
// Test validators
describe('validators', function () {
it('should contain all validators', function () {
assert.equal(1, Object.keys(spec.validators).length);
assert.ok(!_.isUndefined(spec.validators['schema.json']));
});
});
describe('#validate', function () {
it('should throw an Error when passed the wrong arguments', function () {
var errors = {
'swaggerObject is required': [],
'swaggerObject must be an object': ['wrongType'],
'callback is required': [petStoreJson],
'callback must be a function': [petStoreJson, 'wrongType']
};
_.each(errors, function (args, message) {
try {
spec.validate.apply(spec, args);
} catch (err) {
assert.equal(message, err.message);
}
});
});
it('should return undefined for valid JSON files', function (done) {
spec.validate(petStoreJson, function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(err));
assert.ok(_.isUndefined(result));
done();
});
});
describe('should return errors for structurally invalid JSON files', function () {
it('extra property', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].get.extra = 'value';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'OBJECT_ADDITIONAL_PROPERTIES',
message: 'Additional properties not allowed: extra',
path: ['paths', '/pets', 'get']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('invalid reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].get.responses['200'].schema.items.$ref = 'Pet';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_REFERENCE',
message: 'Not a valid JSON Reference',
path: ['paths', '/pets', 'get', 'responses', '200', 'schema', 'items', '$ref']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('invalid type', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.info.contact.name = false;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
// Visible because the schema provides it
description: 'The identifying name of the contact person/organization.',
message: 'Expected type string but found type boolean',
path: ['info', 'contact', 'name']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('missing required value', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
delete swaggerObject.paths;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
message: 'Missing required property: paths',
path: []
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('wrong enum value', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.schemes.push('fake');
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'ENUM_MISMATCH',
message: 'No enum match for: fake',
path: ['schemes', '1']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
});
describe('should return errors for semantically invalid JSON files', function () {
it('child model redeclares property', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Person = {
allOf: [
{
$ref: '#/definitions/Pet'
}
],
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
}
};
swaggerObject.paths['/pets'].get.responses.default.schema.$ref = '#/definitions/Person';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'CHILD_DEFINITION_REDECLARES_PROPERTY',
message: 'Child definition declares property already declared by ancestor: name',
path: ['definitions', 'Person', 'properties', 'name']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
describe('default value fails constraint/schema validation', function () {
describe('definition property', function () {
it('enum mismatch', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'string',
enum: ['A', 'B'],
default: 'fake'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'ENUM_MISMATCH',
message: 'Not an allowable value (A, B): fake',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('maximum', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'integer',
maximum: 0,
default: 1
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MAXIMUM',
message: 'Greater than the configured maximum (0): 1',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('maximum (exclusive)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'integer',
maximum: 1,
default: 1,
exclusiveMaximum: true
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MAXIMUM_EXCLUSIVE',
message: 'Greater than or equal to the configured maximum (1): 1',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('maxItems', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'array',
items: {
type: 'string'
},
maxItems: 1,
default: ['A', 'B']
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'ARRAY_LENGTH_LONG',
message: 'Array is too long (2), maximum 1',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('maxLength', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'string',
maxLength: 3,
default: 'fake'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MAX_LENGTH',
message: 'String is too long (4 chars), maximum 3',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('maxProperties', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'object',
maxProperties: 1,
default: {
a: 'a',
b: 'b'
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MAX_PROPERTIES',
message: 'Number of properties is too many (2 properties), maximum 1',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('minimum', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'integer',
minimum: 1,
default: 0
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MINIMUM',
message: 'Less than the configured minimum (1): 0',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('minItems', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'array',
items: {
type: 'string'
},
minItems: 2,
default: ['A']
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'ARRAY_LENGTH_SHORT',
message: 'Array is too short (1), minimum 2',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('minLength', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'string',
minLength: 5,
default: 'fake'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MIN_LENGTH',
message: 'String is too short (4 chars), minimum 5',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('minProperties', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'object',
minProperties: 2,
default: {
a: 'a'
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MIN_PROPERTIES',
message: 'Number of properties is too few (1 properties), minimum 2',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('multipleOf', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'integer',
multipleOf: 3,
default: 5
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MULTIPLE_OF',
message: 'Not a multiple of 3',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('pattern', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'string',
pattern: '^#.*',
default: 'fake'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'PATTERN',
message: 'Does not match required pattern: ^#.*',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('wrong type', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.fake = {
type: 'integer',
default: 'fake'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['definitions', 'Pet', 'properties', 'fake', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
});
describe('parameter definition', function () {
it('inline schema', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.parameters = {
fake: {
name: 'fake',
type: 'integer',
in: 'query',
default: 'fake'
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['parameters', 'fake', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_PARAMETER',
message: 'Parameter is defined but is not used: #/parameters/fake',
path: ['parameters', 'fake']
}
]);
done();
});
});
it('schema object', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.parameters = {
fake: {
name: 'fake',
in: 'body',
schema: {
type: 'integer',
default: 'fake'
}
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['parameters', 'fake', 'schema', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_PARAMETER',
message: 'Parameter is defined but is not used: #/parameters/fake',
path: ['parameters', 'fake']
}
]);
done();
});
});
it('schema reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.fake = {
type: 'integer',
default: 'fake'
};
swaggerObject.parameters = {
fake: {
name: 'fake',
in: 'body',
schema: {
$ref: '#/definitions/fake'
}
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['parameters', 'fake', 'schema', 'default']
},
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['definitions', 'fake', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_PARAMETER',
message: 'Parameter is defined but is not used: #/parameters/fake',
path: ['parameters', 'fake']
}
]);
done();
});
});
// Testing all other constraints is unnecessary since the same code that validates them is tested above
});
describe('operation parameter', function () {
it('inline schema', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].post.parameters.push({
name: 'fake',
type: 'integer',
in: 'query',
default: 'fake'
});
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'post', 'parameters', '1', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('schema object', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].post.parameters[0].schema = {
type: 'integer',
default: 'fake'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'post', 'parameters', '0', 'schema', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/newPet',
path: ['definitions', 'newPet']
}
]);
done();
});
});
it('inline reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.parameters = {
fake: {
name: 'fake',
in: 'query',
type: 'integer',
default: 'fake'
}
};
swaggerObject.paths['/pets'].post.parameters.push({
$ref: '#/parameters/fake'
});
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['parameters', 'fake', 'default']
},
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'post', 'parameters', '1', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('schema reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.fake = {
type: 'integer',
default: 'fake'
};
swaggerObject.paths['/pets'].post.parameters[0].schema.$ref = '#/definitions/fake';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['definitions', 'fake', 'default']
},
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'post', 'parameters', '0', 'schema', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/newPet',
path: ['definitions', 'newPet']
}
]);
done();
});
});
// Testing all other constraints is unnecessary since the same code that validates them is tested above
});
describe('operation parameter (path level)', function () {
it('inline schema', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].parameters = [
{
name: 'fake',
type: 'integer',
in: 'query',
default: 'fake'
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
// Since this is a path level parameter, all operations will get the same error
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'parameters', '0', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('schema object', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].parameters = [
{
name: 'fake',
in: 'body',
schema: {
type: 'integer',
default: 'fake'
}
}
];
delete swaggerObject.paths['/pets'].post.parameters;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
// Since this is a path level parameter, all operations will get the same error
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'parameters', '0', 'schema', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/newPet',
path: ['definitions', 'newPet']
}
]);
done();
});
});
it('inline reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.parameters = {
fake: {
name: 'fake',
in: 'query',
type: 'integer',
default: 'fake'
}
};
swaggerObject.paths['/pets'].parameters = [
{
$ref: '#/parameters/fake'
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
// Since this is a path level parameter, all operations will get the same error
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['parameters', 'fake', 'default']
},
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'parameters', '0', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('schema reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.fake = {
type: 'integer',
default: 'fake'
};
swaggerObject.paths['/pets'].parameters = [
{
name: 'fake',
in: 'body',
schema: {
$ref: '#/definitions/fake'
}
}
];
delete swaggerObject.paths['/pets'].post.parameters;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
// Since this is a path level parameter, all operations will get the same error
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['definitions', 'fake', 'default']
},
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'parameters', '0', 'schema', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/newPet',
path: ['definitions', 'newPet']
}
]);
done();
});
});
// Testing all other constraints is unnecessary since the same code that validates them is tested above
});
describe('operation response', function () {
it('schema object', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].get.responses['201'] = {
description: 'Fake response',
schema: {
type: 'integer',
default: 'fake'
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'get', 'responses', '201', 'schema', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('schema reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.fake = {
type: 'integer',
default: 'fake'
};
swaggerObject.paths['/pets'].get.responses['201'] = {
description: 'Fake response',
schema: {
$ref: '#/definitions/fake'
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['definitions', 'fake', 'default']
},
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['paths', '/pets', 'get', 'responses', '201', 'schema', 'default']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
// Testing all other constraints is unnecessary since the same code that validates them is tested above
});
describe('response definition', function () {
it('schema object', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.responses = {
fake: {
description: 'Fake response',
schema: {
type: 'integer',
default: 'fake'
}
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['responses', 'fake', 'schema', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_RESPONSE',
message: 'Response is defined but is not used: #/responses/fake',
path: ['responses', 'fake']
}
]);
done();
});
});
it('schema reference', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.fake = {
type: 'integer',
default: 'fake'
};
swaggerObject.responses = {
fake: {
description: 'Fake response',
schema: {
$ref: '#/definitions/fake'
}
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['responses', 'fake', 'schema', 'default']
},
{
code: 'INVALID_TYPE',
message: 'Not a valid integer: fake',
path: ['definitions', 'fake', 'default']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_RESPONSE',
message: 'Response is defined but is not used: #/responses/fake',
path: ['responses', 'fake']
}
]);
done();
});
});
// Testing all other constraints is unnecessary since the same code that validates them is tested above
});
});
it('duplicate API path (equivalent)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets/{petId}'] = _.cloneDeep(swaggerObject.paths['/pets/{id}']);
swaggerObject.paths['/pets/{petId}'].parameters[0].name = 'petId';
swaggerObject.paths['/pets/{petId}'].delete.parameters[0].name = 'petId';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'DUPLICATE_API_PATH',
message: 'API path (or equivalent) already defined: /pets/{petId}',
path: ['paths', '/pets/{petId}']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
describe('duplicate operation parameter (name+in)', function () {
it('path level', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
var cParam = _.cloneDeep(swaggerObject.paths['/pets/{id}'].parameters[0]);
// Make the parameter not identical but still having the same id
cParam.type = 'string';
delete cParam.format;
swaggerObject.paths['/pets/{id}'].parameters.push(cParam);
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
// Since this is a path level parameter, all operations that do not override the property will get the error
assert.deepEqual(result.errors, [
{
code: 'DUPLICATE_PARAMETER',
message: 'Parameter already defined: id',
path: ['paths', '/pets/{id}', 'parameters', '1', 'name']
},
{
code: 'DUPLICATE_PARAMETER',
message: 'Parameter already defined: id',
path: ['paths', '/pets/{id}', 'get', 'parameters', '1', 'name']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('path level (remote)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
var cPath = _.cloneDeep(swaggerObject.paths['/pets/{id}']);
var cParam = _.cloneDeep(cPath.parameters[0]);
// Make the parameter not identical but still having the same id
cParam.type = 'string';
delete cParam.format;
cPath.parameters.push(cParam);
swaggerObject.paths['/people/{id}'] = {
$ref: 'https://rawgit.com/apigee-127/swagger-tools/master/test/browser/people.json#/paths/~1people~1{id}'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
// Since this is a path level parameter, all operations that do not override the property will get the error
assert.deepEqual(result.errors, [
{
code: 'DUPLICATE_PARAMETER',
message: 'Parameter already defined: id',
path: ['paths', '/people/{id}', 'parameters', '1', 'name']
},
{
code: 'DUPLICATE_PARAMETER',
message: 'Parameter already defined: id',
path: ['paths', '/people/{id}', 'get', 'parameters', '1', 'name']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('operation level', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
var cParam = _.cloneDeep(swaggerObject.paths['/pets/{id}'].delete.parameters[0]);
// Make the parameter not identical but still having the same id
cParam.type = 'string';
delete cParam.format;
swaggerObject.paths['/pets/{id}'].delete.parameters.push(cParam);
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'DUPLICATE_PARAMETER',
message: 'Parameter already defined: id',
path: ['paths', '/pets/{id}', 'delete', 'parameters', '1', 'name']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('operation level (remote)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
// Make the parameter not identical but still having the same id
swaggerObject.paths['/pets/{id}'].delete.parameters[0].type = 'string';
delete swaggerObject.paths['/pets/{id}'].delete.parameters[0].format;
swaggerObject.paths['/pets/{id}'].delete.parameters.push({
$ref: 'https://rawgit.com/apigee-127/swagger-tools/master/test/browser/people.json#/paths/~1people~1{id}/delete/parameters/0'
});
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'DUPLICATE_PARAMETER',
message: 'Parameter already defined: id',
path: ['paths', '/pets/{id}', 'delete', 'parameters', '1', 'name']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
});
it('missing operation path parameter', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
delete swaggerObject.paths['/pets/{id}'].parameters;
delete swaggerObject.paths['/pets/{id}'].delete.parameters;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
// Since this is a path level parameter, all operations will get the same error
assert.deepEqual(result.errors, [
{
code: 'MISSING_API_PATH_PARAMETER',
message: 'API requires path parameter but it is not defined: id',
path: ['paths', '/pets/{id}', 'delete']
},
{
code: 'MISSING_API_PATH_PARAMETER',
message: 'API requires path parameter but it is not defined: id',
path: ['paths', '/pets/{id}', 'get']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('missing required model property', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
delete swaggerObject.definitions.Pet.properties.name;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MISSING_REQUIRED_DEFINITION_PROPERTY',
message: 'Definition requires property but it is not defined: name',
path: ['definitions', 'Pet', 'required', '1']
},
{
code: 'MISSING_REQUIRED_DEFINITION_PROPERTY',
message: 'Definition requires property but it is not defined: name',
path: ['definitions', 'newPet', 'required', '0']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('model is subtype of one of its subtypes (Circular Inheritance)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
_.merge(swaggerObject.definitions, {
Bar: {
allOf: [
{
$ref: '#/definitions/Baz'
}
],
properties: {
bar: {
type: 'string'
}
}
},
Baz: {
allOf: [
{
$ref: '#/definitions/Bar'
}
],
properties: {
baz: {
type: 'string'
}
}
}
});
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'CYCLICAL_DEFINITION_INHERITANCE',
message: 'Definition has a circular inheritance: #/definitions/Bar -> #/definitions/Baz -> ' +
'#/definitions/Bar',
path: ['definitions', 'Bar', 'allOf']
},
{
code: 'CYCLICAL_DEFINITION_INHERITANCE',
message: 'Definition has a circular inheritance: #/definitions/Baz -> #/definitions/Bar -> ' +
'#/definitions/Baz',
path: ['definitions', 'Baz', 'allOf']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('unresolvable operation path parameter', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
var newParam = _.cloneDeep(swaggerObject.paths['/pets/{id}'].parameters[0]);
newParam.name = 'petId';
swaggerObject.paths['/pets/{id}'].delete.parameters.push(newParam);
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_API_PATH_PARAMETER',
message: 'API path parameter could not be resolved: ' + newParam.name,
path: ['paths', '/pets/{id}', 'delete', 'parameters', '1', 'name']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
describe('unresolvable model', function () {
it('model definition', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Fake = {
properties: {
project: {
$ref: '#/definitions/Project'
}
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_DEFINITION',
message: 'Definition could not be resolved: #/definitions/Project',
path: ['definitions', 'Fake', 'properties', 'project', '$ref']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/Fake',
path: [
'definitions',
'Fake'
]
}
]);
done();
});
});
it('parameter', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].post.parameters[0].schema.$ref = '#/definitions/Fake';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_DEFINITION',
message: 'Definition could not be resolved: #/definitions/Fake',
path: ['paths', '/pets', 'post', 'parameters', '0', 'schema', '$ref']
}
]);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/newPet',
path: [
'definitions',
'newPet'
]
}
]);
done();
});
});
});
it('unresolvable security definition (global)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.security = [
{
oauth3: ['write']
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_SECURITY_DEFINITION',
message: 'Security definition could not be resolved: #/securityDefinitions/oauth3',
path: ['security', '0', 'oauth3']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('unresolvable security definition (operation)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].get.security = [
{
oauth3: ['write']
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_SECURITY_DEFINITION',
message: 'Security definition could not be resolved: #/securityDefinitions/oauth3',
path: ['paths', '/pets', 'get', 'security', '0', 'oauth3']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('unresolvable security definition scope (global)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.security = [
{
oauth2: ['fake']
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_SECURITY_DEFINITION_SCOPE',
message: 'Security definition scope could not be resolved: #/securityDefinitions/oauth2/scopes/fake',
path: ['security', '0', 'oauth2', '0']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('unresolvable security definition scope (operation)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].get.security = [
{
oauth2: ['fake']
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_SECURITY_DEFINITION_SCOPE',
message: 'Security definition scope could not be resolved: #/securityDefinitions/oauth2/scopes/fake',
path: ['paths', '/pets', 'get', 'security', '0', 'oauth2', '0']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
});
describe('should return warnings for semantically invalid JSON files', function () {
// TODO: Validate duplicate authorization scope reference (API Declaration)
// Not possible due to https://github.com/swagger-api/swagger-spec/issues/159
it('duplicate security definition reference (global)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.security = [
{
oauth2: ['write']
},
{
oauth2: ['read']
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.warnings, [
{
code: 'DUPLICATE_SECURITY_DEFINITION_REFERENCE',
message: 'Security definition reference already defined: oauth2',
path: ['security', '1', 'oauth2']
}
]);
assert.equal(result.errors.length, 0);
done();
});
});
it('duplicate security definition reference (operation)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].get.security = [
{
oauth2: ['write']
},
{
oauth2: ['read']
}
];
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.warnings, [
{
code: 'DUPLICATE_SECURITY_DEFINITION_REFERENCE',
message: 'Security definition reference already defined: oauth2',
path: ['paths', '/pets', 'get', 'security', '1', 'oauth2']
}
]);
assert.equal(result.errors.length, 0);
done();
});
});
it('unused model', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Person = {
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/Person',
path: ['definitions', 'Person']
}
]);
assert.equal(result.errors.length, 0);
done();
});
});
it('unused parameter', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.parameters = {
fake: {
name: 'fake',
type: 'string',
in: 'path'
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.equal(result.errors.length, 0);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_PARAMETER',
message: 'Parameter is defined but is not used: #/parameters/fake',
path: ['parameters', 'fake']
}
]);
done();
});
});
it('unused response', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.responses = {
fake: {
description: 'Fake response',
schema: {
type: 'string'
}
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.equal(result.errors.length, 0);
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_RESPONSE',
message: 'Response is defined but is not used: #/responses/fake',
path: ['responses', 'fake']
}
]);
done();
});
});
it('unused security definition', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.securityDefinitions.internalApiKey = {
type: 'apiKey',
in: 'header',
name: 'api_key'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_SECURITY_DEFINITION',
message: 'Security definition is defined but is not used: #/securityDefinitions/internalApiKey',
path: ['securityDefinitions', 'internalApiKey']
}
]);
assert.equal(result.errors.length, 0);
done();
});
});
it('unused security definition scope', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.securityDefinitions.oauth2.scopes.fake = 'Fake security scope';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_SECURITY_DEFINITION_SCOPE',
message: 'Security definition scope is defined but is not used: #/securityDefinitions/oauth2/scopes/fake',
path: ['securityDefinitions', 'oauth2', 'scopes', 'fake']
}
]);
assert.equal(result.errors.length, 0);
done();
});
});
});
});
describe('#composeSchema', function () {
it('should fail when passed the wrong arguments', function () {
var swaggerObject = _.cloneDeep(petStoreJson);
var errors = {
'swaggerObject is required': [],
'swaggerObject must be an object': ['wrongType'],
'modelRef is required': [swaggerObject],
'callback is required': [swaggerObject, '#/definitions/Pet'],
'callback must be a function': [swaggerObject, '#/definitions/Pet', 'wrongType'],
'modelRef must be a JSON Pointer': [swaggerObject, 'Pet', function() {}, 'wrongType']
};
_.each(errors, function (args, message) {
try {
spec.composeModel.apply(spec, args);
} catch (err) {
assert.equal(message, err.message);
}
});
});
it('should return undefined for unresolvable model', function (done) {
spec.composeModel(_.cloneDeep(petStoreJson), '#/definitions/Liger', function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(result));
done();
});
});
it('should throw an Error for an API Declaration that has invalid models', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Person = {
allOf: [
{
$ref: '#/definitions/Pet'
}
],
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
}
};
swaggerObject.paths['/pets'].get.responses.default.schema.$ref = '#/definitions/Person';
spec.composeModel(swaggerObject, '#/definitions/Pet', function (err, result) {
assert.ok(_.isUndefined(result));
assert.equal('The Swagger document(s) are invalid', err.message);
assert.equal(1, err.errors.length);
assert.equal(0, err.warnings.length);
assert.deepEqual({
code: 'CHILD_DEFINITION_REDECLARES_PROPERTY',
message: 'Child definition declares property already declared by ancestor: name',
path: ['definitions', 'Person', 'properties', 'name']
}, err.errors[0]);
done();
});
});
it('should return a valid composed model', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
var ePet = _.cloneDeep(swaggerObject.definitions.Pet);
var eResults = [];
var eCompany;
var eEmployee;
var ePerson;
swaggerObject.definitions.Person = {
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
},
required: ['name'],
discriminator: 'name'
};
swaggerObject.definitions.Employee = {
allOf: [
{
$ref: '#/definitions/Person'
}
],
properties: {
company: {
type: 'string'
},
email: {
type: 'string'
}
},
required: ['company', 'email']
};
swaggerObject.definitions.Company = {
properties: {
name: {
type: 'string'
},
employees: {
type: 'array',
items: {
$ref: '#/definitions/Employee'
}
}
}
};
// Create expected Employee
eEmployee = _.cloneDeep(swaggerObject.definitions.Employee);
eEmployee.title = 'Composed #/definitions/Employee';
eEmployee.allOf = [
_.cloneDeep(swaggerObject.definitions.Person)
];
delete eEmployee.id;
delete eEmployee.allOf[0].id;
delete eEmployee.allOf[0].subTypes;
// Create expected Person
ePerson = _.cloneDeep(swaggerObject.definitions.Person);
ePerson.title = 'Composed #/definitions/Person';
delete ePerson.id;
delete ePerson.subTypes;
// Create expected Company
eCompany = _.cloneDeep(swaggerObject.definitions.Company);
eCompany.title = 'Composed #/definitions/Company';
eCompany.properties.employees.items = {
allOf: [
_.cloneDeep(swaggerObject.definitions.Person)
],
properties: _.cloneDeep(swaggerObject.definitions.Employee.properties),
required: _.cloneDeep(swaggerObject.definitions.Employee.required)
};
delete eCompany.id;
delete eCompany.properties.employees.items.allOf[0].id;
delete eCompany.properties.employees.items.allOf[0].subTypes;
// Create expected Pet
ePet.title = 'Composed #/definitions/Pet';
ePet.properties.category = _.cloneDeep(swaggerObject.definitions.Category);
ePet.properties.id.maximum = 100;
ePet.properties.id.minimum = 0;
ePet.properties.tags = {
items: {
properties: _.cloneDeep(swaggerObject.definitions.Tag.properties)
},
type: 'array'
};
delete ePet.id;
delete ePet.properties.category.id;
// Collect our expected results
eResults.push(eEmployee);
eResults.push(ePerson);
eResults.push(eCompany);
eResults.push(ePet);
async.map(['Employee', 'Person', 'Company', 'Pet'], function (modelId, callback) {
spec.composeModel(swaggerObject, '#/definitions/' + modelId, function (err, results) {
callback(err, results);
});
}, function (err, results) {
if (err) {
throw err;
}
_.each(results, function (result, index) {
assert.deepEqual(eResults[index], result);
});
done();
});
});
});
describe('#validateModel', function () {
it('should throw an Error for an API Declaration that has invalid models', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Person = {
allOf: [
{
$ref: '#/definitions/Pet'
}
],
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
}
};
swaggerObject.paths['/pets'].get.responses.default.schema.$ref = '#/definitions/Person';
spec.composeModel(swaggerObject, '#/definitions/Pet', function (err, result) {
assert.ok(_.isUndefined(result));
assert.equal('The Swagger document(s) are invalid', err.message);
assert.equal(1, err.errors.length);
assert.equal(0, err.warnings.length);
assert.deepEqual({
code: 'CHILD_DEFINITION_REDECLARES_PROPERTY',
message: 'Child definition declares property already declared by ancestor: name',
path: ['definitions', 'Person', 'properties', 'name']
}, err.errors[0]);
done();
});
});
it('should return errors/warnings for invalid model', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
spec.validateModel(swaggerObject, '#/definitions/Pet', {
id: 1
}, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
message: 'Missing required property: name',
path: []
}
]);
done();
});
});
it('should return undefined for valid model', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
spec.validateModel(swaggerObject, '#/definitions/Pet', {
id: 1,
name: 'Jeremy'
}, function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(result));
done();
});
});
});
describe('#resolve', function () {
it('should throw errors for invalid arguments', function () {
var errors = {
'document is required': [],
'document must be an object': ['resource-listing.json'],
'callback is required': [{}],
'callback must be a function': [{}, 'wrong-type'],
'ptr must be a JSON Pointer string': [{}, [], function () {}]
};
_.each(errors, function (args, message) {
try {
spec.resolve.apply(undefined, args);
assert.fail(null, null, 'Should had failed above');
} catch (err) {
assert.equal(message, err.message);
}
});
});
it('should return the whole document when there is no pointer argument', function (done) {
spec.resolve(petStoreJson, function (err, resolved) {
if (err) {
throw err;
}
JsonRefs.resolveRefs(petStoreJson, function (err, json) {
if (err) {
throw err;
}
assert.deepEqual(json, resolved);
done();
});
});
});
it('should return the document fragment corresponding to the pointer argument', function (done) {
spec.resolve(petStoreJson, '#/definitions/Pet', function (err, resolved) {
if (err) {
throw err;
}
assert.deepEqual(JsonRefs.resolveRefs(petStoreJson, function (err, json) {
if (err) {
throw err;
}
assert.deepEqual(json.definitions.Pet, resolved);
done();
}));
});
});
});
describe('#convert', function () {
it('should throw an Error (unsupported)', function () {
try {
spec.convert();
assert.fail(null, null, 'Should had failed above');
} catch (err) {
assert.equal(err.message, 'Specification#convert only works for Swagger 1.2');
}
});
});
describe('issues', function () {
// This should be removed when the upstream bug in the Swagger schema is fixed
// https://github.com/swagger-api/swagger-spec/issues/174
it('missing items property for array type (Issue 62)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
delete swaggerObject.paths['/pets'].get.responses['200'].schema.items;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'OBJECT_MISSING_REQUIRED_PROPERTY',
message: 'Missing required property: items',
path: ['paths', '/pets', 'get', 'responses', '200', 'schema']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('should not report missing model for inlines model schemas (Issue 61)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Pet.properties.extraCategories = {
type: 'array',
items: _.cloneDeep(swaggerObject.definitions.Category)
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(result));
done();
});
});
it('should handle path parameters that are not path segments (Issue 72)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/export/{collection}.{format}'] = {
get: {
operationId: 'exportData',
parameters: [
{
description: 'Collection name',
name: 'collection',
in: 'path',
type: 'string'
},
{
description: 'The export format',
name: 'format',
in: 'path',
type: 'string'
}
],
responses: {
'200': {
description: 'Exported data',
schema: {
type: 'string'
}
},
default: {
description: 'Unexpected error',
schema: {
$ref: '#/definitions/Error'
}
}
},
summary: 'Export data in requested format'
}
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(result));
done();
});
});
it('should not report errofs for non-operation path-properties (Issue 103)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets/{id}']['x-swagger-router-controller'] = 'Pets';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(result));
done();
});
});
it('should not throw a runtime Error for missing response reference (Issue 120)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.paths['/pets'].get.responses['200'] = {
$ref: '#/responses/missing'
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'UNRESOLVABLE_RESPONSE',
message: 'Response could not be resolved: #/responses/missing',
path: ['paths', '/pets', 'get', 'responses', '200', '$ref']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('should not throw a runtime Error for missing schema allOf reference (Issue 121)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.newPet.allOf[0].$ref = '#/definitions/missing';
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'MISSING_REQUIRED_DEFINITION_PROPERTY',
message: 'Definition requires property but it is not defined: name',
path: ['definitions', 'newPet', 'required', '0']
},
{
code: 'UNRESOLVABLE_DEFINITION',
message: 'Definition could not be resolved: #/definitions/missing',
path: ['definitions', 'newPet', 'allOf', '0', '$ref']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('void support should be limited to responses (Issue 124)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.Person = {
default: {
name: 'Anonymous Person'
},
properties: {
name: {
type: 'string'
}
},
required: ['name']
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/Person',
path: [
'definitions',
'Person'
]
}
]);
assert.equal(result.errors.length, 0);
done();
});
});
it('do not assume definitions have properties attributes (Issue 122)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
swaggerObject.definitions.UberPet = {
allOf: [
{
$ref: '#/definitions/Pet'
}
]
};
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.warnings, [
{
code: 'UNUSED_DEFINITION',
message: 'Definition is defined but is not used: #/definitions/UberPet',
path: [
'definitions',
'UberPet'
]
}
]);
assert.equal(result.errors.length, 0);
done();
});
});
it('should throw an error for an operation having more than one body parameter (Issue 136)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
var cBodyParam = _.cloneDeep(swaggerObject.paths['/pets'].post.parameters[0]);
cBodyParam.name = 'duplicateBody';
swaggerObject.paths['/pets'].post.parameters.push(cBodyParam);
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.deepEqual(result.errors, [
{
code: 'DULPICATE_API_BODY_PARAMETER',
message: 'API has more than one body parameter',
path: ['paths', '/pets', 'post', 'parameters', '1']
}
]);
assert.equal(result.warnings.length, 0);
done();
});
});
it('should handle operations with an empty parameters array (Issue 189)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
var cOperation = _.cloneDeep(swaggerObject.paths['/pets'].post);
cOperation.operationId = 'putPet';
cOperation.parameters = [];
swaggerObject.paths['/pets'].put = cOperation;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(result));
done();
});
});
it('inline models used for inheritance should not be marked as unused (Issue 187)', function (done) {
var swaggerObject = _.cloneDeep(petStoreJson);
// Definition
swaggerObject.paths['/pets'].get.responses.default.schema = {
allOf: [
{
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
}
}
]
};
// Parameter
swaggerObject.paths['/pets'].post.parameters[0].schema = {
allOf: [
{
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
}
}
]
};
// Response
swaggerObject.paths['/pets'].get.responses.default.schema = {
allOf: [
{
properties: {
age: {
type: 'integer'
},
name: {
type: 'string'
}
}
}
]
};
// Remove reference to avoid unused warning
delete swaggerObject.definitions.newPet;
spec.validate(swaggerObject, function (err, result) {
if (err) {
throw err;
}
assert.ok(_.isUndefined(result));
done();
});
});
});
});
|
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/views/Hello'
Vue.use(Router)
// route-level code splitting
const router = new Router({
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: '/',
name: 'Hello',
component: Hello
}
]
})
export default router |
define(['appns', 'jquery', 'underscore', 'backbone', 'backbone-relational', 'jquery.elastic', 'jquery.magicedit2', 'jsrender', 'jquery.tools'], function(App, $, _, Backbone) {
App.EventView = Backbone.View.extend({
tagName: 'div',
className: 'eventView',
events: {
},
destroy: function() {
this.remove();
this.unbind();
},
initialize: function() {
_.bindAll(this, 'render', 'destroy');
this.model.bind('change', this.render);
this.model.bind('destroy', this.destroy);
},
template: $.templates('#event-tmpl'),
render: function() {
return $(this.el).html(this.template.render(this.model.toJSON()));
}
});
App.EventListView = Backbone.View.extend({
events: {
"click #eventfooter a" : "loadMore",
},
destroy: function() {
this.remove();
this.unbind();
},
initialize: function() {
_.bindAll(this, 'render', 'renderEvent', 'renderEventAt', 'toggleLoadMoreBtn', 'destroy', 'forceRefetch', 'loadMore');
this.collection.bind('add', this.renderEvent);
this.collection.bind('reset', this.render);
},
template: $.templates('#event-list-tmpl'),
forceRefetch: function(ids, opts) {
if (typeof(ids) === 'undefined')
ids = App.globalController.get('filter:tag_ids');
var limit = App.globalController.get('events:nFetched', 30);
if (limit < 30)
limit = 30;
var offset = App.globalController.get('events:fetchOffset', 0);
App.globalController.set('events:nFetched', 0);
this.collection.fetch({data: { limit: limit, offset: offset, filter: { tags: ids } }});
},
loadMore: function(ev) {
var limit = 30;
var offset = App.globalController.get('events:nFetched', 0);
var ids = App.globalController.get('filter:tag_ids');
this.collection.fetch({
data: {
limit: limit,
offset: offset,
filter: {
tags: ids
}
},
add: true
});
},
toggleLoadMoreBtn: function(ev) {
var n_events = this.collection.length;
var total_events = App.globalController.get('project').get('event_stats').total;
console.log('events/events', n_events, total_events);
if (n_events < total_events)
$(this.el).find('#eventfooter a').removeClass('hide');
else
$(this.el).find('#eventfooter a').addClass('hide');
},
render: function() {
var n_events = this.collection.length;
App.globalController.set('events:nFetched');
$(this.el).html(this.template.render({}));
this.collection.each(this.renderEvent);
this.toggleLoadMoreBtn();
return $(this.el);
},
renderEvent: function(m, opt1, opt2) {
var n_events = this.collection.length;
App.globalController.set('events:nFetched', n_events);
var idx = (typeof(opt1) === 'number') ? opt1 : opt2.index;
console.log("renderEvent: idx=%o", idx);
this.renderEventAt(m, idx);
this.toggleLoadMoreBtn();
},
renderEventAt: function(m, idx) {
var elist = $(this.el).find('.event-list');
var nelems = elist.children().length;
var eView = new App.EventView({model: m});
var eHTML = $(eView.render());
if (idx >= nelems)
elist.append(eHTML);
else
elist.children().slice(idx).first().before(eHTML);
}
});
});
|
(function () {
'use strict';
describe('Registrations Controller Tests', function () {
// Initialize global variables
var RegistrationsController,
$scope,
$httpBackend,
$state,
Authentication,
RegistrationsService,
mockRegistration;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _RegistrationsService_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
$state = _$state_;
Authentication = _Authentication_;
RegistrationsService = _RegistrationsService_;
// create mock Registration
mockRegistration = new RegistrationsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Registration Name'
});
// Mock logged in user
Authentication.user = {
roles: ['user']
};
// Initialize the Registrations controller.
RegistrationsController = $controller('RegistrationsController as vm', {
$scope: $scope,
registrationResolve: {}
});
//Spy on state go
spyOn($state, 'go');
}));
describe('vm.save() as create', function () {
var sampleRegistrationPostData;
beforeEach(function () {
// Create a sample Registration object
sampleRegistrationPostData = new RegistrationsService({
name: 'Registration Name'
});
$scope.vm.registration = sampleRegistrationPostData;
});
it('should send a POST request with the form input values and then locate to new object URL', inject(function (RegistrationsService) {
// Set POST response
$httpBackend.expectPOST('api/registrations', sampleRegistrationPostData).respond(mockRegistration);
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL redirection after the Registration was created
expect($state.go).toHaveBeenCalledWith('registrations.view', {
registrationId: mockRegistration._id
});
}));
it('should set $scope.vm.error if error', function () {
var errorMessage = 'this is an error message';
$httpBackend.expectPOST('api/registrations', sampleRegistrationPostData).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
});
});
describe('vm.save() as update', function () {
beforeEach(function () {
// Mock Registration in $scope
$scope.vm.registration = mockRegistration;
});
it('should update a valid Registration', inject(function (RegistrationsService) {
// Set PUT response
$httpBackend.expectPUT(/api\/registrations\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL location to new object
expect($state.go).toHaveBeenCalledWith('registrations.view', {
registrationId: mockRegistration._id
});
}));
it('should set $scope.vm.error if error', inject(function (RegistrationsService) {
var errorMessage = 'error';
$httpBackend.expectPUT(/api\/registrations\/([0-9a-fA-F]{24})$/).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
}));
});
describe('vm.remove()', function () {
beforeEach(function () {
//Setup Registrations
$scope.vm.registration = mockRegistration;
});
it('should delete the Registration and redirect to Registrations', function () {
//Return true on confirm message
spyOn(window, 'confirm').and.returnValue(true);
$httpBackend.expectDELETE(/api\/registrations\/([0-9a-fA-F]{24})$/).respond(204);
$scope.vm.remove();
$httpBackend.flush();
expect($state.go).toHaveBeenCalledWith('registrations.list');
});
it('should should not delete the Registration and not redirect', function () {
//Return false on confirm message
spyOn(window, 'confirm').and.returnValue(false);
$scope.vm.remove();
expect($state.go).not.toHaveBeenCalled();
});
});
});
})();
|
var DC = (function() {
var shipData = {};
var dc = {
update: function(data) {
var ship = shipData[data.id];
ship.state = data.state;
ship.power = data.power;
ship.time = new Date().toString();
},
dealMessage: function(message) {
dc.update(message);
},
addShip: function(data) {
shipData[data.id] = {
id: data.id,
powerSystem: data.powerSystem,
supplySystem: data.supplySystem,
state: 0,
power: 100,
time: new Date().toString()
};
},
removeShip: function(id) {
delete shipData[id];
},
getData: function() {
return shipData;
},
toString: function() {
return "DC";
}
};
dc.notifySystem = new EncodeDecorator(new NotifySystem(dc));
Mediator.registerDc(dc.notifySystem);
return dc;
})();
|
/**
* Created by dli on 25.01.2015.
*/
define('sync/time/after',['sync/time/CONST'], function (CONST) {
return function(t1, t2){
if(t1 > t2){
var trailing = t1 - t2,
heading = CONST.LOGICAL_HOUR - t1 + t2;
if(Math.min(trailing, heading) > CONST.CERTAINTY_MARGIN) throw new Error('UncertainTemporalRelation');
return trailing < heading;
} else if (t1 < t2){
var trailing = t2 - t1,
heading = CONST.LOGICAL_HOUR - t2 + t1;
if(Math.min(trailing, heading) > CONST.CERTAINTY_MARGIN) throw new Error('UncertainTemporalRelation');
return heading < trailing;
}
return false;
}
}); |
'use strict';
angular.module('kickballApp', [
'kickballApp.services',
'kickballApp.controllers',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.sortable',
'ui.slider',
'firebase'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'attendance/attendance.html'
})
.when('/score', {
templateUrl: 'scorekeeper/scorekeeper.html'
})
.when('/lineup', {
templateUrl: 'lineup/lineup.html',
controller: 'LineupController'
})
.when('/player/:id', {
templateUrl: 'edit/edit.html',
controller: 'EditPlayerController'
})
.otherwise({
redirectTo: '/'
});
});
|
// Regular expression that matches all symbols in the Cyrillic Extended-A block as per Unicode v9.0.0:
/[\u2DE0-\u2DFF]/; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.