code
stringlengths 2
1.05M
|
---|
const chai = require('chai');
const MemoryCache = require('..');
const observable = require('../lib/observable');
const constants = require('../lib/constants');
const { expect, assert } = chai;
const testObj = () => ({
a: { b: 'c' },
deep: { nested: { obj: { is: { set: 'yes' }}}},
arr: [1,2,3,4,5]
});
const noop = () => {};
describe('Observable', function () {
it('is a function', function () {
expect(observable).to.be.a('function');
});
it('returns observable functions', function () {
const x = observable();
expect(x.on).to.be.a('function');
expect(x.one).to.be.a('function');
expect(x.off).to.be.a('function');
expect(x.trigger).to.be.a('function');
});
it('does not observe non-symbol event', function () {
const x = observable();
expect(() => {
x.on('test', noop);
}).to.throw();
});
it('observes symbol events', function () {
const x = observable();
expect(() => {
x.on(constants.get, noop);
x.one(constants.get, noop);
x.trigger(constants.get, noop);
x.off(constants.get, noop);
}).to.not.throw();
});
it('triggers functions bound to an event', function () {
const x = observable();
let i = 0;
x.on(constants.get, () => i++);
x.trigger(constants.get)
x.trigger(constants.get)
x.trigger(constants.get)
expect(i).to.equal(3);
});
it('passes arguments to functions bound to an event', function () {
const x = observable();
let args;
x.on(constants.get, (a,b,c) => args = [a,b,c]);
x.trigger(constants.get, 'a', 'b', 'c');
expect(args).to.include('a', 'b', 'c')
});
it('removes functions bound to an event', function () {
const x = observable();
let passed = true;
const fn = () => passed = false;
x.on(constants.get, fn);
x.off(constants.get, fn);
x.trigger(constants.get);
expect(passed).to.equal(true);
});
it('triggers functions bound to an event only one time', function () {
const x = observable();
let i = 0;
x.one(constants.get, () => i++);
x.trigger(constants.get);
x.trigger(constants.get);
x.trigger(constants.get);
expect(i).to.equal(1);
});
});
describe('MemoryCache', function () {
const test = testObj();
let cache;
it('should be a function', function () {
expect(MemoryCache).to.be.a('function');
});
it('should have all api functions', function () {
cache = new MemoryCache();
// Assert all functions are set
expect(cache).to.be.an('object');
expect(cache.set).to.be.a('function');
expect(cache.get).to.be.a('function');
expect(cache.remove).to.be.a('function');
expect(cache.expire).to.be.a('function');
expect(cache.merge).to.be.a('function');
expect(cache.concat).to.be.a('function');
expect(cache.reset).to.be.a('function');
expect(cache.has).to.be.a('function');
expect(cache.debug).to.not.equal(undefined);
expect(cache.events).to.not.equal(undefined);
expect(cache.size).to.not.equal(undefined);
expect(cache.keys).to.not.equal(undefined);
expect(cache.onGet).to.be.a('function');
expect(cache.oneGet).to.be.a('function');
expect(cache.offGet).to.be.a('function');
expect(cache.onSet).to.be.a('function');
expect(cache.oneSet).to.be.a('function');
expect(cache.offSet).to.be.a('function');
expect(cache.onRemove).to.be.a('function');
expect(cache.oneRemove).to.be.a('function');
expect(cache.offRemove).to.be.a('function');
expect(cache.onExpire).to.be.a('function');
expect(cache.oneExpire).to.be.a('function');
expect(cache.offExpire).to.be.a('function');
expect(cache.onMerge).to.be.a('function');
expect(cache.oneMerge).to.be.a('function');
expect(cache.offMerge).to.be.a('function');
expect(cache.onConcat).to.be.a('function');
expect(cache.oneConcat).to.be.a('function');
expect(cache.offConcat).to.be.a('function');
expect(cache.onReset).to.be.a('function');
expect(cache.oneReset).to.be.a('function');
expect(cache.offReset).to.be.a('function');
});
it('should set a key and return it', function () {
const returnValue = cache.set('test', test);
expect(returnValue).to.be.an('object');
});
it('should get a key', function () {
const value = cache.get('test');
expect(value).to.be.an('object');
expect(value.a.b).to.equal(test.a.b);
});
it('should get the whole cache when passed true as key', function () {
assert.deepEqual(cache.get(true).test, test);
});
it('should delete a key', function () {
cache.set('remove', test);
assert.deepEqual(cache.get('remove'), test);
expect(cache.remove('remove')).to.equal(true);
expect(cache.get('remove')).to.equal(undefined);
});
it('should concat an array key', function () {
cache.set('concat', [1,2,3]);
expect(cache.get('concat')).to.not.include(4,5);
cache.concat('concat', [4,5]);
expect(cache.get('concat')).to.include(1,2,3,4,5);
});
it('should merge an object key', function () {
cache.set('merge', { merge: true });
expect(cache.get('merge')).to.not.have.any.keys('merged');
cache.merge('merge', { merged: true});
expect(cache.get('merge')).to.have.any.keys('merge','merged');
expect(cache.get('merge')).to.deep.equal({ merge: true, merged: true });
});
it('should expire a set key', function (done) {
expect(cache.get('merge')).to.deep.equal({ merge: true, merged: true });
cache.expire('merge', 1);
expect(cache.get('merge')).to.not.equal(undefined);
setTimeout(() => {
expect(cache.get('merge')).to.equal(undefined);
done();
}, 5);
});
it('should set a key and expire if time is set', function (done) {
cache.set('set-and-expire', true, 1);
expect(cache.get('set-and-expire')).to.equal(true);
setTimeout(() => {
expect(cache.get('set-and-expire')).to.equal(undefined);
done();
}, 5);
});
it('should reset cache', function () {
expect(cache.size).to.equal(2)
cache.reset();
expect(cache.size).to.equal(0)
});
it('should return all cache keys', function () {
cache.set('1', 1);
cache.set('2', 2);
cache.set('3', 3);
expect(cache.keys).to.include('1', '2', '3');
});
it('should check to see if cache has a key', function () {
expect(cache.has('1')).to.equal(true);
expect(cache.has('4')).to.equal(false);
});
it('should iterate through cache', function () {
const keys = [];
const values = []
cache.each((val, key) => {
values.push(val);
keys.push(key);
});
expect(values).to.include(1,2,3);
expect(keys).to.include('1','2','3');
});
it('should return cache size', function () {
expect(cache.size).to.equal(3);
});
it('should bind to events', function (done) {
// Assert events
const eventsTested = {
get: false,
set: false,
merge: false,
concat: false,
remove: false,
expire: false,
reset: false
};
expect(cache.events).to.equal(false);
cache.events = true;
expect(cache.events).to.equal(true);
// Bind events to fire 1 time. All events should set true.
cache.oneGet(() => { eventsTested.get = true; });
cache.oneSet(() => { eventsTested.set = true; });
cache.oneRemove(() => { eventsTested.remove = true; });
cache.oneExpire(() => { eventsTested.expire = true; });
cache.oneMerge(() => { eventsTested.merge = true; });
cache.oneConcat(() => { eventsTested.concat = true; });
cache.oneReset(() => { eventsTested.reset = true; });
cache.set('merge', {});
cache.set('concat', []);
cache.set('remove', true);
cache.get('merge');
cache.merge('merge', {});
cache.concat('concat', []);
cache.expire('remove', 0);
cache.remove('remove');
cache.reset();
setTimeout(() => {
expect(Object.values(eventsTested)).to.not.include(false);
done();
}, 10);
});
it('should cache passed object', function () {
const c = {
test: true,
taste: 'good',
tats: 'lots',
tits: 'blitz'
}
cache = new MemoryCache(c);
expect(cache.keys).to.include('test', 'taste', 'tats', 'tits');
expect(cache.get(true)).to.deep.equal(c);
});
}); |
var URL = require('url');
var Pagination = function(request, model){
this.request = request;
this.model = model;
this.paginate = function(query, limit, sort, selected, onDataReception){
var url = URL.parse(this.request.url).pathname;
var page = this.request.param('page');
page = page === undefined ? 0 : page;
this.model.find(query).sort(sort).skip(page*limit).limit( (limit + 1) ).select( selected ).exec(function(err, members){
//Fetched more than the limit
members.splice(limit, 1);
var paginatedMembers = {
data : members
};
if(members.length >= limit ){
nextPage = parseInt(page) + 1;
paginatedMembers["next"] = url + "?page=" + nextPage;
}
if (page >= 1) {
prevPage = parseInt(page) - 1;
paginatedMembers["prev"] = url + "?page=" + prevPage;
};
onDataReception(paginatedMembers);
});
};
}
module.exports = function(request, model){
return new Pagination(request, model);
}
|
define(
[
'solarfield/lightship-js/src/Solarfield/Lightship/Environment',
'solarfield/ok-kit-js/src/Solarfield/Ok/ObjectUtils'
],
function (LightshipEnvironment, ObjectUtils) {
"use strict";
var Environment = ObjectUtils.extend(LightshipEnvironment, {
});
return Environment;
}
);
|
'use strict';
exports.BattleScripts = {
inherit: 'gen5',
gen: 4,
init: function () {
for (let i in this.data.Pokedex) {
delete this.data.Pokedex[i].abilities['H'];
}
},
modifyDamage: function (baseDamage, pokemon, target, move, suppressMessages) {
// DPP divides modifiers into several mathematically important stages
// The modifiers run earlier than other generations are called with ModifyDamagePhase1 and ModifyDamagePhase2
if (!move.type) move.type = '???';
let type = move.type;
// Burn
if (pokemon.status === 'brn' && baseDamage && move.category === 'Physical' && !pokemon.hasAbility('guts')) {
baseDamage = this.modify(baseDamage, 0.5);
}
// Other modifiers (Reflect/Light Screen/etc)
baseDamage = this.runEvent('ModifyDamagePhase1', pokemon, target, move, baseDamage);
// Double battle multi-hit
if (move.spreadHit) {
let spreadModifier = move.spreadModifier || 0.75;
this.debug('Spread modifier: ' + spreadModifier);
baseDamage = this.modify(baseDamage, spreadModifier);
}
// Weather
baseDamage = this.runEvent('WeatherModifyDamage', pokemon, target, move, baseDamage);
if (this.gen === 3 && move.category === 'Physical' && !Math.floor(baseDamage)) {
baseDamage = 1;
}
baseDamage += 2;
if (move.crit) {
baseDamage = this.modify(baseDamage, move.critModifier || 2);
}
// Mod 2 (Damage is floored after all multipliers are in)
baseDamage = Math.floor(this.runEvent('ModifyDamagePhase2', pokemon, target, move, baseDamage));
// this is not a modifier
baseDamage = this.randomizer(baseDamage);
// STAB
if (move.hasSTAB || type !== '???' && pokemon.hasType(type)) {
// The "???" type never gets STAB
// Not even if you Roost in Gen 4 and somehow manage to use
// Struggle in the same turn.
// (On second thought, it might be easier to get a Missingno.)
baseDamage = this.modify(baseDamage, move.stab || 1.5);
}
// types
move.typeMod = target.runEffectiveness(move);
move.typeMod = this.clampIntRange(move.typeMod, -6, 6);
if (move.typeMod > 0) {
if (!suppressMessages) this.add('-supereffective', target);
for (let i = 0; i < move.typeMod; i++) {
baseDamage *= 2;
}
}
if (move.typeMod < 0) {
if (!suppressMessages) this.add('-resisted', target);
for (let i = 0; i > move.typeMod; i--) {
baseDamage = Math.floor(baseDamage / 2);
}
}
if (move.crit && !suppressMessages) this.add('-crit', target);
// Final modifier.
baseDamage = this.runEvent('ModifyDamage', pokemon, target, move, baseDamage);
if (!Math.floor(baseDamage)) {
return 1;
}
return Math.floor(baseDamage);
},
calcRecoilDamage: function (damageDealt, move) {
return this.clampIntRange(Math.floor(damageDealt * move.recoil[0] / move.recoil[1]), 1);
},
randomSet: function (template, slot, teamDetails) {
if (slot === undefined) slot = 1;
let baseTemplate = (template = this.getTemplate(template));
let species = template.species;
if (!template.exists || (!template.randomBattleMoves && !template.learnset)) {
template = this.getTemplate('unown');
let err = new Error('Template incompatible with random battles: ' + species);
require('../../crashlogger')(err, 'The gen 4 randbat set generator');
}
if (template.battleOnly) species = template.baseSpecies;
let movePool = (template.randomBattleMoves ? template.randomBattleMoves.slice() : Object.keys(template.learnset));
let moves = [];
let ability = '';
let item = '';
let evs = {
hp: 85,
atk: 85,
def: 85,
spa: 85,
spd: 85,
spe: 85,
};
let ivs = {
hp: 31,
atk: 31,
def: 31,
spa: 31,
spd: 31,
spe: 31,
};
let hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) {
hasType[template.types[1]] = true;
}
let hasAbility = {};
hasAbility[template.abilities[0]] = true;
if (template.abilities[1]) {
hasAbility[template.abilities[1]] = true;
}
let availableHP = 0;
for (let i = 0, len = movePool.length; i < len; i++) {
if (movePool[i].substr(0, 11) === 'hiddenpower') availableHP++;
}
// These moves can be used even if we aren't setting up to use them:
let SetupException = {
closecombat:1, extremespeed:1, suckerpunch:1, superpower:1,
dracometeor:1, leafstorm:1, overheat:1,
};
let counterAbilities = {
'Adaptability':1, 'Hustle':1, 'Iron Fist':1, 'Skill Link':1,
};
let hasMove, counter;
do {
// Keep track of all moves we have:
hasMove = {};
for (let k = 0; k < moves.length; k++) {
if (moves[k].substr(0, 11) === 'hiddenpower') {
hasMove['hiddenpower'] = true;
} else {
hasMove[moves[k]] = true;
}
}
// Choose next 4 moves from learnset/viable moves and add them to moves list:
while (moves.length < 4 && movePool.length) {
let moveid = this.sampleNoReplace(movePool);
if (moveid.substr(0, 11) === 'hiddenpower') {
availableHP--;
if (hasMove['hiddenpower']) continue;
hasMove['hiddenpower'] = true;
} else {
hasMove[moveid] = true;
}
moves.push(moveid);
}
counter = this.queryMoves(moves, hasType, hasAbility, movePool);
// Iterate through the moves again, this time to cull them:
for (let k = 0; k < moves.length; k++) {
let move = this.getMove(moves[k]);
let moveid = move.id;
let rejected = false;
let isSetup = false;
switch (moveid) {
// Not very useful without their supporting moves
case 'batonpass':
if (!counter.setupType && !counter['speedsetup'] && !hasMove['substitute']) rejected = true;
break;
case 'eruption': case 'waterspout':
if (counter.Physical + counter.Special < 4) rejected = true;
break;
case 'focuspunch':
if (!hasMove['substitute'] || counter.damagingMoves.length < 2) rejected = true;
if (hasMove['hammerarm']) rejected = true;
break;
case 'rest': {
if (movePool.includes('sleeptalk')) rejected = true;
break;
}
case 'sleeptalk':
if (!hasMove['rest']) rejected = true;
if (movePool.length > 1) {
let rest = movePool.indexOf('rest');
if (rest >= 0) this.fastPop(movePool, rest);
}
break;
// Set up once and only if we have the moves for it
case 'bellydrum': case 'bulkup': case 'curse': case 'dragondance': case 'swordsdance':
if (counter.setupType !== 'Physical' || counter['physicalsetup'] > 1) {
if (!hasMove['growth'] || hasMove['sunnyday']) rejected = true;
}
if (counter.Physical + counter['physicalpool'] < 2 && !hasMove['batonpass'] && (!hasMove['rest'] || !hasMove['sleeptalk'])) rejected = true;
isSetup = true;
break;
case 'calmmind': case 'growth': case 'nastyplot': case 'tailglow':
if (counter.setupType !== 'Special' || counter['specialsetup'] > 1) rejected = true;
if (counter.Special + counter['specialpool'] < 2 && !hasMove['batonpass'] && (!hasMove['rest'] || !hasMove['sleeptalk'])) rejected = true;
isSetup = true;
break;
case 'agility': case 'rockpolish':
if (counter.damagingMoves.length < 2 && !hasMove['batonpass']) rejected = true;
if (hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
if (!counter.setupType) isSetup = true;
break;
// Bad after setup
case 'explosion': case 'selfdestruct':
if (counter.stab < 2 || counter.setupType || !!counter['recovery'] || hasMove['rest']) rejected = true;
break;
case 'foresight': case 'protect': case 'roar':
if (counter.setupType && !hasAbility['Speed Boost']) rejected = true;
break;
case 'rapidspin':
if (teamDetails.rapidSpin) rejected = true;
break;
case 'stealthrock':
if (counter.setupType || !!counter['speedsetup'] || hasMove['rest'] || teamDetails.stealthRock) rejected = true;
break;
case 'switcheroo': case 'trick':
if (counter.Physical + counter.Special < 3 || counter.setupType) rejected = true;
if (hasMove['lightscreen'] || hasMove['reflect'] || hasMove['suckerpunch'] || hasMove['trickroom']) rejected = true;
break;
case 'toxic': case 'toxicspikes':
if (counter.setupType || teamDetails.toxicSpikes) rejected = true;
break;
case 'trickroom':
if (counter.setupType || !!counter['speedsetup'] || counter.damagingMoves.length < 2) rejected = true;
if (hasMove['lightscreen'] || hasMove['reflect'] || hasMove['rest'] && hasMove['sleeptalk']) rejected = true;
break;
case 'uturn':
if (counter.setupType || !!counter['speedsetup'] || hasMove['batonpass'] || hasMove['substitute']) rejected = true;
if (hasType['Bug'] && counter.stab < 2 && counter.damagingMoves.length > 2) rejected = true;
break;
// Bit redundant to have both
// Attacks:
case 'bodyslam': case 'doubleedge':
if (hasMove['return']) rejected = true;
break;
case 'judgment':
if (counter.setupType !== 'Special' && counter.stab > 1) rejected = true;
break;
case 'quickattack':
if (hasMove['thunderwave']) rejected = true;
break;
case 'firepunch': case 'flamethrower':
if (hasMove['fireblast']) rejected = true;
break;
case 'hydropump':
if (hasMove['surf']) rejected = true;
break;
case 'waterfall':
if (hasMove['aquatail']) rejected = true;
break;
case 'discharge':
if (hasMove['thunderbolt']) rejected = true;
break;
case 'energyball':
if (hasMove['grassknot']) rejected = true;
break;
case 'leafstorm':
if (counter.setupType || hasMove['batonpass'] || hasMove['powerwhip']) rejected = true;
break;
case 'solarbeam':
if (counter.setupType === 'Physical' || !hasMove['sunnyday'] && !movePool.includes('sunnyday')) rejected = true;
break;
case 'icepunch':
if (!counter.setupType && hasMove['icebeam']) rejected = true;
break;
case 'brickbreak':
if (hasMove['substitute'] && hasMove['focuspunch']) rejected = true;
break;
case 'focusblast':
if (hasMove['crosschop']) rejected = true;
break;
case 'seismictoss':
if (hasMove['nightshade'] || counter.Physical + counter.Special >= 1) rejected = true;
break;
case 'gunkshot':
if (hasMove['poisonjab']) rejected = true;
break;
case 'zenheadbutt':
if (hasMove['psychocut']) rejected = true;
break;
case 'rockslide':
if (hasMove['stoneedge']) rejected = true;
break;
case 'shadowclaw':
if (hasMove['shadowforce']) rejected = true;
break;
case 'dragonclaw':
if (hasMove['outrage']) rejected = true;
break;
case 'dracometeor':
if (hasMove['calmmind']) rejected = true;
break;
case 'crunch': case 'nightslash':
if (hasMove['suckerpunch']) rejected = true;
break;
case 'pursuit':
if (counter.setupType || hasMove['payback']) rejected = true;
break;
case 'gyroball': case 'flashcannon':
if (hasMove['ironhead'] && counter.setupType !== 'Special') rejected = true;
break;
// Status:
case 'leechseed': case 'painsplit': case 'wish':
if (hasMove['moonlight'] || hasMove['rest'] || hasMove['rockpolish'] || hasMove['synthesis']) rejected = true;
break;
case 'substitute':
if (hasMove['pursuit'] || hasMove['rest'] || hasMove['taunt']) rejected = true;
break;
case 'thunderwave':
if (hasMove['toxic'] || hasMove['trickroom']) rejected = true;
break;
}
// Increased/decreased priority moves are unneeded with moves that boost only speed
if (move.priority !== 0 && !!counter['speedsetup']) {
rejected = true;
}
// This move doesn't satisfy our setup requirements:
if ((move.category === 'Physical' && counter.setupType === 'Special') || (move.category === 'Special' && counter.setupType === 'Physical')) {
// Reject STABs last in case the setup type changes later on
if (!SetupException[moveid] && (!hasType[move.type] || counter.stab > 1 || counter[move.category] < 2)) rejected = true;
}
if (counter.setupType && !isSetup && move.category !== counter.setupType && counter[counter.setupType] < 2 && !hasMove['batonpass'] && moveid !== 'rest' && moveid !== 'sleeptalk') {
// Mono-attacking with setup and RestTalk is allowed
// Reject Status moves only if there is nothing else to reject
if (move.category !== 'Status' || counter[counter.setupType] + counter.Status > 3 && counter['physicalsetup'] + counter['specialsetup'] < 2) rejected = true;
}
if (counter.setupType === 'Special' && moveid === 'hiddenpower' && template.types.length > 1 && counter['Special'] <= 2 && !hasType[move.type] && !counter['Physical'] && counter['specialpool']) {
// Hidden Power isn't good enough
rejected = true;
}
// Pokemon should have moves that benefit their Ability/Type/Weather, as well as moves required by its forme
if ((hasType['Electric'] && !counter['Electric']) ||
(hasType['Fighting'] && !counter['Fighting'] && (counter.setupType || !counter['Status'])) ||
(hasType['Fire'] && !counter['Fire']) ||
(hasType['Ground'] && !counter['Ground'] && (counter.setupType || counter['speedsetup'] || hasMove['raindance'] || !counter['Status'])) ||
(hasType['Ice'] && !counter['Ice']) ||
(hasType['Psychic'] && !!counter['Psychic'] && !hasType['Flying'] && template.types.length > 1 && counter.stab < 2) ||
(hasType['Water'] && !counter['Water'] && (!hasType['Ice'] || !counter['Ice'])) ||
((hasAbility['Adaptability'] && !counter.setupType && template.types.length > 1 && (!counter[template.types[0]] || !counter[template.types[1]])) ||
(hasAbility['Guts'] && hasType['Normal'] && movePool.includes('facade')) ||
(hasAbility['Slow Start'] && movePool.includes('substitute')) ||
(counter['defensesetup'] && !counter.recovery && !hasMove['rest']) ||
(template.requiredMove && movePool.includes(toId(template.requiredMove)))) &&
(counter['physicalsetup'] + counter['specialsetup'] < 2 && (!counter.setupType || (move.category !== counter.setupType && move.category !== 'Status') || counter[counter.setupType] + counter.Status > 3))) {
// Reject Status or non-STAB
if (!isSetup && !move.weather && moveid !== 'judgment' && moveid !== 'rest' && moveid !== 'sleeptalk') {
if (move.category === 'Status' || !hasType[move.type] || (move.basePower && move.basePower < 40 && !move.multihit)) rejected = true;
}
}
// Sleep Talk shouldn't be selected without Rest
if (moveid === 'rest' && rejected) {
let sleeptalk = movePool.indexOf('sleeptalk');
if (sleeptalk >= 0) {
if (movePool.length < 2) {
rejected = false;
} else {
this.fastPop(movePool, sleeptalk);
}
}
}
// Remove rejected moves from the move list
if (rejected && (movePool.length - availableHP || availableHP && (moveid === 'hiddenpower' || !hasMove['hiddenpower']))) {
moves.splice(k, 1);
break;
}
}
if (moves.length === 4 && !counter.stab && !hasMove['metalburst'] && (counter['physicalpool'] || counter['specialpool'])) {
// Move post-processing:
if (counter.damagingMoves.length === 0) {
// A set shouldn't have no attacking moves
moves.splice(this.random(moves.length), 1);
} else if (counter.damagingMoves.length === 1) {
// In most cases, a set shouldn't have no STAB
let damagingid = counter.damagingMoves[0].id;
if (movePool.length - availableHP || availableHP && (damagingid === 'hiddenpower' || !hasMove['hiddenpower'])) {
let replace = false;
if (!counter.damagingMoves[0].damage && template.species !== 'Porygon2') {
replace = true;
}
if (replace) moves.splice(counter.damagingMoveIndex[damagingid], 1);
}
} else if (!counter.damagingMoves[0].damage && !counter.damagingMoves[1].damage && template.species !== 'Porygon2') {
// If you have three or more attacks, and none of them are STAB, reject one of them at random.
let rejectableMoves = [];
let baseDiff = movePool.length - availableHP;
for (let l = 0; l < counter.damagingMoves.length; l++) {
if (baseDiff || availableHP && (!hasMove['hiddenpower'] || counter.damagingMoves[l].id === 'hiddenpower')) {
rejectableMoves.push(counter.damagingMoveIndex[counter.damagingMoves[l].id]);
}
}
if (rejectableMoves.length) {
moves.splice(rejectableMoves[this.random(rejectableMoves.length)], 1);
}
}
}
} while (moves.length < 4 && movePool.length);
// If Hidden Power has been removed, reset the IVs
if (!hasMove['hiddenpower']) {
ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31};
}
let abilities = Object.values(baseTemplate.abilities);
abilities.sort((a, b) => this.getAbility(b).rating - this.getAbility(a).rating);
let ability0 = this.getAbility(abilities[0]);
let ability1 = this.getAbility(abilities[1]);
ability = ability0.name;
if (abilities[1]) {
if (ability0.rating <= ability1.rating) {
if (this.random(2)) ability = ability1.name;
} else if (ability0.rating - 0.6 <= ability1.rating) {
if (!this.random(3)) ability = ability1.name;
}
let rejectAbility = false;
if (ability in counterAbilities) {
// Adaptability, Hustle, Iron Fist, Skill Link
rejectAbility = !counter[toId(ability)];
} else if (ability === 'Blaze') {
rejectAbility = !counter['Fire'];
} else if (ability === 'Chlorophyll') {
rejectAbility = !hasMove['sunnyday'];
} else if (ability === 'Compound Eyes' || ability === 'No Guard') {
rejectAbility = !counter['inaccurate'];
} else if (ability === 'Gluttony') {
rejectAbility = !hasMove['bellydrum'];
} else if (ability === 'Lightning Rod') {
rejectAbility = template.types.includes('Ground');
} else if (ability === 'Limber') {
rejectAbility = template.types.includes('Electric');
} else if (ability === 'Overgrow') {
rejectAbility = !counter['Grass'];
} else if (ability === 'Poison Heal') {
rejectAbility = abilities.includes('Technician') && !!counter['technician'];
} else if (ability === 'Reckless' || ability === 'Rock Head') {
rejectAbility = !counter['recoil'];
} else if (ability === 'Sand Veil') {
rejectAbility = !teamDetails['sand'];
} else if (ability === 'Serene Grace') {
rejectAbility = !counter['serenegrace'] || template.id === 'chansey' || template.id === 'blissey';
} else if (ability === 'Simple') {
rejectAbility = !counter.setupType && !hasMove['cosmicpower'] && !hasMove['flamecharge'];
} else if (ability === 'Snow Cloak') {
rejectAbility = !teamDetails['hail'];
} else if (ability === 'Solar Power') {
rejectAbility = !counter['Special'];
} else if (ability === 'Sturdy') {
rejectAbility = !!counter['recoil'] && !counter['recovery'];
} else if (ability === 'Swift Swim') {
rejectAbility = !hasMove['raindance'] && !teamDetails['rain'];
} else if (ability === 'Swarm') {
rejectAbility = !counter['Bug'];
} else if (ability === 'Synchronize') {
rejectAbility = counter.Status < 2;
} else if (ability === 'Tinted Lens') {
rejectAbility = counter['damage'] >= counter.damagingMoves.length;
} else if (ability === 'Torrent') {
rejectAbility = !counter['Water'];
}
if (rejectAbility) {
if (ability === ability1.name) { // or not
ability = ability0.name;
} else if (ability1.rating > 1) { // only switch if the alternative doesn't suck
ability = ability1.name;
}
}
if (abilities.includes('Swift Swim') && hasMove['raindance']) {
ability = 'Swift Swim';
}
}
item = 'Leftovers';
if (template.requiredItems) {
item = template.requiredItems[this.random(template.requiredItems.length)];
// First, the extra high-priority items
} else if (template.species === 'Deoxys-Attack') {
item = (slot === 0 && hasMove['stealthrock']) ? 'Focus Sash' : 'Life Orb';
} else if (template.species === 'Farfetch\'d') {
item = 'Stick';
} else if (template.species === 'Marowak') {
item = 'Thick Club';
} else if (template.species === 'Pikachu') {
item = 'Light Ball';
} else if (template.species === 'Shedinja' || template.species === 'Smeargle') {
item = 'Focus Sash';
} else if (template.species === 'Unown') {
item = 'Choice Specs';
} else if (template.species === 'Wobbuffet') {
item = hasMove['destinybond'] ? 'Custap Berry' : ['Leftovers', 'Sitrus Berry'][this.random(2)];
} else if (hasMove['switcheroo'] || hasMove['trick']) {
let randomNum = this.random(3);
if (counter.Physical >= 3 && (template.baseStats.spe < 60 || template.baseStats.spe > 108 || randomNum)) {
item = 'Choice Band';
} else if (counter.Special >= 3 && (template.baseStats.spe < 60 || template.baseStats.spe > 108 || randomNum)) {
item = 'Choice Specs';
} else {
item = 'Choice Scarf';
}
} else if (hasMove['bellydrum']) {
item = 'Sitrus Berry';
} else if (ability === 'Magic Guard') {
item = 'Life Orb';
} else if (ability === 'Poison Heal' || ability === 'Toxic Boost') {
item = 'Toxic Orb';
} else if (hasMove['rest'] && !hasMove['sleeptalk'] && ability !== 'Natural Cure' && ability !== 'Shed Skin') {
item = (hasMove['raindance'] && ability === 'Hydration') ? 'Damp Rock' : 'Chesto Berry';
} else if (hasMove['raindance']) {
item = (ability === 'Swift Swim' && counter.Status < 2) ? 'Life Orb' : 'Damp Rock';
} else if (hasMove['sunnyday']) {
item = (ability === 'Chlorophyll' && counter.Status < 2) ? 'Life Orb' : 'Heat Rock';
} else if (hasMove['lightscreen'] && hasMove['reflect']) {
item = 'Light Clay';
} else if (ability === 'Guts') {
item = 'Flame Orb';
} else if (ability === 'Quick Feet' && hasMove['facade']) {
item = 'Toxic Orb';
} else if (ability === 'Unburden') {
item = 'Sitrus Berry';
// Medium priority
} else if (counter.Physical >= 4 && !hasMove['bodyslam'] && !hasMove['fakeout'] && !hasMove['rapidspin'] && !hasMove['suckerpunch']) {
item = template.baseStats.spe >= 60 && template.baseStats.spe <= 108 && !counter['priority'] && this.random(3) ? 'Choice Scarf' : 'Choice Band';
} else if ((counter.Special >= 4 || (counter.Special >= 3 && (hasMove['batonpass'] || hasMove['uturn']))) && !hasMove['chargebeam']) {
item = template.baseStats.spe >= 60 && template.baseStats.spe <= 108 && ability !== 'Speed Boost' && !counter['priority'] && this.random(3) ? 'Choice Scarf' : 'Choice Specs';
} else if (hasMove['endeavor'] || hasMove['flail'] || hasMove['reversal']) {
item = 'Focus Sash';
} else if (hasMove['outrage'] && counter.setupType) {
item = 'Lum Berry';
} else if (ability === 'Slow Start' || hasMove['curse'] || hasMove['detect'] || hasMove['protect'] || hasMove['sleeptalk']) {
item = 'Leftovers';
} else if (hasMove['substitute']) {
item = !counter['drain'] || counter.damagingMoves.length < 2 ? 'Leftovers' : 'Life Orb';
} else if (hasMove['lightscreen'] || hasMove['reflect']) {
item = 'Light Clay';
} else if (counter.damagingMoves.length >= 4) {
item = (!!counter['Normal'] || hasMove['chargebeam'] || (hasMove['suckerpunch'] && !hasType['Dark'])) ? 'Life Orb' : 'Expert Belt';
} else if (counter.damagingMoves.length >= 3 && !hasMove['superfang']) {
item = (template.baseStats.hp + template.baseStats.def + template.baseStats.spd < 285 || !!counter['speedsetup'] || hasMove['trickroom']) ? 'Life Orb' : 'Leftovers';
} else if (template.species === 'Palkia' && (hasMove['dracometeor'] || hasMove['spacialrend']) && hasMove['hydropump']) {
item = 'Lustrous Orb';
} else if (slot === 0 && !counter['recoil'] && !counter['recovery'] && template.baseStats.hp + template.baseStats.def + template.baseStats.spd < 285) {
item = 'Focus Sash';
// This is the "REALLY can't think of a good item" cutoff
} else if (hasType['Poison']) {
item = 'Black Sludge';
} else if (this.getEffectiveness('Rock', template) >= 1 || hasMove['roar']) {
item = 'Leftovers';
} else if (counter.Status <= 1 && !hasMove['rapidspin']) {
item = 'Life Orb';
} else {
item = 'Leftovers';
}
// For Trick / Switcheroo
if (item === 'Leftovers' && hasType['Poison']) {
item = 'Black Sludge';
}
let levelScale = {
LC: 87,
NFE: 85,
NU: 83,
BL2: 81,
UU: 79,
BL: 77,
OU: 75,
Uber: 71,
};
let tier = template.tier;
let level = levelScale[tier] || 75;
// Prepare optimal HP
let hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
if (hasMove['substitute'] && item === 'Sitrus Berry') {
// Two Substitutes should activate Sitrus Berry
while (hp % 4 > 0) {
evs.hp -= 4;
hp = Math.floor(Math.floor(2 * template.baseStats.hp + ivs.hp + Math.floor(evs.hp / 4) + 100) * level / 100 + 10);
}
} else if (hasMove['bellydrum'] && item === 'Sitrus Berry') {
// Belly Drum should activate Sitrus Berry
if (hp % 2 > 0) evs.hp -= 4;
} else if (hasMove['substitute'] && hasMove['reversal']) {
// Reversal users should be able to use four Substitutes
if (hp % 4 === 0) evs.hp -= 4;
} else {
// Maximize number of Stealth Rock switch-ins
let srWeakness = this.getEffectiveness('Rock', template);
if (srWeakness > 0 && hp % (4 / srWeakness) === 0) evs.hp -= 4;
}
// Minimize confusion damage
if (!counter['Physical'] && !hasMove['transform']) {
evs.atk = 0;
ivs.atk = hasMove['hiddenpower'] ? ivs.atk - 28 : 0;
}
if (hasMove['gyroball'] || hasMove['trickroom']) {
evs.spe = 0;
ivs.spe = hasMove['hiddenpower'] ? ivs.spe - 28 : 0;
}
return {
name: template.baseSpecies,
species: species,
moves: moves,
ability: ability,
evs: evs,
ivs: ivs,
item: item,
level: level,
shiny: !this.random(1024),
};
},
randomTeam: function (side) {
let pokemon = [];
let allowedNFE = {'Porygon2':1, 'Scyther':1};
let pokemonPool = [];
for (let id in this.data.FormatsData) {
let template = this.getTemplate(id);
if (template.gen > 4 || template.isNonstandard || !template.randomBattleMoves || template.nfe && !allowedNFE[template.species]) continue;
pokemonPool.push(id);
}
let typeCount = {};
let typeComboCount = {};
let baseFormes = {};
let uberCount = 0;
let nuCount = 0;
let teamDetails = {};
while (pokemonPool.length && pokemon.length < 6) {
let template = this.getTemplate(this.sampleNoReplace(pokemonPool));
if (!template.exists) continue;
// Limit to one of each species (Species Clause)
if (baseFormes[template.baseSpecies]) continue;
let tier = template.tier;
switch (tier) {
case 'Uber':
// Ubers are limited to 2 but have a 20% chance of being added anyway.
if (uberCount > 1 && this.random(5) >= 1) continue;
break;
case 'NU':
// NUs are limited to 2 but have a 20% chance of being added anyway.
if (nuCount > 1 && this.random(5) >= 1) continue;
}
// Adjust rate for species with multiple formes
switch (template.baseSpecies) {
case 'Arceus':
if (this.random(17) >= 1) continue;
break;
case 'Castform':
if (this.random(4) >= 1) continue;
break;
case 'Cherrim':
if (this.random(2) >= 1) continue;
break;
case 'Rotom':
if (this.random(6) >= 1) continue;
break;
}
let types = template.types;
// Limit 2 of any type
let skip = false;
for (let t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 && this.random(5) >= 1) {
skip = true;
break;
}
}
if (skip) continue;
let set = this.randomSet(template, pokemon.length, teamDetails);
// Limit 1 of any type combination
let typeCombo = types.slice().sort().join();
if (set.ability === 'Drought' || set.ability === 'Drizzle' || set.ability === 'Sand Stream') {
// Drought, Drizzle and Sand Stream don't count towards the type combo limit
typeCombo = set.ability;
if (typeCombo in typeComboCount) continue;
} else {
if (typeComboCount[typeCombo] >= 1) continue;
}
// Okay, the set passes, add it to our team
pokemon.push(set);
// Now that our Pokemon has passed all checks, we can increment our counters
baseFormes[template.baseSpecies] = 1;
// Increment type counters
for (let t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
typeCount[types[t]] = 1;
}
}
if (typeCombo in typeComboCount) {
typeComboCount[typeCombo]++;
} else {
typeComboCount[typeCombo] = 1;
}
// Increment Uber/NU counters
if (tier === 'Uber') {
uberCount++;
} else if (tier === 'NU') {
nuCount++;
}
// Team has
if (set.ability === 'Snow Warning') teamDetails['hail'] = 1;
if (set.ability === 'Drizzle' || set.moves.includes('raindance')) teamDetails['rain'] = 1;
if (set.ability === 'Sand Stream') teamDetails['sand'] = 1;
if (set.moves.includes('stealthrock')) teamDetails['stealthRock'] = 1;
if (set.moves.includes('toxicspikes')) teamDetails['toxicSpikes'] = 1;
if (set.moves.includes('rapidspin')) teamDetails['rapidSpin'] = 1;
}
return pokemon;
},
};
|
$(function(){
var InvitationForm = Backbone.View.extend({
el: $('fieldset[data-control=invitation]'),
events: {
},
initialize: function(){
if(!this.$el.length) return null;
this.listenTo(Backbone, 'showInvitationForm', this.showInvitationForm);
this.listenTo(Backbone, 'hideInvitationForm', this.hideInvitationForm);
},
showInvitationForm: function(){
this.$el.removeClass('hidden');
},
hideInvitationForm: function(){
this.$el.addClass('hidden');
}
});
var invitationForm = new InvitationForm();
});
|
import React, { PropTypes } from 'react';
class AutoFocus extends React.Component {
constructor( props ) {
super( props );
this.receiveRef = this.receiveRef.bind( this );
}
componentDidMount() {
if ( this.ref ) {
this.ref.focus();
}
}
receiveRef( node ) {
this.ref = node;
}
render() {
return this.props.children( this.receiveRef );
}
}
AutoFocus.propTypes = {
children: PropTypes.func.isRequired,
};
export default AutoFocus;
|
var DObject_8h =
[
[ "DObject", "classHelix_1_1Logic_1_1dev_1_1DObject.html", "classHelix_1_1Logic_1_1dev_1_1DObject" ],
[ "DObject_svect", "DObject_8h.html#a56460b28b8ab9b64a1aecf912b2f14ac", null ]
]; |
/*
* Sidebar toggle function
*/
(function(document) {
var toggle = document.querySelector('.sidebar-toggle');
var sidebar = document.querySelector('#sidebar');
var checkbox = document.querySelector('#sidebar-checkbox');
document.addEventListener('click', function(e) {
var target = e.target;
if(!checkbox.checked ||
sidebar.contains(target) ||
(target === checkbox || target === toggle)) return;
checkbox.checked = false;
}, false);
})(document);
/*global jQuery */
/*jshint browser:true */
/*!
* FitVids 1.1
*
* Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
*/
;(function( $ ){
'use strict';
$.fn.fitVids = function( options ) {
var settings = {
customSelector: null,
ignore: null
};
if(!document.getElementById('fit-vids-style')) {
// appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js
var head = document.head || document.getElementsByTagName('head')[0];
var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
var div = document.createElement("div");
div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>';
head.appendChild(div.childNodes[1]);
}
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
'iframe[src*="player.vimeo.com"]',
'iframe[src*="youtube.com"]',
'iframe[src*="youtube-nocookie.com"]',
'iframe[src*="kickstarter.com"][src*="video.html"]',
'object',
'embed'
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var ignoreList = '.fitvidsignore';
if(settings.ignore) {
ignoreList = ignoreList + ', ' + settings.ignore;
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos = $allVideos.not('object object'); // SwfObj conflict patch
$allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.
$allVideos.each(function(){
var $this = $(this);
if($this.parents(ignoreList).length > 0) {
return; // Disable FitVids on this video.
}
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width'))))
{
$this.attr('height', 9);
$this.attr('width', 16);
}
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+'%');
$this.removeAttr('height').removeAttr('width');
});
});
};
// Works with either jQuery or Zepto
})( window.jQuery || window.Zepto );
/*
* Show disqus comments
*/
jQuery(document).ready(function() {
jQuery(".post").fitVids();
// Load discus comment
function initDisqusComments(){
if(config.disqus_shortname != '' && config.disqus_shortname != null && config.disqus_shortname != undefined) {
var disqus_shortname = config.disqus_shortname;
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}else {
alert("Please check Disqus short name configuration on your _config.yml");
}
}
initDisqusComments();
$(this).fadeOut(200);
/*$('.load-view').click(function(){
initDisqusComments();
$(this).fadeOut(200);
});*/
});
/*
* Scroll to top button
*/
jQuery(document).ready(function($){
// browser window scroll (in pixels) after which the "back to top" link is shown
var offset = 300,
//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
offset_opacity = 1200,
//duration of the top scrolling animation (in ms)
scroll_top_duration = 700,
//grab the "back to top" link
$back_to_top = $('.wc-top');
//hide or show the "back to top" link
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('wc-is-visible') : $back_to_top.removeClass('wc-is-visible wc-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('wc-fade-out');
}
});
//smooth scroll to top
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import compose from 'recompose/compose';
import getDefaultValues from './getDefaultValues';
import FormField from './FormField';
import Toolbar from './Toolbar';
const noop = () => {};
export const SimpleForm = ({ children, handleSubmit, invalid, record, resource, basePath, submitOnEnter }) => {
return (
<form onSubmit={ submitOnEnter ? handleSubmit : noop } className="simple-form">
<div style={{ padding: '0 1em 1em 1em' }}>
{React.Children.map(children, input => input && (
<div key={input.props.source} className={`aor-input-${input.props.source}`} style={input.props.style}>
<FormField input={input} resource={resource} record={record} basePath={basePath} />
</div>
))}
</div>
<Toolbar invalid={invalid} submitOnEnter={submitOnEnter} />
</form>
);
};
SimpleForm.propTypes = {
children: PropTypes.node,
defaultValue: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func,
]),
handleSubmit: PropTypes.func,
invalid: PropTypes.bool,
record: PropTypes.object,
resource: PropTypes.string,
basePath: PropTypes.string,
validate: PropTypes.func,
submitOnEnter: PropTypes.bool,
};
SimpleForm.defaultProps = {
submitOnEnter: true,
};
const enhance = compose(
connect((state, props) => ({
initialValues: getDefaultValues(state, props),
})),
reduxForm({
form: 'record-form',
enableReinitialize: true,
}),
);
export default enhance(SimpleForm);
|
export function allDaysDisabledBefore (day, unit, { minDate, includeDates } = {}) {
const dateBefore = day.clone().subtract(1, unit)
return (minDate && dateBefore.isBefore(minDate, unit)) ||
(includeDates && includeDates.every(includeDate => dateBefore.isBefore(includeDate, unit))) ||
false
}
|
var util = require('util');
var fs = require('fs');
var path = require('path');
var ltrim = require('underscore.string/ltrim');
exports.isCommand = function (input) {
if (input.toLowerCase().substr(0, prefix.length) === prefix)
return true;
else
return false;
};
exports.isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
exports.isURL = function (str) {
var pattern = new RedExp(
'^' +
'(?:(?:https?|ftp)://)' +
'(?:\\S+(?::\\S*)?@)?' +
'(?:' +
'(?!(?:10|127)(?:\\.\\d{1,3}){3})' +
'(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})' +
'(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})' +
'(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' +
'(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' +
'(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' +
'|' +
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
'(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' +
'\\.?' +
')' +
'(?::\\d{2,5})?' +
'(?:[/?#]\\S*)?' +
'$', 'i'
);
if (!pattern.test(str))
return false;
else
return true;
};
exports.getCommand = function (input) {
return input.replace(prefix, '').split(' ')[0];
};
exports.getFolders = function (SourcePath) {
return fs.readdirSync(SourcePath).filter(function (file) {
return fs.statSync(path.join(SourcePath, file)).isDirectory();
});
};
exports.getMessage = function (input) {
return input.replace(prefix, '');
};
exports.getParams = function (text) {
return text.split(' ').slice(1);
};
exports.normalizeChannel = function (channel) {
return util.format('#%s', ltrim(channel.toLowerCase() , '#'));
};
exports.numParams = function (text) {
return text.split(' ').length - 1;
};
exports.splitInput = function (splitAt, message, intSplit) {
var data = message.split(splitAt)[1];
return data.slice(0, data.length - intSplit);
};
|
//window.twttr=(function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],t=window.twttr||{};if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f){t._e.push(f);};return t;}(document,"script","twitter-wjs"));
function textchange(e) {
$('#twitter').attr({href: 'https://twitter.com/share?url=tw&text=' + encodeURIComponent($(this).val())});
// http://stackoverflow.com/a/2848483
length = $(this).val().length;
$('#length').text(140-length);
}
jQuery(document).ready(function($) {
$('#text').spellcheck({events: 'keyup', url: '/spellcheck.php'});
$('#text').change(textchange);
$('#text').keyup(textchange);
$( "#slider" ).slider({
value:1,
min: 1,
max: 5,
step: 1,
slide: function( event, ui ) {
$( "#depth" ).val( ui.value );
//$('#text').trigger('keyup');
}
});
});
|
function main() {
var N = 10000;
var lines = generateLines(N);
//timeCanvas2D(lines, N);
timeBatchDraw(lines, N);
}
function generateLines(N) {
var lines = new Array(N);
let canvas = document.getElementById("canvas");
let w = canvas.width;
let h = canvas.height;
// Create funky lines:
for (i=0; i<N; i++) {
lines[i] = {
fromX: (1.3*i/N) * w,
fromY: 0.5/(2*(i/N) + 1) * h,
toX: (0.1*i-1)/(N - i) * w,
toY: (0.3*N)/(5*(i*i)/N) * 0.5 * h
};
}
//console.log(lines);
return lines;
}
function timeBatchDraw(lines, N) {
let canvas = document.getElementById("canvas");
let params = {
maxLines: N,
clearColor: {r: 1, g: 1, b: 1, a: 1}
};
let batchDrawer = new BatchDrawer(canvas, params);
if (batchDrawer.error != null) {
console.log(batchDrawer.error);
return;
}
console.time("BatchDraw");
for (i=0; i<N; i++) {
batchDrawer.addLine(lines[i].fromX, lines[i].fromY, lines[i].toX, lines[i].toY, 0.001, 1, 0.5, 0.1, 1);
}
batchDrawer.draw(false);
console.timeEnd("BatchDraw");
}
function timeCanvas2D(lines, N) {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.lineWidth = 0.01;
ctx.strokeStyle = '#ffa500';
ctx.fillStyle="#FFFFFF";
console.time("Canvas2D");
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i=0; i<N; i++) {
ctx.beginPath();
ctx.moveTo(lines[i].fromX, lines[i].fromY);
ctx.lineTo(lines[i].toX, lines[i].toY);
ctx.stroke();
}
console.timeEnd("Canvas2D");
}
|
marriageMapApp.factory('MapService', ['UtilArrayService', function(UtilArrayService) {
var mapLoading = true;
var observerPOIShowCallback = null;
var map = {
center: { latitude: null, longitude: null },
zoom: null
};
var poisDay = [
{
id : 10,
coords : {
latitude : 48.8143725,
longitude : -3.4430839999999753
},
icon : "img/church/blue-outline-church-64.png",
iconInverse : "img/church/blank-outline-church-64.png",
options : "",
title : "L'église",
description : "Nous vous donnons rendez-vous à 10h45 pour la célébration qui aura lieu à l'église Saint Jacques à Perros Guirec.",
astuces : [{type : "astuce", value : "Pour vous garer, pensez au parking du Carrefour City, ou celui derrière l'église (place des halles) ou dans le centre ville."}]
},
{
id : 20,
coords : {
latitude : 48.8156313,
longitude : -3.4447666
},
icon : "img/ring/blue-outline-ring-64.png",
iconInverse : "img/ring/blank-outline-ring-64.png",
options : "",
title : "La mairie",
description : "La cérémonie civile aura lieu à 10h dans la mairie de Perros-Guirec.",
astuces : [{type : "astuce", value : "Pour vous garer, pensez au parking de la police municipale (rue Anatole France), nous nous rendrons ensuite à l'église à pied."}]
},
{
id : 30,
coords : {
latitude : 48.8151101,
longitude : -3.4543653
},
icon : "img/glasses/blue-outline-glasses-64.png",
iconInverse : "img/glasses/blank-outline-glasses-64.png",
options : "",
title : "Le vin d'honneur",
description : "Après l'église, retrouvons nous pour partager un moment de convivialité au palais des Congrès, rue du Maréchal Foch.",
astuces : [{type : "astuce", value : "Nous irons à pied depuis l'église (15 min de marche). Prévoyez des chaussures adéquates !"}]
},
{
id : 40,
coords : {
latitude : 48.8155061,
longitude : -3.3579911
},
icon : "img/servers/blue-outline-servers-64.png",
iconInverse : "img/servers/blank-outline-servers-64.png",
options : "",
title : "Le repas",
description : "Les festivités se dérouleront dans la salle des fêtes de Trévou Tréguignec, 23 rue de la mairie.",
astuces : [{type : "astuce", value : "Les logements proposés sur la carte sont tous à moins de 10 min à pied de la salle."},{type : "astuce", value : "N'hésitez pas à regarder aussi les chambres d'hôtes, gîtes ou locations non mentionnés ici."}]
}
];
var poisSleep = [
{
id : 100,
coords : {
latitude : 48.819331,
longitude : -3.352362
},
icon : "img/camping/blue-outline-camping-64.png",
iconInverse : "img/camping/blank-outline-camping-64.png",
options : "",
distance : "à 700 m de la salle",
title : "Camping le Mat",
description : "<i>Entre Paimpol et Perros-Guirec, la vue sur les 7 îles est imprenable. La grande plage de sable fin de la baie de Trestel, spot reconnu par les amateurs de glisse, vous invite à la détente ou à des vacances dynamiques. C 'est la Bretagne de la Côte de Granit Rose, avec ses sentiers côtiers et ses longues balades iodées. Au camping, autour de la piscine chauffée : flânerie, aquagym, et en été, nocturnes-piscine, concerts et danses bretonnes.</i><br><img src ='img/addresses/mat.jpg'>",
astuces : [
{
type : "astuce",
value : "Si vous réservez pour une seule nuit, pensez à préciser qu'il s'agit de notre mariage afin de faciliter votre réservation."
},
{
type : "phone",
value : "02 96 23 71 52"
},
{
type : "website",
value : "<a target='_new' href ='http://www.flowercampings.com/camping-bretagne/camping-le-mat'>Consulter le site internet (nouvel onglet)</a>"
}
]
},
{
id : 110,
coords : {
latitude : 48.8189145,
longitude : -3.3538073
},
icon : "img/hotel/blue-outline-hotel-64.png",
iconInverse : "img/hotel/blank-outline-hotel-64.png",
options : "",
distance : "à 600 m de la salle",
title : "Les Terrasses de Trestel",
description : "<i>Entre Tréguier et Perros-Guirec, en bordure d'une magnifique plage de sable fin, la Résidence Hôtelière «les terrasses de Trestel» vous ouvre les portes de la côte de Granit Rose. Vous aurez le bonheur d'habiter une maisonnette ou un appartement au coeur d'un grand jardin devant la mer.</i><br><img src='img/addresses/trestel.jpg'>",
astuces : [
{
type : "phone",
value : "02 96 15 10 10"
},
{
type : "website",
value : "<a target='_new' href ='http://location-bord-de-mer-appartement-vacances-piscine-tourisme.terrasses-trestel.fr/'>Consulter le site internet (nouvel onglet)</a>"
}
]
},
{
id : 120,
coords : {
latitude : 48.8165061,
longitude : -3.3597911
},
icon : "img/camping/blue-outline-camping-64.png",
iconInverse : "img/camping/blank-outline-camping-64.png",
options : "",
title : "Camping les Macareux",
distance : "à 300 m de la salle",
description : "<i>Camping familial, très calme et reposant (ni piscine ,ni animation), ombragé situé dans un site remarquable à 800 mètres de la grande plage de sable fin de Trestel et à 400 mètres du port de plaisance 'Port Le Goff'.</i><br><img src ='img/addresses/macareux.jpg'>",
astuces : [
{
type : "astuce",
value : "Si vous réservez pour une seule nuit, pensez à préciser qu'il s'agit de notre mariage afin de faciliter votre réservation."
},
{
type : "phone",
value : "02 96 23 71 45"
},
{
type : "website",
value : "<a target='_new' href ='http://camping-les-macareux.monsite-orange.fr/'>Consulter le site internet (nouvel onglet)</a>"
}
]
}
];
var currentPois = [];
var service = {
/**
* Retourne le centre de la carte
*/
getMap : function () {
return map;
},
/**
* Retourne les points d'intérêts
*/
currentPois : currentPois,
setCurrentPoisDay : function(set) {
angular.forEach(currentPois, function(value, key) {
value.options = {animation : null};
});
if (set) {
angular.forEach(poisDay, function(value, key) {
value.options = {animation : 2};
});
UtilArrayService.addArrayToArray(currentPois, poisDay);
if(observerPOIShowCallback)
observerPOIShowCallback(poisDay);
} else {
UtilArrayService.removeArrayFromArrayByAttribute("id", currentPois, poisDay);
}
},
setCurrentPoisSleep : function(set) {
angular.forEach(currentPois, function(value, key) {
value.options = {animation : null};
});
if (set) {
angular.forEach(poisSleep, function(value, key) {
value.options = {animation : 2};
});
UtilArrayService.addArrayToArray(currentPois, poisSleep);
if(observerPOIShowCallback)
observerPOIShowCallback(poisSleep, true);
} else {
UtilArrayService.removeArrayFromArrayByAttribute("id", currentPois, poisSleep);
}
},
setMapLoading : function(value) {
mapLoading = value;
},
getMapLoading : function() {
return mapLoading;
},
setObserverPOIShow : function(callback) {
observerPOIShowCallback = callback;
}
}
service.setCurrentPoisDay(true);
return service;
}]); |
xdescribe('uiMask', function () {
var inputHtml = "<input ui-mask=\"'(9)9'\" ng-model='x'>";
var $compile, $rootScope, element;
beforeEach(module('ui.directives'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
}));
describe('ui changes on model changes', function () {
it('should update ui valid model value', function () {
$rootScope.x = undefined;
element = $compile(inputHtml)($rootScope);
$rootScope.$digest();
expect(element.val()).toBe('');
$rootScope.$apply(function () {
$rootScope.x = 12;
});
expect(element.val()).toBe('(1)2');
});
it('should wipe out ui on invalid model value', function () {
$rootScope.x = 12;
element = $compile(inputHtml)($rootScope);
$rootScope.$digest();
expect(element.val()).toBe('(1)2');
$rootScope.$apply(function () {
$rootScope.x = 1;
});
expect(element.val()).toBe('');
});
});
describe('model binding on ui change', function () {
//TODO: was having har time writing those tests, will open a separate issue for those
});
describe('should fail', function() {
it('errors on missing quotes', function() {
$rootScope.x = 42;
var errorInputHtml = "<input ui-mask=\"(9)9\" ng-model='x'>";
element = $compile(errorInputHtml)($rootScope);
expect($rootScope.$digest).toThrow('The Mask widget is not correctly set up');
});
});
}); |
$(document).ready(function() {
///*определение ширины скролбара
// создадим элемент с прокруткой
var div = document.createElement('div');
div.style.overflowY = 'scroll';
div.style.width = '50px';
div.style.height = '50px';
div.style.position = 'absolute';
div.style.zIndex = '-1';
// при display:none размеры нельзя узнать
// нужно, чтобы элемент был видим,
// visibility:hidden - можно, т.к. сохраняет геометрию
div.style.visibility = 'hidden';
document.body.appendChild(div);
var scrollWidth = div.offsetWidth - div.clientWidth;
document.body.removeChild(div);
//*/
var fixedblock = $('#fixed');
var stick_state = false;
function fxm() {
if ($(window).width() > 640-scrollWidth) {
fixedblock.trigger("sticky_kit:detach");
fixedblock.stick_in_parent({
parent: '#main .columns',
offset_top: 30,
inner_scrolling: false
});
fixedblock.stick_in_parent()
.on("sticky_kit:stick", function(e) {
stick_state = true;
})
.on("sticky_kit:unstick", function(e) {
stick_state = false;
});
} else {
fixedblock.trigger("sticky_kit:detach");
}
}
fxm();
var navigation = document.getElementById('navigation');
if (navigation) {
var new_fix_elem = document.createElement('div');
new_fix_elem.setAttribute('class', 'nav__bounce__element');
navigation.parentNode.insertBefore(new_fix_elem, navigation);
}
var my__abs__list = document.querySelector('.my__abs__list');
var count_change = -1;
var fix_flag = false;
var navleft = navigation.querySelector('.block--left .menu');
/* шаг скролла */
var topless = 0;
var difference = 0;
function navig_fixit() {
var cont_top = window.pageYOffset ? window.pageYOffset : document.body.scrollTop;
var docHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
difference = cont_top - topless;
topless = cont_top;
if (navigation) {
if ($(window).width() > 768 - scrollWidth) {
var height = navigation.offsetHeight;
var rect = navigation.getBoundingClientRect();
var rect2 = new_fix_elem.getBoundingClientRect();
navigation.style.left = rect.left + 'px';
navigation.style.width = new_fix_elem.offsetWidth + 'px';
if (navleft.classList.contains('open') === true) {
var rectus = navleft.getBoundingClientRect();
console.log(rectus.height);
if (navigation.style.marginTop == '') {
navigation.style.marginTop = '0px';
}
var ms = parseInt(navigation.style.marginTop);
ms = Math.abs(ms);
ms += difference;
if (ms >= 0) {
var x_height = height + rectus.height - 50;
if (ms <= x_height - docHeight) {
navigation.style.marginTop = -ms+'px';
} else {
if (difference < 0) {
navigation.style.marginTop = -ms+'px';
}
}
}
/* navigation.classList.remove('fixed'); */
new_fix_elem.style.height = '0px';
return false;
}
if (fix_flag === false) {
if (rect2.top + height*2 < 0) {
if (rect2.top > count_change) {
navigation.classList.add('fixed');
new_fix_elem.style.height = height + 'px';
fix_flag = true;
fixedblock.css('margin-top', height + 'px');
if (stick_state === false) {
fixedblock.css('margin-top', '0px');
}
} else {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
fixedblock.css('margin-top', '0px');
}
}
} else {
if (rect2.top > count_change) {
navigation.classList.add('fixed');
new_fix_elem.style.height = height + 'px';
fix_flag = true;
fixedblock.css('margin-top', height + 'px');
if (stick_state === false) {
fixedblock.css('margin-top', '0px');
}
if (rect2.top > 0) {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
}
} else {
navigation.classList.remove('fixed');
new_fix_elem.style.height = '0px';
fix_flag = false;
my__abs__list.classList.remove('active');
fixedblock.css('margin-top', '0px');
}
}
count_change = rect2.top;
} else {
navigation.classList.remove('fixed');
navigation.style = '';
new_fix_elem.style.height = '0px';
my__abs__list.classList.remove('active');
}
}
}
navig_fixit();
//debounce
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// Использование
var myEfficientFn = debounce(function() {
// All the taxing stuff you do
navig_fixit();
fxm();
if (navigation) {
navigation.classList.remove('active');
}
}, 200);
/* var myEfficientFn2 = debounce(function() {
// All the taxing stuff you do
fxm();
}, 250); */
window.addEventListener('resize', myEfficientFn);
/* window.addEventListener('scroll', myEfficientFn2); */
$(window).scroll(function() {
navig_fixit();
});
}); |
<script type="text/javascript">
//set the interval temporary variable
var setIntrVal = null;
var intrVal = 3000;
//lets get the slider elements
var slides = document.getElementById('slides'); //get the <ul id="slides">
var slide = document.getElementsByClassName('slide'); //get the <li class="slide">
var active = document.getElementsByClassName('active'); //get the <li class="slide active">
//lets set z-index properties to the slides
var j = 99; //lets initialize a higher value, change this if you need to
for (var i = 0; i < slide.length; i++) {
slide[i].style.zIndex = j;
j--;
}
var ywtSlider = {
init: function (newIntrVal) {
//pass the new interval value into the intrVal variable
if(newIntrVal) intrVal = newIntrVal;
//start cycle on init
ywtSlider.cycle();
},
cycle: function() {
//check if cycle is already started then clear the cycle
//this will clear the current interval
if(setIntrVal) clearInterval(setIntrVal);
//ok lets start another cycle
setIntrVal = setInterval(function () {
ywtSlider.slide('next');
}, intrVal);
//console.log(interVal);
},
slide: function (dir) {
//lets get the slide index number so we can set this to the slide
var nodeList = Array.prototype.slice.call(slides.children);
var itemIndex = nodeList.indexOf(active[active.length - 1]);
if (dir == 'back') {
//check and run if the direction is back
//if the direction is back
//lets remove the class starting from the current item to the last
for (k = itemIndex; k < slide.length; k++) {
slide[k].className = 'slide';
}
} else if (dir == 'next') {
//check and run if the direction is next
//lets check first the position of the current item
if (itemIndex + 1 < slide.length - 1) {
//if the next item index is not the last item lets set the 'active' class
//to the next item
slide[itemIndex + 1].className += ' active';
} else {
//if the next item supposed to be the last item, lets remove the 'active' class
//from all slide elements
for (var k = 0; k < slide.length; k++) {
slide[k].className = 'slide';
}
}
}
//continue the cycle
ywtSlider.cycle();
}
};
window.onload = function() {
ywtSlider.init(5000);
}
</script>
|
/**
* Created by Cai Kang Jie on 2017/7/31.
*/
import lazyLoading from './../../store/modules/routeConfig/lazyLoading'
export default {
name: 'UI Features',
expanded: false,
sidebarMeta: {
title: 'UI Features',
icon: 'ion-android-laptop',
order: 1
},
subMenu: [{
name: 'Panels',
path: '/ui/panels',
component: lazyLoading('ui/panels'),
sidebarMeta: {
title: 'Panels',
order: 100
}
}, {
name: 'Typography',
path: '/ui/typography',
component: lazyLoading('ui/typography'),
sidebarMeta: {
title: 'Typography',
order: 200
}
}, {
name: 'Grid',
path: '/ui/grid',
component: lazyLoading('ui/grid'),
sidebarMeta: {
title: 'Grid',
order: 400
}
}, {
name: 'Buttons',
path: '/ui/buttons',
component: lazyLoading('ui/buttons'),
sidebarMeta: {
title: 'Buttons',
order: 500
}
}, {
name: 'Progress Bars',
path: '/ui/progressBars',
component: lazyLoading('ui/progressBars'),
sidebarMeta: {
title: 'Progress Bars',
order: 600
}
}, {
name: 'Alerts',
path: '/ui/alerts',
component: lazyLoading('ui/alerts'),
sidebarMeta: {
title: 'Alerts',
order: 700
}
}]
}
|
'use strict';
function Memoized() {}
const memoize = (
// Create memoized function
fn // function, sync or async
// Returns: function, memoized
) => {
const cache = new Map();
const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
callback(record.err, record.data);
return;
}
fn(...args, (err, data) => {
memoized.add(key, err, data);
memoized.emit('memoize', key, err, data);
callback(err, data);
});
};
const fields = {
cache,
timeout: 0,
limit: 0,
size: 0,
maxSize: 0,
maxCount: 0,
events: {
timeout: null,
memoize: null,
overflow: null,
add: null,
del: null,
clear: null
}
};
Object.setPrototypeOf(memoized, Memoized.prototype);
return Object.assign(memoized, fields);
};
Memoized.prototype.clear = function() {
this.emit('clear');
this.cache.clear();
};
Memoized.prototype.add = function(key, err, data) {
this.emit('add', err, data);
this.cache.set(key, { err, data });
return this;
};
Memoized.prototype.del = function(key) {
this.emit('del', key);
this.cache.delete(key);
return this;
};
Memoized.prototype.get = function(key, callback) {
const record = this.cache.get(key);
callback(record.err, record.data);
return this;
};
Memoized.prototype.on = function(
eventName, // string
listener // function, handler
// on('memoize', function(err, data))
// on('add', function(key, err, data))
// on('del', function(key))
// on('clear', function())
) {
if (eventName in this.events) {
this.events[eventName] = listener;
}
};
Memoized.prototype.emit = function(
// Emit Collector events
eventName, // string
...args // rest arguments
) {
const event = this.events[eventName];
if (event) event(...args);
};
module.exports = {
memoize,
};
|
$(document).ready(function() {
$(".container").hide();
$(".container").fadeIn('5000');
$(".showcase-wrapper").hide();
$(".showcase-wrapper").fadeIn("slow");
});
/*
var toggle = false;
$('.nav-toggle').on('click', function () {
if (toggle == false) {
$('#sidebar-wrapper').stop().animate({
'left': '4px'
});
toggle = true;
} else {
$('#sidebar-wrapper').stop().animate({
'left': '250px'
});
toggle = false;
}
});
*/
$(function() {
$('.project-box>.row>.project-post').append('<span class="more-info">Click for more information</span>');
$('.project-box').click(function(e) {
if (e.target.tagName == "A" || e.target.tagName == "IMG") {
return true;
}
$(this).find('.more-info').toggle();
$(this).find('.post').slideToggle();
});
});
|
var jwt = require('jsonwebtoken');
/**
* Middleware
*/
module.exports = function(scullog){
return {
realIp: function* (next) {
this.req.ip = this.headers['x-forwarded-for'] || this.ip;
yield* next;
},
handelError: function* (next) {
try {
yield* next;
} catch (err) {
this.status = err.status || 500;
this.body = err.message;
C.logger.error(err.stack);
this.app.emit('error', err, this);
}
},
loadRealPath: function* (next) {
// router url format must be /api/(.*)
this.request.fPath = scullog.getFileManager().filePath(this.params[0], this.request.query.base);
C.logger.info(this.request.fPath);
yield* next;
},
checkPathExists: function* (next) {
// Must after loadRealPath
if (!(yield scullog.getFileManager().exists(this.request.fPath))) {
this.status = 404;
this.body = 'Path Not Exists!';
}
else {
yield* next;
}
},
checkBase: function* (next){
var base = this.request.query.base;
if (!!!base || scullog.getConfiguration().directory.indexOf(base) == -1) {
this.status = 400;
this.body = 'Invalid Base Location!';
} else {
yield* next;
}
},
checkPathNotExists: function* (next) {
// Must after loadRealPath
if (this.query.type != 'UPLOAD_FILE' && (yield scullog.getFileManager().exists(this.request.fPath))) {
this.status = 400;
this.body = 'Path Has Exists!';
}
else {
yield* next;
}
},
checkAccessCookie: function* (next) {
if (this.request.url.indexOf('/access') == -1) {
var accessJwt = this.cookies.get(scullog.getConfiguration().id);
if (accessJwt) {
try {
var decoded = jwt.verify(accessJwt, scullog.getConfiguration().secret);
} catch (e) {
this.append('access-expired', 'true');
}
} else if (this.request.header["access-role"] != "default") {
this.append('access-expired', 'true');
}
}
yield* next;
}
}
};
|
var Thermostat = function() {
this.temp = 20;
this.mode = 'power saving';
this.min = 10;
this.max = 25;
};
Thermostat.prototype.setPowerSaving = function(value) {
this.mode = (value ? 'power saving' : 'normal');
this.max = (value ? 25 : 32);
};
Thermostat.prototype.increase = function() {
if(this.temp < this.max) {this.temp++}
};
Thermostat.prototype.decrease = function() {
if(this.temp > this.min) {this.temp--}
};
Thermostat.prototype.resetTemp = function() {
this.temp = 20;
};
|
/* @flow */
import React from "react";
import PropTypes from "prop-types";
import {
Text,
TouchableOpacity,
Platform,
StyleSheet,
ScrollView,
PixelRatio,
View
} from "react-native";
import Modal from "react-native-modalbox";
type Props = {
styleContainer?: Object,
coverScreen?: boolean,
backButtonEnabled?: boolean,
height?: number,
title?: string,
options: Array<Object>,
refs: Function,
fontFamily?: string,
titleFontFamily?: string,
isOpen?: boolean,
cancelButtonIndex?: number,
itemDivider?: number
};
type State = void;
class BottomSheet extends React.PureComponent<Props, State> {
open: Function;
static propTypes = {
styleContainer: PropTypes.object,
coverScreen: PropTypes.bool,
backButtonEnabled: PropTypes.bool,
height: PropTypes.number,
title: PropTypes.string,
options: PropTypes.arrayOf(PropTypes.object).isRequired,
refs: PropTypes.func.isRequired,
fontFamily: PropTypes.string,
titleFontFamily: PropTypes.string,
isOpen: PropTypes.bool,
cancelButtonIndex: PropTypes.number,
itemDivider: PropTypes.number
};
renderOption = (options: Array<Object>) => {
return options.map((item, index) => {
return (
<View style={{ flexDirection: "column" }} key={index}>
<TouchableOpacity onPress={item.onPress}>
<View style={styles.item}>
{item.icon}
<Text
style={[styles.text, { fontFamily: this.props.fontFamily }]}
>
{item.title}
</Text>
</View>
</TouchableOpacity>
{this.props.itemDivider === index + 1 ? (
<View style={styles.separator} />
) : null}
</View>
);
});
};
renderTitle = () => {
if (!this.props.title) {
return;
}
return (
<Text style={[styles.title, { fontFamily: this.props.titleFontFamily }]}>
{this.props.title}
</Text>
);
};
render() {
return (
<Modal
style={[this.props.styleContainer, { height: this.props.height }]}
backButtonClose={this.props.backButtonEnabled}
position="bottom"
isOpen={this.props.isOpen}
ref={this.props.refs}
coverScreen={this.props.coverScreen}
>
<ScrollView style={styles.modal}>
{this.renderTitle()}
{this.renderOption(this.props.options)}
</ScrollView>
</Modal>
);
}
}
const styles = StyleSheet.create({
text: {
paddingHorizontal: 32,
fontFamily: "Roboto",
textAlignVertical: "center",
color: "#000",
opacity: 0.87
},
item: {
flexDirection: "row",
height: 48,
alignItems: "center",
paddingLeft: 16,
paddingRight: 16
},
title: {
height: 42,
color: "#000",
opacity: 0.54,
marginLeft: 16
},
modal: {
marginTop: 16
},
separator: {
height: 1 / PixelRatio.get(),
backgroundColor: "#CCCCCC",
marginTop: 7,
marginBottom: 8,
width: "100%"
}
});
export default BottomSheet;
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, describe, it, expect, beforeEach, afterEach, waitsFor, runs, $ */
define(function (require, exports, module) {
'use strict';
var Editor = require("editor/Editor").Editor,
EditorCommandHandlers = require("editor/EditorCommandHandlers"),
Commands = require("command/Commands"),
CommandManager = require("command/CommandManager"),
SpecRunnerUtils = require("spec/SpecRunnerUtils"),
EditorUtils = require("editor/EditorUtils");
describe("EditorCommandHandlers", function () {
var defaultContent = "function foo() {\n" +
" function bar() {\n" +
" \n" +
" a();\n" +
" \n" +
" }\n" +
"\n" +
"}";
var myDocument, myEditor;
beforeEach(function () {
// create dummy Document for the Editor
myDocument = SpecRunnerUtils.createMockDocument(defaultContent);
// create Editor instance (containing a CodeMirror instance)
$("body").append("<div id='editor'/>");
myEditor = new Editor(myDocument, true, "javascript", $("#editor").get(0), {});
// Must be focused so editor commands target it
myEditor.focus();
});
afterEach(function () {
myEditor.destroy();
myEditor = null;
$("#editor").remove();
myDocument = null;
});
// Helper functions for testing cursor position / selection range
function expectCursorAt(pos) {
var selection = myEditor.getSelection();
expect(selection.start).toEqual(selection.end);
expect(selection.start).toEqual(pos);
}
function expectSelection(sel) {
expect(myEditor.getSelection()).toEqual(sel);
}
describe("Line comment/uncomment", function () {
it("should comment/uncomment a single line, cursor at start", function () {
myEditor.setCursorPos(3, 0);
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[3] = "// a();";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 3, ch: 2});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectCursorAt({line: 3, ch: 0});
});
it("should comment/uncomment a single line, cursor at end", function () {
myEditor.setCursorPos(3, 12);
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[3] = "// a();";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 3, ch: 14});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectCursorAt({line: 3, ch: 12});
});
it("should comment/uncomment first line in file", function () {
myEditor.setCursorPos(0, 0);
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[0] = "//function foo() {";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 0, ch: 2});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectCursorAt({line: 0, ch: 0});
});
it("should comment/uncomment a single partly-selected line", function () {
// select "function" on line 1
myEditor.setSelection({line: 1, ch: 4}, {line: 1, ch: 12});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[1] = "// function bar() {";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 6}, end: {line: 1, ch: 14}});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 1, ch: 4}, end: {line: 1, ch: 12}});
});
it("should comment/uncomment a single selected line", function () {
// selection covers all of line's text, but not \n at end
myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[1] = "// function bar() {";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 0}, end: {line: 1, ch: 22}});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 1, ch: 0}, end: {line: 1, ch: 20}});
});
it("should comment/uncomment a single fully-selected line (including LF)", function () {
// selection including \n at end of line
myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[1] = "// function bar() {";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 1, ch: 0}, end: {line: 2, ch: 0}});
});
it("should comment/uncomment multiple selected lines", function () {
// selection including \n at end of line
myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[1] = "// function bar() {";
lines[2] = "// ";
lines[3] = "// a();";
lines[4] = "// ";
lines[5] = "// }";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}});
});
it("should comment/uncomment ragged multi-line selection", function () {
myEditor.setSelection({line: 1, ch: 6}, {line: 3, ch: 9});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var lines = defaultContent.split("\n");
lines[1] = "// function bar() {";
lines[2] = "// ";
lines[3] = "// a();";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 8}, end: {line: 3, ch: 11}});
expect(myEditor.getSelectedText()).toEqual("nction bar() {\n// \n// a");
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 1, ch: 6}, end: {line: 3, ch: 9}});
});
it("should comment/uncomment after select all", function () {
myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
var expectedText = "//function foo() {\n" +
"// function bar() {\n" +
"// \n" +
"// a();\n" +
"// \n" +
"// }\n" +
"//\n" +
"//}";
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 3}});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}});
});
it("should comment/uncomment lines that were partially commented out already, our style", function () {
// Start with line 3 commented out, with "//" at column 0
var lines = defaultContent.split("\n");
lines[3] = "// a();";
var startingContent = lines.join("\n");
myDocument.setText(startingContent);
// select lines 1-3
myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
lines = defaultContent.split("\n");
lines[1] = "// function bar() {";
lines[2] = "// ";
lines[3] = "//// a();";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(startingContent);
expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}});
});
it("should comment/uncomment lines that were partially commented out already, comment closer to code", function () {
// Start with line 3 commented out, with "//" snug against the code
var lines = defaultContent.split("\n");
lines[3] = " //a();";
var startingContent = lines.join("\n");
myDocument.setText(startingContent);
// select lines 1-3
myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
lines = defaultContent.split("\n");
lines[1] = "// function bar() {";
lines[2] = "// ";
lines[3] = "// //a();";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(startingContent);
expectSelection({start: {line: 1, ch: 0}, end: {line: 4, ch: 0}});
});
it("should uncomment indented, aligned comments", function () {
// Start with lines 1-5 commented out, with "//" all aligned at column 4
var lines = defaultContent.split("\n");
lines[1] = " //function bar() {";
lines[2] = " // ";
lines[3] = " // a();";
lines[4] = " // ";
lines[5] = " //}";
var startingContent = lines.join("\n");
myDocument.setText(startingContent);
// select lines 1-5
myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}});
});
it("should uncomment ragged partial comments", function () {
// Start with lines 1-5 commented out, with "//" snug up against each non-blank line's code
var lines = defaultContent.split("\n");
lines[1] = " //function bar() {";
lines[2] = " ";
lines[3] = " //a();";
lines[4] = " ";
lines[5] = " //}";
var startingContent = lines.join("\n");
myDocument.setText(startingContent);
// select lines 1-5
myEditor.setSelection({line: 1, ch: 0}, {line: 6, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_COMMENT, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 1, ch: 0}, end: {line: 6, ch: 0}});
});
});
describe("Duplicate", function () {
it("should duplicate whole line if no selection", function () {
// place cursor in middle of line 1
myEditor.setCursorPos(1, 10);
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines.splice(1, 0, " function bar() {");
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 2, ch: 10});
});
it("should duplicate line + \n if selected line is at end of file", function () {
var lines = defaultContent.split("\n"),
len = lines.length;
// place cursor at the beginning of the last line
myEditor.setCursorPos(len - 1, 0);
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
lines.push("}");
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: len, ch: 0});
});
it("should duplicate first line", function () {
// place cursor at start of line 0
myEditor.setCursorPos(0, 0);
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines.splice(0, 0, "function foo() {");
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 1, ch: 0});
});
it("should duplicate empty line", function () {
// place cursor on line 6
myEditor.setCursorPos(6, 0);
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines.splice(6, 0, "");
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 7, ch: 0});
});
it("should duplicate selection within a line", function () {
// select "bar" on line 1
myEditor.setSelection({line: 1, ch: 13}, {line: 1, ch: 16});
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines[1] = " function barbar() {";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 16}, end: {line: 1, ch: 19}});
});
it("should duplicate when entire line selected, excluding newline", function () {
// select all of line 1, EXcluding trailing \n
myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20});
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines[1] = " function bar() { function bar() {";
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 20}, end: {line: 1, ch: 40}});
});
it("should duplicate when entire line selected, including newline", function () {
// select all of line 1, INcluding trailing \n
myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0});
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines.splice(1, 0, " function bar() {");
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 2, ch: 0}, end: {line: 3, ch: 0}});
});
it("should duplicate when multiple lines selected", function () {
// select lines 1-3
myEditor.setSelection({line: 1, ch: 0}, {line: 4, ch: 0});
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines.splice(1, 0, " function bar() {",
" ",
" a();");
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 4, ch: 0}, end: {line: 7, ch: 0}});
});
it("should duplicate selection crossing line boundary", function () {
// select from middle of line 1 to middle of line 3
myEditor.setSelection({line: 1, ch: 13}, {line: 3, ch: 11});
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var lines = defaultContent.split("\n");
lines.splice(1, 3, " function bar() {",
" ",
" a()bar() {",
" ",
" a();");
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 3, ch: 11}, end: {line: 5, ch: 11}});
});
it("should duplicate after select all", function () {
myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1});
CommandManager.execute(Commands.EDIT_DUPLICATE, myEditor);
var expectedText = defaultContent + defaultContent;
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 7, ch: 1}, end: {line: 14, ch: 1}});
});
});
describe("Move Lines Up/Down", function () {
it("should move whole line up if no selection", function () {
// place cursor in middle of line 1
myEditor.setCursorPos(1, 10);
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[0];
lines[0] = lines[1];
lines[1] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 0, ch: 10});
});
it("should move whole line down if no selection", function () {
// place cursor in middle of line 1
myEditor.setCursorPos(1, 10);
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[2];
lines[2] = lines[1];
lines[1] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 2, ch: 10});
});
it("shouldn't move up first line", function () {
// place cursor at start of line 0
myEditor.setCursorPos(0, 0);
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectCursorAt({line: 0, ch: 0});
});
it("shouldn't move down last line", function () {
var lines = defaultContent.split("\n"),
len = lines.length;
// place cursor at the beginning of the last line
myEditor.setCursorPos(len - 1, 0);
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: len - 1, ch: 0});
});
it("should move up empty line", function () {
// place cursor on line 6
myEditor.setCursorPos(6, 0);
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[5];
lines[5] = lines[6];
lines[6] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 5, ch: 0});
});
it("should move down empty line", function () {
// place cursor on line 6
myEditor.setCursorPos(6, 0);
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[7];
lines[7] = lines[6];
lines[6] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 7, ch: 0});
});
it("should move up when entire line selected, excluding newline", function () {
// select all of line 1, EXcluding trailing \n
myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20});
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[0];
lines[0] = lines[1];
lines[1] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 0, ch: 0}, end: {line: 0, ch: 20}});
});
it("should move down when entire line selected, excluding newline", function () {
// select all of line 1, EXcluding trailing \n
myEditor.setSelection({line: 1, ch: 0}, {line: 1, ch: 20});
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[2];
lines[2] = lines[1];
lines[1] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 2, ch: 0}, end: {line: 2, ch: 20}});
});
it("should move up when entire line selected, including newline", function () {
// select all of line 1, INcluding trailing \n
myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[0];
lines[0] = lines[1];
lines[1] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 0, ch: 0}, end: {line: 1, ch: 0}});
});
it("should move down when entire line selected, including newline", function () {
// select all of line 1, INcluding trailing \n
myEditor.setSelection({line: 1, ch: 0}, {line: 2, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[2];
lines[2] = lines[1];
lines[1] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 2, ch: 0}, end: {line: 3, ch: 0}});
});
it("should move up when multiple lines selected", function () {
// select lines 2-3
myEditor.setSelection({line: 2, ch: 0}, {line: 4, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[1];
lines[1] = lines[2];
lines[2] = lines[3];
lines[3] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 0}});
});
it("should move down when multiple lines selected", function () {
// select lines 2-3
myEditor.setSelection({line: 2, ch: 0}, {line: 4, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[4];
lines[4] = lines[3];
lines[3] = lines[2];
lines[2] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 3, ch: 0}, end: {line: 5, ch: 0}});
});
it("should move up selection crossing line boundary", function () {
// select from middle of line 2 to middle of line 3
myEditor.setSelection({line: 2, ch: 8}, {line: 3, ch: 11});
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[1];
lines[1] = lines[2];
lines[2] = lines[3];
lines[3] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 8}, end: {line: 2, ch: 11}});
});
it("should move down selection crossing line boundary", function () {
// select from middle of line 2 to middle of line 3
myEditor.setSelection({line: 2, ch: 8}, {line: 3, ch: 11});
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[4];
lines[4] = lines[3];
lines[3] = lines[2];
lines[2] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 3, ch: 8}, end: {line: 4, ch: 11}});
});
it("should move the last line up", function () {
// place cursor in last line
myEditor.setCursorPos(7, 0);
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[6];
lines[6] = lines[7];
lines[7] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 6, ch: 0});
});
it("should move the first line down", function () {
// place cursor in first line
myEditor.setCursorPos(0, 0);
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[1];
lines[1] = lines[0];
lines[0] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectCursorAt({line: 1, ch: 0});
});
it("should move the last lines up", function () {
// select lines 6-7
myEditor.setSelection({line: 6, ch: 0}, {line: 7, ch: 1});
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[5];
lines[5] = lines[6];
lines[6] = lines[7];
lines[7] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 5, ch: 0}, end: {line: 6, ch: 1}});
});
it("should move the first lines down", function () {
// select lines 0-1
myEditor.setSelection({line: 0, ch: 0}, {line: 2, ch: 0});
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
var lines = defaultContent.split("\n");
var temp = lines[2];
lines[2] = lines[1];
lines[1] = lines[0];
lines[0] = temp;
var expectedText = lines.join("\n");
expect(myDocument.getText()).toEqual(expectedText);
expectSelection({start: {line: 1, ch: 0}, end: {line: 3, ch: 0}});
});
it("shouldn't move up after select all", function () {
myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1});
CommandManager.execute(Commands.EDIT_LINE_UP, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}});
});
it("shouldn't move down after select all", function () {
myEditor.setSelection({line: 0, ch: 0}, {line: 7, ch: 1});
CommandManager.execute(Commands.EDIT_LINE_DOWN, myEditor);
expect(myDocument.getText()).toEqual(defaultContent);
expectSelection({start: {line: 0, ch: 0}, end: {line: 7, ch: 1}});
});
});
});
});
|
var ParseIndex = require("../../index");
module.exports = function addRole(params) {
Parse.Cloud.define("addRole", (req, res) => {
if (req.params.masterKey === ParseIndex.config.masterKey) {
var roleName = req.params.roleName;
if (roleName.length > 2) {
var roleACL = new Parse.ACL();
roleACL.setPublicReadAccess(true);
var roleName = req.params.roleName;
var role = new Parse.Role(roleName, roleACL);
role.save().then(
ok => {
res.success(`Đã tạo thành công role : ${roleName} ! ✅`);
},
e => {
res.error(e.message);
}
);
} else {
res.error("⛔️ Tên role quá ngắn, yêu cần tối thiểu 3 ký tự ⛔️");
}
} else {
res.error("⛔️ Sai mật khẩu quản trị (masterKey) 🔑");
} //end check Masterkey
}); //end define
}; //end cloud
|
/* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Check whether an element is a finite number
isFiniteNumber = require( 'validate.io-finite' ),
// Module to be tested:
quantile = require( './../lib/array.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'array quantile', function tests() {
var validationData = require( './fixtures/array.json' ),
lambda = validationData.lambda;
it( 'should export a function', function test() {
expect( quantile ).to.be.a( 'function' );
});
it( 'should evaluate the quantile function', function test() {
var data, actual, expected, i;
data = validationData.data;
actual = new Array( data.length );
actual = quantile( actual, data, lambda );
expected = validationData.expected.map( function( d ) {
if (d === 'Inf' ) {
return Number.POSITIVE_INFINITY;
}
if ( d === '-Inf' ) {
return Number.NEGATIVE_INFINITY;
}
return d;
});
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-12 );
}
}
});
it( 'should return an empty array if provided an empty array', function test() {
assert.deepEqual( quantile( [], [], lambda ), [] );
});
it( 'should handle non-numeric values by setting the element to NaN', function test() {
var data, actual, expected;
data = [ true, null, [], {} ];
actual = new Array( data.length );
actual = quantile( actual, data, lambda );
expected = [ NaN, NaN, NaN, NaN ];
assert.deepEqual( actual, expected );
});
});
|
// JS specifically for the toolkit documentation
(function( $, window, document ) {
// Masthead
// -----------------------------------
var $window = $(window),
winTop = $window.scrollTop(),
$masthead = $('.masthead'),
$mastheadTitle = $masthead.find('.page-title'),
$pageTitle = $('.jumbotron h1'),
threshold = $pageTitle.offset().top - $masthead.outerHeight(),
fadeIn, fadeOut;
$window.scroll(function(){
winTop = $window.scrollTop();
fadeIn = -1 + ( winTop / threshold );
fadeOut = 2 - ( winTop / (threshold/2) );
// ^ OFFSET ^ FADESPEED
// Numbers further from Higher numbers increase
// zero will delay the the speed of the fade.
// opacity change.
$mastheadTitle.css( 'opacity', fadeIn );
$pageTitle.css( 'opacity', fadeOut );
});
}( window.jQuery, window, document )); |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'pagebreak', 'km', {
alt: 'បំបែកទំព័រ',
toolbar: 'បន្ថែមការបំបែកទំព័រមុនបោះពុម្ព'
} );
|
// Copyright 2016 Hewlett-Packard Development Company, L.P.
//
// 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.
//
// END OF TERMS AND CONDITIONS
const nock = require('nock');
const expect = require('chai').expect;
const encryptUtil = require('./../app/routes/auth/encrypt.es6');
const fs = require('fs');
const async = require('async');
const resources = require('../app/resources/strings.es6');
// TODO: add test for TTL expiration.
// Disable eslint to allow for Nock generated objects
/* eslint-disable quote-props*/
/* eslint-disable no-unused-expressions */
/* eslint-disable no-useless-escape */
/* eslint-disable camelcase */
process.env.HE_ISSUER = "issue";
process.env.HE_AUTH_SERVICE_PORT = 0;
process.env.HE_AUTH_NO_COLLECTOR = 1;
process.env.HE_AUDIENCE = "audience";
process.env.HE_AUTH_MOCK_AUTH = "true";
process.env.HE_AUTH_SSL_PASS = "default";
process.env.JWE_SECRETS_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.VAULT_DEV_ROOT_TOKEN_ID = "default";
process.env.HE_IDENTITY_PORTAL_ENDPOINT = "http://example.com";
process.env.HE_IDENTITY_WS_ENDPOINT = "http://example.com";
process.env.JWE_TOKEN_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.JWE_TOKEN_URL_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.JWT_TOKEN_PATH = "./test/assets/jwe_secrets_assets.pem";
process.env.JWE_TOKEN_URL_PATH_PUB = "./test/assets/jwe_secrets_pub_assets.pem";
process.env.JWT_TOKEN_PATH_PUB = "./test/assets/jwe_secrets_pub_assets.pem";
process.env.HE_AUTH_SSL_KEY = "./test/assets/key.pem";
process.env.HE_AUTH_SSL_CERT = "./test/assets/cert.pem";
if (process.env.HTTP_PROXY || process.env.http_proxy) {
process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',vault' : 'vault';
process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',vault' : 'vault';
process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',basicauth' : 'basicauth';
process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',basicauth' : 'basicauth';
process.env.NO_PROXY = process.env.NO_PROXY ? process.env.NO_PROXY + ',localhost' : 'localhost';
process.env.no_proxy = process.env.no_proxy ? process.env.no_proxy + ',localhost' : 'localhost';
}
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/init')
.reply(200, {"initialized": true}, ['Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'21',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/seal-status')
.reply(200, {
"sealed": false, "t": 1,
"n": 1,
"progress": 0,
"version": "Vault v0.6.1",
"cluster_name": "vault-cluster-8ed1001e",
"cluster_id": "48a3ee1a-14fd-be4e-3cc5-bb023c56024e"
}, [
'Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'159',
'Connection',
'close'
]);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/mounts')
.reply(200, {
"secret/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "generic secret storage",
"type": "generic"
},
"cubbyhole/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "per-token private secret storage",
"type": "cubbyhole"
},
"sys/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "system endpoints used for control, policy and debugging",
"type": "system"
},
"request_id": "93f8c930-6ddf-6165-7989-63c598c14aac",
"lease_id": "",
"renewable": false,
"lease_duration": 0,
"data": {
"cubbyhole/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "per-token private secret storage",
"type": "cubbyhole"
},
"secret/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "generic secret storage",
"type": "generic"
},
"sys/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "system endpoints used for control, policy and debugging",
"type": "system"
}
},
"wrap_info": null,
"warnings": null,
"auth": null
}, [
'Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'961',
'Connection',
'close'
]);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/sys/auth')
.reply(200, {
"token/": {
"config": {
"default_lease_ttl": 0,
"max_lease_ttl": 0
},
"description": "token based credentials",
"type": "token"
},
"request_id": "ad9b37e3-7963-3848-95b3-7915d8504202",
"lease_id": "",
"renewable": false,
"lease_duration": 0,
"data": {
"token/": {
"config": {
"default_lease_ttl": 0, "max_lease_ttl": 0
},
"description": "token based credentials",
"type": "token"
}
},
"wrap_info": null,
"warnings": null,
"auth": null
}, [
'Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 05:04:04 GMT',
'Content-Length',
'393',
'Connection',
'close'
]);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration", "auth": {"type": "basic_auth"}
},
"user_info": {
"id": "abcd"
},
"secrets": {"token": "YWRtaW46YWRtaW4="}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Tue, 01 Nov 2016 04:18:12 GMT',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/secret/abcd/integration')
.reply(200, {
"request_id": "c48cf5e1-e9c2-c16d-dfaa-847944584e20",
"lease_id": "",
"renewable": false,
"lease_duration": 2592000,
"data": {
"integration_info": {"auth": "auth", "name": "integration"},
"secrets": {"username": "admin", "password": "admin"},
"user_info": {"id": "abcd"}
},
"wrap_info": null,
"warnings": null,
"auth": null
}, ['Content-Type',
'application/json',
'Date',
'Fri, 11 Nov 2016 14:44:08 GMT',
'Content-Length',
'273',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/secret/DoesNotExists/integration')
.reply(404, {"errors": []}, ['Content-Type',
'application/json',
'Date',
'Fri, 11 Nov 2016 14:45:20 GMT',
'Content-Length',
'14',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.get('/v1/secret/abcd/DoesNotExists')
.reply(404, {"errors": []}, ['Content-Type',
'application/json',
'Date',
'Fri, 11 Nov 2016 14:45:20 GMT',
'Content-Length',
'14',
'Connection',
'close']);
nock('http://basicauth', {"encodedQueryParams": true})
.get('/success')
.reply(200, {"authenticated": true, "user": "admin"}, ['Server',
'nginx',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Content-Type',
'application/json',
'Content-Length',
'48',
'Connection',
'close',
'Access-Control-Allow-Origin',
'*',
'Access-Control-Allow-Credentials',
'true']);
nock('http://basicauth', {"encodedQueryParams": true})
.get('/failure')
.reply(401, {"authenticated": true, "user": "admin"}, ['Server',
'nginx',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Content-Type',
'application/json',
'Content-Length',
'48',
'Connection',
'close',
'Access-Control-Allow-Origin',
'*',
'Access-Control-Allow-Credentials',
'true']);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "GET"
}
}
}
},
"user_info": {
"id": "abcd"
},
"secrets": {
"token": "YWRtaW46YWRtaW4="
}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
}
}
},
"user_info": {
"id": "abcd"
},
"secrets": {
"token": "YWRtaW46YWRtaW4="
}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Connection',
'close']);
nock('http://vault:8200', {"encodedQueryParams": true})
.put('/v1/secret/abcd/integration', {
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http:\/\/idmauth\/success",
verb: "POST"
}
}
}
},
"user_info": {
"id": "abcd"
},
"secrets": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
}
})
.reply(204, "", ['Content-Type',
'application/json',
'Date',
'Sat, 12 Nov 2016 03:10:08 GMT',
'Connection',
'close']);
const authService = require('../server.es6');
const request = require('supertest')(authService.app);
/* eslint-disable no-undef */
let token = "";
let secret = "";
let secretPayload = {"username": "admin", "password": "admin"};
describe('Auth Service tests', function() {
this.timeout(20000);
before(function(done) {
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
});
it('should fail to yield token if fields are not properly set', function(done) {
request
.post('/token_urls')
.send({})
.expect(500, done);
});
it('should fail to yield token if url_props is not set', function(done) {
request
.post('/token_urls')
.send({
"user_info": {"id": "abcd"},
"integration_info": {"name": "integration", "auth": "auth"},
"bot_info": "xyz"
})
.expect(500, done);
});
it('should fail to yield token if bot_info is not set', function(done) {
request
.post('/token_urls')
.send({
"user_info": {"id": "abcd"},
"integration_info": {"name": "integration", "auth": "auth"},
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if integration_info is not set', function(done) {
request
.post('/token_urls')
.send({
"user_info": {"id": "abcd"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if user_info is not set', function(done) {
request
.post('/token_urls')
.send({
"integration_info": {"name": "integration", "auth": "auth"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if integration_info.name is not set', function(done) {
request
.post('/token_urls')
.send({
"integration_info": {"auth": "auth"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should fail to yield token if integration_info.auth is not set', function(done) {
request
.post('/token_urls')
.send({
"integration_info": {"name": "integration"},
"bot_info": "xyz",
"url_props": {"ttl": 300}
})
.expect(500, done);
});
it('should yield valid token if body is correctly built', function(done) {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {"type": "basic_auth"}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
});
it('should return an error when posting secrets without providing a token or secret', function(done) {
request
.post('/secrets')
.send({})
.expect(500, done);
});
it('should return an error when posting secrets without providing a valid token', function(done) {
request
.post('/secrets')
.send({"secrets": secret})
.expect(500, done);
});
it('should return an error when posting secrets without providing a valid secret', function(done) {
request
.post('/secrets')
.send({"secrets": {"invalid": "secret"}, "token": token})
.expect(500, done);
});
it('should store the secret given a valid token and secret', function(done) {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
it('should be able to retrieve the stored secret', function(done) {
let userID = 'abcd';
let integrationName = 'integration';
request
.get(`/secrets/${userID}/${integrationName}`)
.expect(200)
.expect(resp => {
expect(resp).to.exist;
expect(resp.body).to.exist;
expect(resp.body.secrets).to.exist;
expect(resp.body.secrets).to.be.an('object');
expect(resp.body.integration_info).to.exist;
expect(resp.body.integration_info).to.be.an('object');
expect(resp.body.integration_info.name).to.exist;
expect(resp.body.integration_info.auth).to.exist;
expect(resp.body.user_info).to.exist;
expect(resp.body.user_info).to.be.an('object');
expect(resp.body.user_info.id).to.exist;
})
.end(done);
});
it('should error out when a non-existing userID is given', function(done) {
let userID = 'DoesNotExists';
let integrationName = 'integration';
request
.get(`/secrets/${userID}/${integrationName}`)
.expect(404, done);
});
it('should error out when a non-existing integrationName is given', function(done) {
let userID = 'abcd';
let integrationName = 'DoesNotExists';
request
.get(`/secrets/${userID}/${integrationName}`)
.expect(404, done);
});
});
describe('Auth Service endpoint authentication test', function() {
it('should yield valid token with an embedded endpoint (credentials set to admin:admin)', function(done) {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
});
it('should store the secret given valid credentials', function(done) {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
});
describe('Auth Service endpoint authentication test for failure', function() {
it('should yield valid token with an embedded endpoint (credentials set to admin:newPassword)', function(done) {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/failure",
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
});
it('should not store the secret given invalid credentials', function(done) {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
it('should not store the secret if `verb` is not specified', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
url: "http://basicauth/success"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('should not store the secret if `url` is not specified', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
"endpoint": {
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('should store the secret if `endpoint` is not specified', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "basic_auth",
"params": {
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
});
});
describe('Test IDM authentication', function() {
it('Should fail if missing endpoint', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing url', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing verb', function(done) {
async.series([
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing secrets', function(done) {
request
.post('/secrets')
.send({"token": token})
.expect(500, done);
});
it('Should fail if missing user', function(done) {
async.series([
done => {
let secretPayload = {
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing username in user structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"password": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing password in user structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing tenant', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing username in tenant structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing password in tenant structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"username": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if missing NAME in tenant structure', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://basicauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should fail if an unsupported http verb is given.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "admin",
"password": "admin"
},
"tenant": {
"username": "admin",
"password": "admin"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/success",
verb: "GET"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(500, done);
});
});
it('Should successfully authenticate when payload is built correctly.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": resources.MOCK_IDM_CREDS.username,
"password": resources.MOCK_IDM_CREDS.password
},
"tenant": {
"name": resources.MOCK_IDM_CREDS.tenantName,
"username": resources.MOCK_IDM_CREDS.tenantUsername,
"password": resources.MOCK_IDM_CREDS.tenantPassword
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/success",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(201, done);
});
});
it('Should not allow access to an agent with incorrect user credentials.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": "wrong",
"password": "wrong"
},
"tenant": {
"name": resources.MOCK_IDM_CREDS.tenantName,
"username": resources.MOCK_IDM_CREDS.tenantUsername,
"password": resources.MOCK_IDM_CREDS.tenantPassword
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/failure",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
});
it('Should not allow access to an agent with incorrect tenant credentials.', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": resources.MOCK_IDM_CREDS.username,
"password": resources.MOCK_IDM_CREDS.password
},
"tenant": {
"name": resources.MOCK_IDM_CREDS.tenantName,
"username": "wrong",
"password": "wrong"
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/failure",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
});
it('Should not allow access to an agent with incorrect tenant NAME', function(done) {
async.series([
done => {
let secretPayload = {
"user": {
"username": resources.MOCK_IDM_CREDS.username,
"password": resources.MOCK_IDM_CREDS.password
},
"tenant": {
"name": "wrong",
"username": resources.MOCK_IDM_CREDS.tenantUsername,
"password": resources.MOCK_IDM_CREDS.tenantPassword
}
};
let secretsPubKey = fs.readFileSync('./test/assets/jwe_secrets_pub_assets.pem');
encryptUtil.encryptWithKey(secretsPubKey, JSON.stringify(secretPayload),
(err, encryptedSecrets) => {
if (err)
return done(err);
secret = encryptedSecrets;
done();
});
},
done => {
let payload = {
"user_info": {
"id": "abcd"
},
"integration_info": {
"name": "integration",
"auth": {
"type": "idm_auth",
"params": {
"endpoint": {
url: "http://idmauth/failure",
verb: "POST"
}
}
}
},
"bot_info": "xyz",
"url_props": {
"ttl": 300
}
};
request
.post('/token_urls')
.send(payload)
.expect(201)
.expect(res => {
expect(res.body).exists;
expect(res.body.token).exists;
expect(res.body.message).equals('token_url created');
token = res.body.token;
})
.end(err => {
if (err) {
return done(err);
}
done();
});
}
], () => {
request
.post('/secrets')
.send({"secrets": secret, "token": token})
.expect(401, done);
});
});
});
|
/*:
* @plugindesc Basic plugin for manipulating important parameters.
* @author RM CoreScript team
*
* @help
* Basic plugin for manipulating important parameters.
* There is no plugin command.
*
* Caching images improves performance but increases memory allocation.
* On mobile devices, a lot of memory allocation causes the browser to crash.
* Therefore, the upper limit of memory allocation is set with cacheLimit.
*
* If you want to regain high performance, just increase cacheLimit.
* There is no need to revert to 1.4.
*
* @param cacheLimit
* @type number
* @desc The upper limit of images' cached size (MPixel)
* @default 10
*
* @param screenWidth
* @type number
* @desc The resolution of screen width
* @default 816
*
* @param screenHeight
* @type number
* @desc The resolution of screen height
* @default 624
*
* @param changeWindowWidthTo
* @type number
* @desc If set, change window width to this value
*
* @param changeWindowHeightTo
* @type number
* @desc If set, change window height to this value
*
* @param renderingMode
* @type select
* @option canvas
* @option webgl
* @option auto
* @desc The rendering mode (canvas/webgl/auto)
* @default auto
*
* @param alwaysDash
* @type boolean
* @desc The initial value whether the player always dashes (on/off)
* @on ON
* @off OFF
* @default false
*
* @param textSpeed
* @type number
* @desc The text speed on "Show Text". The larger this parameter is, the slower text speed. (0: show all texts at once)
* @default 1
*
* @param autoSaveFileId
* @type number
* @desc The file number to auto save when "Transfer Player" (0: off)
* @default 0
*
* @param errorMessage
* @type string
* @desc The message when error occurred
* @default Error occurred. Please ask to the creator of this game.
*
* @param showErrorDetail
* @type boolean
* @desc Show where the error is caused and stack trace when error
* @default true
*
* @param enableProgressBar
* @type boolean
* @desc Show progress bar when it takes a long time to load resources
* @default true
*
* @param maxRenderingFps
* @type number
* @desc The maximum value of rendering frame per seconds (0: unlimited)
* @default 0
*/
/*:ja
* @plugindesc 基本的なパラメーターを設定するプラグインです。
* @author RM CoreScript team
*
* @help
* 基本的なパラメーターを設定するプラグインです。
* このプラグインにはプラグインコマンドはありません。
*
* 画像をキャッシュするとパフォーマンスは向上しますが、その分メモリ確保も増大します。
* モバイルデバイスでは、たくさんのメモリ確保はブラウザをクラッシュさせます。
* そこで、メモリ確保の上限を「画像キャッシュ上限値」で設定しています。
*
* もし高いパフォーマンスを取り戻したければ、ただ画像キャッシュ上限値を増加させればよいです。
* 1.4に戻す必要はありません。
*
* @param cacheLimit
* @type number
* @text 画像キャッシュ上限値
* @desc 画像のメモリへのキャッシュの上限値 (MPix)
* @default 10
*
* @param screenWidth
* @type number
* @text ゲーム画面の幅
* @default 816
*
* @param screenHeight
* @type number
* @text ゲーム画面の高さ
* @default 624
*
* @param changeWindowWidthTo
* @type number
* @text ウィンドウの幅
* @desc 値が設定されなかった場合、ゲーム画面の幅と同じ
*
* @param changeWindowHeightTo
* @type number
* @text ウィンドウの高さ
* @desc 値が設定されなかった場合、ゲーム画面の高さと同じ
*
* @param renderingMode
* @type select
* @option canvas
* @option webgl
* @option auto
* @text レンダリングモード
* @default auto
*
* @param alwaysDash
* @type boolean
* @text 「常時ダッシュ」の初期値
* @on ON
* @off OFF
* @default false
*
* @param textSpeed
* @type number
* @text 「文章の表示」のスピード
* @desc 数字が大きいほど文章の表示スピードが遅くなります (0を指定した場合は一度に全文を表示します)
* @default 1
*
* @param autoSaveFileId
* @type number
* @text オートセーブ番号
* @desc 「場所移動」の際に指定したファイル番号にオートセーブします(0を指定した場合はオートセーブしません)
* @default 0
*
* @param errorMessage
* @type string
* @text エラーメッセージ
* @desc エラー時にプレイヤーに向けて表示するメッセージです
* @default エラーが発生しました。ゲームの作者にご連絡ください。
*
* @param showErrorDetail
* @type boolean
* @text エラー詳細表示
* @desc ONにすると、エラー時にエラーを発生させたイベントの情報とスタックトレースを表示します
* @default true
*
* @param enableProgressBar
* @type boolean
* @text ロード進捗バー有効化
* @desc ONにすると、読み込みに時間がかかっている時にロード進捗バーを表示します
* @default true
*
* @param maxRenderingFps
* @type number
* @text 描画FPS上限値
* @desc 描画FPSの上限値を設定します (0を指定した場合は制限なし)
* @default 0
*/
(function() {
'use strict';
function isNumber(str) {
return !!str && !isNaN(str);
}
function toNumber(str, def) {
return isNumber(str) ? +str : def;
}
var parameters = PluginManager.parameters('Community_Basic');
var cacheLimit = toNumber(parameters['cacheLimit'], 10);
var screenWidth = toNumber(parameters['screenWidth'], 816);
var screenHeight = toNumber(parameters['screenHeight'], 624);
var renderingMode = parameters['renderingMode'].toLowerCase();
var alwaysDash = (parameters['alwaysDash'] === 'true') ||(parameters['alwaysDash'] === 'on');
var textSpeed = toNumber(parameters['textSpeed'], 1);
var windowWidthTo = toNumber(parameters['changeWindowWidthTo'], 0);
var windowHeightTo = toNumber(parameters['changeWindowHeightTo'], 0);
var maxRenderingFps = toNumber(parameters['maxRenderingFps'], 0);
var autoSaveFileId = toNumber(parameters['autoSaveFileId'], 0);
var errorMessage = parameters['errorMessage'];
var showErrorDetail = parameters['showErrorDetail'] === 'true';
var enableProgressBar = parameters['enableProgressBar'] === 'true';
var windowWidth;
var windowHeight;
if(windowWidthTo){
windowWidth = windowWidthTo;
}else if(screenWidth !== SceneManager._screenWidth){
windowWidth = screenWidth;
}
if(windowHeightTo){
windowHeight = windowHeightTo;
}else if(screenHeight !== SceneManager._screenHeight){
windowHeight = screenHeight;
}
ImageCache.limit = cacheLimit * 1000 * 1000;
SceneManager._screenWidth = screenWidth;
SceneManager._screenHeight = screenHeight;
SceneManager._boxWidth = screenWidth;
SceneManager._boxHeight = screenHeight;
SceneManager.preferableRendererType = function() {
if (Utils.isOptionValid('canvas')) {
return 'canvas';
} else if (Utils.isOptionValid('webgl')) {
return 'webgl';
} else if (renderingMode === 'canvas') {
return 'canvas';
} else if (renderingMode === 'webgl') {
return 'webgl';
} else {
return 'auto';
}
};
var _ConfigManager_applyData = ConfigManager.applyData;
ConfigManager.applyData = function(config) {
_ConfigManager_applyData.apply(this, arguments);
if (config['alwaysDash'] === undefined) {
this.alwaysDash = alwaysDash;
}
};
var _Window_Message_clearFlags = Window_Message.prototype.clearFlags;
Window_Message.prototype.clearFlags = function(textState) {
_Window_Message_clearFlags.apply(this, arguments);
this._textSpeed = textSpeed - 1;
};
var _SceneManager_initNwjs = SceneManager.initNwjs;
SceneManager.initNwjs = function() {
_SceneManager_initNwjs.apply(this, arguments);
if (Utils.isNwjs() && windowWidth && windowHeight) {
var dw = windowWidth - window.innerWidth;
var dh = windowHeight - window.innerHeight;
window.moveBy(-dw / 2, -dh / 2);
window.resizeBy(dw, dh);
}
};
if (maxRenderingFps) {
var currentTime = Date.now();
var deltaTime = 1000 / maxRenderingFps;
var accumulator = 0;
var _SceneManager_renderScene = SceneManager.renderScene;
SceneManager.renderScene = function() {
var newTime = Date.now();
accumulator += newTime - currentTime;
currentTime = newTime;
if (accumulator >= deltaTime) {
accumulator -= deltaTime;
_SceneManager_renderScene.apply(this, arguments);
}
};
}
DataManager.setAutoSaveFileId(autoSaveFileId);
Graphics.setErrorMessage(errorMessage);
Graphics.setShowErrorDetail(showErrorDetail);
Graphics.setProgressEnabled(enableProgressBar);
})();
|
pinion.on("create.message.systemMessagesList", function(data) {
data.element.settings.data = pinion.messages.reverse();
});
pinion.backend.renderer.SystemMessageRenderer = (function($) {
var constr,
modules = pinion.php.modules;
// public API -- constructor
constr = function(settings, backend) {
var data = settings.data;
this.$element = $("<div class='pinion-backend-renderer-SystemMessageRenderer'></div>")
.append("<div class='pinion-colorfield-left'></div>")
.append("<div class='pinion-colorfield-right'></div>")
.addClass("pinion-"+data.type);
// ICON
if(data.module) {
$("<div class='pinion-moduleIcon'><img src='"+modules[data.module].icon+"' /></div>").appendTo(this.$element);
}
// MESSAGE
$("<div class='pinion-textWrapper'><div class='pinion-systemMessage'>"+data.text+"</div></div>").appendTo(this.$element);
}
// public API -- prototype
constr.prototype = {
constructor: pinion.backend.renderer.SystemMessageRenderer
}
return constr;
}(jQuery));
|
function solve(args){
var i,
array = [];
for(i = 0; i < args.length; i++){
array[i] = +args[i];
}
var sum = 0,
count = 0,
min = array[0],
max = array[0],
avg = 0;
for(i = 0; i < array.length; i++){
sum += array[i];
count++;
if(array[i] < min){
min = array[i];
}
if(array[i] > max){
max = array[i];
}
}
avg = sum / count;
console.log('min=' + Number(min).toFixed(2));
console.log('max=' + Number(max).toFixed(2));
console.log('sum=' + Number(sum).toFixed(2));
console.log('avg=' + Number(avg).toFixed(2));
}
solve(['2', '5', '1']); |
define(["globals",
"ember",
"core_ext",
"ember-i18n",
"ember-bootstrap",
"select2",
"moment",
"mediaelement",
"jquery.highlight-search-results",
"jquery.autogrow-textarea",
"jquery.anchorlinks",
"jquery.hashtags",
"jquery.expander",
"bootstrap.file-input"], function(globals, Ember){
if (!globals.app) {
var options = {}
if (typeof DEBUG !== 'undefined') {
Ember.LOG_BINDINGS = true;
options = {
// log when Ember generates a controller or a route from a generic class
LOG_ACTIVE_GENERATION: true,
// log when Ember looks up a template or a view
LOG_VIEW_LOOKUPS: true,
LOG_TRANSITIONS: true
// LOG_TRANSITIONS_INTERNAL: true
}
}
App = Ember.Application.create(options);
// We need to delay initialization to load the rest of the application
App.deferReadiness()
globals.app = App
}
return globals.app;
});
|
import React from 'react';
import PropTypes from 'prop-types';
import './Todo.css';
const ARCHIVE_SHORTCUT_KEY_CODE = 65; // 'a'
const onArchiveShortcutPress = (handler, event) => {
if(event.keyCode === ARCHIVE_SHORTCUT_KEY_CODE) handler(event);
};
const Todo = ({text, completed, onClick, onDeleteClick}) => (
<li className={completed ? 'TodoList_Item-completed' : 'TodoList_Item'}>
<span
className={completed ? 'TodoList_Text-completed' : 'TodoList_Text'}
onClick={onClick}
onKeyDown={onArchiveShortcutPress.bind(null, onClick)}
role='button'
tabIndex='0'
>
{text}
</span>
<button className='Todo_Delete' onClick={onDeleteClick} style={{color: 'red'}}>
<svg width="26" height="26" viewBox="0 0 1024 1024">
<g style={{fill: '#b3b3b3'}}>
<path d="M640.35,91.169H536.971V23.991C536.971,10.469,526.064,0,512.543,0c-1.312,0-2.187,0.438-2.614,0.875
C509.491,0.438,508.616,0,508.179,0H265.212h-1.74h-1.75c-13.521,0-23.99,10.469-23.99,23.991v67.179H133.916
c-29.667,0-52.783,23.116-52.783,52.783v38.387v47.981h45.803v491.6c0,29.668,22.679,52.346,52.346,52.346h415.703
c29.667,0,52.782-22.678,52.782-52.346v-491.6h45.366v-47.981v-38.387C693.133,114.286,670.008,91.169,640.35,91.169z
M285.713,47.981h202.84v43.188h-202.84V47.981z M599.349,721.922c0,3.061-1.312,4.363-4.364,4.363H179.282
c-3.052,0-4.364-1.303-4.364-4.363V230.32h424.431V721.922z M644.715,182.339H129.551v-38.387c0-3.053,1.312-4.802,4.364-4.802
H640.35c3.053,0,4.365,1.749,4.365,4.802V182.339z"/>
<rect x="475.031" y="286.593" width="48.418" height="396.942"/>
<rect x="363.361" y="286.593" width="48.418" height="396.942"/>
<rect x="251.69" y="286.593" width="48.418" height="396.942"/>
</g>
</svg>
</button>
</li>
);
Todo.propTypes = {
text: PropTypes.string.isRequired,
completed: PropTypes.bool.isRequired,
onClick: PropTypes.func.isRequired,
onDeleteClick: PropTypes.func.isRequired
};
export default Todo;
|
// Generated on 2015-05-19 using generator-angular-fullstack 2.0.13
'use strict';
module.exports = function (grunt) {
var localConfig;
try {
localConfig = require('./server/config/local.env');
} catch(e) {
localConfig = {};
}
// Load grunt tasks automatically, when needed
require('jit-grunt')(grunt, {
express: 'grunt-express-server',
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn',
protractor: 'grunt-protractor-runner',
injector: 'grunt-asset-injector',
buildcontrol: 'grunt-build-control'
});
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
pkg: grunt.file.readJSON('package.json'),
yeoman: {
// configurable paths
client: require('./bower.json').appPath || 'client',
dist: 'dist'
},
express: {
options: {
port: process.env.PORT || 9000
},
dev: {
options: {
script: 'server/app.js',
debug: true
}
},
prod: {
options: {
script: 'dist/server/app.js'
}
}
},
open: {
server: {
url: 'http://localhost:<%= express.options.port %>'
}
},
watch: {
injectJS: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.js',
'!<%= yeoman.client %>/{app,components}/**/*.spec.js',
'!<%= yeoman.client %>/{app,components}/**/*.mock.js',
'!<%= yeoman.client %>/app/app.js'],
tasks: ['injector:scripts']
},
injectCss: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.css'
],
tasks: ['injector:css']
},
mochaTest: {
files: ['server/**/*.spec.js'],
tasks: ['env:test', 'mochaTest']
},
jsTest: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.spec.js',
'<%= yeoman.client %>/{app,components}/**/*.mock.js'
],
tasks: ['newer:jshint:all', 'karma']
},
injectSass: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'],
tasks: ['injector:sass']
},
sass: {
files: [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}'],
tasks: ['sass', 'autoprefixer']
},
jade: {
files: [
'<%= yeoman.client %>/{app,components}/*',
'<%= yeoman.client %>/{app,components}/**/*.jade'],
tasks: ['jade']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
files: [
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.css',
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.html',
'{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js',
'!{.tmp,<%= yeoman.client %>}{app,components}/**/*.spec.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js',
'<%= yeoman.client %>/assets/images/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}'
],
options: {
livereload: true
}
},
express: {
files: [
'server/**/*.{js,json}'
],
tasks: ['express:dev', 'wait'],
options: {
livereload: true,
nospawn: true //Without this option specified express won't be reloaded
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '<%= yeoman.client %>/.jshintrc',
reporter: require('jshint-stylish')
},
server: {
options: {
jshintrc: 'server/.jshintrc'
},
src: [
'server/**/*.js',
'!server/**/*.spec.js'
]
},
serverTest: {
options: {
jshintrc: 'server/.jshintrc-spec'
},
src: ['server/**/*.spec.js']
},
all: [
'<%= yeoman.client %>/{app,components}/**/*.js',
'!<%= yeoman.client %>/{app,components}/**/*.spec.js',
'!<%= yeoman.client %>/{app,components}/**/*.mock.js'
],
test: {
src: [
'<%= yeoman.client %>/{app,components}/**/*.spec.js',
'<%= yeoman.client %>/{app,components}/**/*.mock.js'
]
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*',
'!<%= yeoman.dist %>/.openshift',
'!<%= yeoman.dist %>/Procfile'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/',
src: '{,*/}*.css',
dest: '.tmp/'
}]
}
},
// Debugging with node inspector
'node-inspector': {
custom: {
options: {
'web-host': 'localhost'
}
}
},
// Use nodemon to run server in debug mode with an initial breakpoint
nodemon: {
debug: {
script: 'server/app.js',
options: {
nodeArgs: ['--debug-brk'],
env: {
PORT: process.env.PORT || 9000
},
callback: function (nodemon) {
nodemon.on('log', function (event) {
console.log(event.colour);
});
// opens browser on initial server start
nodemon.on('config:update', function () {
setTimeout(function () {
require('open')('http://localhost:8080/debug?port=5858');
}, 500);
});
}
}
}
},
// Automatically inject Bower components into the app
wiredep: {
target: {
src: '<%= yeoman.client %>/index.html',
ignorePath: '<%= yeoman.client %>/',
exclude: [/bootstrap-sass-official/, /bootstrap.js/, '/json3/', '/es5-shim/', /bootstrap.css/, /font-awesome.css/ ]
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= yeoman.dist %>/public/{,*/}*.js',
'<%= yeoman.dist %>/public/{,*/}*.css',
'<%= yeoman.dist %>/public/assets/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/public/assets/fonts/*'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: ['<%= yeoman.client %>/index.html'],
options: {
dest: '<%= yeoman.dist %>/public'
}
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/public/{,*/}*.html'],
css: ['<%= yeoman.dist %>/public/{,*/}*.css'],
js: ['<%= yeoman.dist %>/public/{,*/}*.js'],
options: {
assetsDirs: [
'<%= yeoman.dist %>/public',
'<%= yeoman.dist %>/public/assets/images'
],
// This is so we update image references in our ng-templates
patterns: {
js: [
[/(assets\/images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
]
}
}
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.client %>/assets/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/public/assets/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.client %>/assets/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/public/assets/images'
}]
}
},
// Allow the use of non-minsafe AngularJS files. Automatically makes it
// minsafe compatible so Uglify does not destroy the ng references
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat',
src: '*/**.js',
dest: '.tmp/concat'
}]
}
},
// Package all the html partials into a single javascript payload
ngtemplates: {
options: {
// This should be the name of your apps angular module
module: 'joggingApp',
htmlmin: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true
},
usemin: 'app/app.js'
},
main: {
cwd: '<%= yeoman.client %>',
src: ['{app,components}/**/*.html'],
dest: '.tmp/templates.js'
},
tmp: {
cwd: '.tmp',
src: ['{app,components}/**/*.html'],
dest: '.tmp/tmp-templates.js'
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/public/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.client %>',
dest: '<%= yeoman.dist %>/public',
src: [
'*.{ico,png,txt}',
'.htaccess',
'bower_components/**/*',
'assets/images/{,*/}*.{webp}',
'assets/fonts/**/*',
'index.html'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/public/assets/images',
src: ['generated/*']
}, {
expand: true,
dest: '<%= yeoman.dist %>',
src: [
'package.json',
'server/**/*'
]
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.client %>',
dest: '.tmp/',
src: ['{app,components}/**/*.css']
}
},
buildcontrol: {
options: {
dir: 'dist',
commit: true,
push: true,
connectCommits: false,
message: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%'
},
heroku: {
options: {
remote: 'heroku',
branch: 'master'
}
},
openshift: {
options: {
remote: 'openshift',
branch: 'master'
}
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'jade',
'sass',
],
test: [
'jade',
'sass',
],
debug: {
tasks: [
'nodemon',
'node-inspector'
],
options: {
logConcurrentOutput: true
}
},
dist: [
'jade',
'sass',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true
}
},
mochaTest: {
options: {
reporter: 'spec'
},
src: ['server/**/*.spec.js']
},
protractor: {
options: {
configFile: 'protractor.conf.js'
},
chrome: {
options: {
args: {
browser: 'chrome'
}
}
}
},
env: {
test: {
NODE_ENV: 'test'
},
prod: {
NODE_ENV: 'production'
},
all: localConfig
},
// Compiles Jade to html
jade: {
compile: {
options: {
data: {
debug: false
}
},
files: [{
expand: true,
cwd: '<%= yeoman.client %>',
src: [
'{app,components}/**/*.jade'
],
dest: '.tmp',
ext: '.html'
}]
}
},
// Compiles Sass to CSS
sass: {
server: {
options: {
loadPath: [
'<%= yeoman.client %>/bower_components',
'<%= yeoman.client %>/app',
'<%= yeoman.client %>/components'
],
compass: false
},
files: {
'.tmp/app/app.css' : '<%= yeoman.client %>/app/app.scss'
}
}
},
injector: {
options: {
},
// Inject application script files into index.html (doesn't include bower)
scripts: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/', '');
filePath = filePath.replace('/.tmp/', '');
return '<script src="' + filePath + '"></script>';
},
starttag: '<!-- injector:js -->',
endtag: '<!-- endinjector -->'
},
files: {
'<%= yeoman.client %>/index.html': [
['{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js',
'!{.tmp,<%= yeoman.client %>}/app/app.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.spec.js',
'!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js']
]
}
},
// Inject component scss into app.scss
sass: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/app/', '');
filePath = filePath.replace('/client/components/', '');
return '@import \'' + filePath + '\';';
},
starttag: '// injector',
endtag: '// endinjector'
},
files: {
'<%= yeoman.client %>/app/app.scss': [
'<%= yeoman.client %>/{app,components}/**/*.{scss,sass}',
'!<%= yeoman.client %>/app/app.{scss,sass}'
]
}
},
// Inject component css into index.html
css: {
options: {
transform: function(filePath) {
filePath = filePath.replace('/client/', '');
filePath = filePath.replace('/.tmp/', '');
return '<link rel="stylesheet" href="' + filePath + '">';
},
starttag: '<!-- injector:css -->',
endtag: '<!-- endinjector -->'
},
files: {
'<%= yeoman.client %>/index.html': [
'<%= yeoman.client %>/{app,components}/**/*.css'
]
}
}
},
});
// Used for delaying livereload until after server has restarted
grunt.registerTask('wait', function () {
grunt.log.ok('Waiting for server reload...');
var done = this.async();
setTimeout(function () {
grunt.log.writeln('Done waiting!');
done();
}, 1500);
});
grunt.registerTask('express-keepalive', 'Keep grunt running', function() {
this.async();
});
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'env:all', 'env:prod', 'express:prod', 'wait', 'open', 'express-keepalive']);
}
if (target === 'debug') {
return grunt.task.run([
'clean:server',
'env:all',
'injector:sass',
'concurrent:server',
'injector',
'wiredep',
'autoprefixer',
'concurrent:debug'
]);
}
grunt.task.run([
'clean:server',
'env:all',
'injector:sass',
'concurrent:server',
'injector',
'wiredep',
'autoprefixer',
'express:dev',
'wait',
'open',
'watch'
]);
});
grunt.registerTask('server', function () {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve']);
});
grunt.registerTask('test', function(target) {
if (target === 'server') {
return grunt.task.run([
'env:all',
'env:test',
'mochaTest'
]);
}
else if (target === 'client') {
return grunt.task.run([
'clean:server',
'env:all',
'injector:sass',
'concurrent:test',
'injector',
'autoprefixer',
'karma'
]);
}
else if (target === 'e2e') {
return grunt.task.run([
'clean:server',
'env:all',
'env:test',
'injector:sass',
'concurrent:test',
'injector',
'wiredep',
'autoprefixer',
'express:dev',
'protractor'
]);
}
else grunt.task.run([
'test:server',
'test:client'
]);
});
grunt.registerTask('build', [
'clean:dist',
'injector:sass',
'concurrent:dist',
'injector',
'wiredep',
'useminPrepare',
'autoprefixer',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'rev',
'usemin'
]);
grunt.registerTask('default', [
//'newer:jshint',
'test',
'build'
]);
};
|
module.exports = function(grunt){
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
ctags: {
files: ['ctags'],
tasks: ['shell:ctags'],
options: {
nospawn: false,
},
}
},
shell: {
ctags: {
command: [
'cp ctags $HOME/.ctags',
'cp taglist.vim $HOME/.vim/bundle/taglist/plugin/taglist.vim',
'ctags -f - --format=2 --excmd=pattern --fields=nks '+
'--sort=no --language-force=css --css-types=cis test.css'
].join('&&')
},
release: {
command: 'cp ctags $HOME/.ctags',
},
options:{
stdout:true
}
},
});
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['watch']);
grunt.registerTask('release', ['shell:release']);
};
|
var TreeNode = require('../dist/treenode').TreeNode;
describe("TreeNode Class", function() {
var tree;
var data = [
{
name: 'I am ROOT',
status: 'initial'
},
{
name: 'Node 1',
status: 'initial'
},
{
name: 'Node 2',
status: 'initial'
},
{
name: 'Node 3',
status: 'initial'
}
];
beforeEach(function() {
tree = new TreeNode(data[0]);
});
it("should allow a child to be added and return as a TreeNode object", function() {
var leaf = tree.addChild(data[1]);
expect(leaf.data.name).toEqual(data[1].name);
});
it("should return its root", function() {
expect(tree.root().data.name).toEqual(data[0].name);
var leaf = tree.addChild(data[1]);
expect(leaf.root().data.name).toEqual(data[0].name)
});
it("should find data", function() {
tree.addChild(data[1]);
tree.addChild(data[2]);
expect(tree.find(data[1]).data).toEqual(data[1]);
expect(tree.find(data[2]).data).toEqual(data[2]);
expect(tree.find(data[3])).toBe(null);
});
it("should find leaves", function() {
tree.addChild(data[1]);
var intermediateNode = tree.addChild(data[2]);
intermediateNode.addChild(data[3]);
var leaves = tree.leaves();
// we've added 3 nodes, but only two are leaves
expect(leaves.length).toBe(2);
});
it("should execute forEach() callback on all child nodes", function() {
var intermediateNode = tree.addChild(data[1]);
var childNode = intermediateNode.addChild(data[2]);
var grandchildNode = childNode.addChild(data[3]);
intermediateNode.forEach(function(node) {
node.data.status = 'updated';
});
expect(tree.root().data.status).toBe('initial');
expect(intermediateNode.data.status).toBe('updated');
expect(childNode.data.status).toBe('updated');
expect(grandchildNode.data.status).toBe('updated');
});
it("should return the number of children", function() {
expect(tree.numChildren()).toBe(0);
tree.addChild(data[1]);
expect(tree.numChildren()).toBe(1);
var intermediateNode = tree.addChild(data[2]);
expect(tree.numChildren()).toBe(2);
intermediateNode.addChild(data[3]);
expect(tree.numChildren()).toBe(2);
expect(intermediateNode.numChildren()).toBe(1);
});
}); |
/*
* Copyright (c) 2015-2017 Steven Soloff
*
* This is free software: you can redistribute it and/or modify it under the
* terms of the MIT License (https://opensource.org/licenses/MIT).
* This software comes with ABSOLUTELY NO WARRANTY.
*/
'use strict'
const _ = require('underscore')
const diceExpressionResult = require('./dice-expression-result')
const diceExpressionTypeIds = require('./dice-expression-type-ids')
/**
* Provides methods for creating dice expressions.
*
* @module dice-expression
*/
module.exports = {
/**
* Creates a new addition expression.
*
* @param {module:dice-expression~Expression!} augendExpression - The
* augend expression.
* @param {module:dice-expression~Expression!} addendExpression - The
* addend expression.
*
* @returns {module:dice-expression~AdditionExpression!} The new addition
* expression.
*
* @throws {Error} If `augendExpression` is not defined or if
* `addendExpression` is not defined.
*/
forAddition (augendExpression, addendExpression) {
if (!augendExpression) {
throw new Error('augend expression is not defined')
} else if (!addendExpression) {
throw new Error('addend expression is not defined')
}
/**
* An expression that adds two expressions.
*
* @namespace AdditionExpression
*/
return {
/**
* The addend expression.
*
* @memberOf module:dice-expression~AdditionExpression
*
* @type {module:dice-expression~Expression!}
*/
addendExpression,
/**
* The augend expression.
*
* @memberOf module:dice-expression~AdditionExpression
*
* @type {module:dice-expression~Expression!}
*/
augendExpression,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~AdditionExpression
*
* @returns {module:dice-expression-result~AdditionExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forAddition(
augendExpression.evaluate(),
addendExpression.evaluate()
)
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~AdditionExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.ADDITION
}
},
/**
* Creates a new array expression.
*
* @param {module:dice-expression~Expression[]!} expressions - The
* expressions that are the array elements.
*
* @returns {module:dice-expression~ArrayExpression!} The new array
* expression.
*
* @throws {Error} If `expressions` is not an array.
*/
forArray (expressions) {
if (!_.isArray(expressions)) {
throw new Error('expressions is not an array')
}
/**
* An expression that acts as an array of expressions.
*
* @namespace ArrayExpression
*/
return {
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~ArrayExpression
*
* @returns {module:dice-expression-result~ArrayExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forArray(_.invoke(expressions, 'evaluate'))
},
/**
* The expressions that are the array elements.
*
* @memberOf module:dice-expression~ArrayExpression
*
* @type {module:dice-expression~Expression[]!}
*/
expressions,
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~ArrayExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.ARRAY
}
},
/**
* Creates a new constant expression.
*
* @param {Number!} constant - The constant.
*
* @returns {module:dice-expression~ConstantExpression!} The new constant
* expression.
*
* @throws {Error} If `constant` is not a number.
*/
forConstant (constant) {
if (!_.isNumber(constant)) {
throw new Error('constant is not a number')
}
/**
* An expression that represents a constant value.
*
* @namespace ConstantExpression
*/
return {
/**
* The constant associated with the expression.
*
* @memberOf module:dice-expression~ConstantExpression
*
* @type {Number!}
*/
constant,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~ConstantExpression
*
* @returns {module:dice-expression-result~ConstantExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forConstant(constant)
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~ConstantExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.CONSTANT
}
},
/**
* Creates a new die expression.
*
* @param {module:dice-bag~Die!} die - The die.
*
* @returns {module:dice-expression~DieExpression!} The new die expression.
*
* @throws {Error} If `die` is not defined.
*/
forDie (die) {
if (!die) {
throw new Error('die is not defined')
}
/**
* An expression that represents a die.
*
* @namespace DieExpression
*/
return {
/**
* The die associated with the expression.
*
* @memberOf module:dice-expression~DieExpression
*
* @type {module:dice-bag~Die!}
*/
die,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~DieExpression
*
* @returns {module:dice-expression-result~DieExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forDie(die)
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~DieExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.DIE
}
},
/**
* Creates a new division expression.
*
* @param {module:dice-expression~Expression!} dividendExpression - The
* dividend expression.
* @param {module:dice-expression~Expression!} divisorExpression - The
* divisor expression.
*
* @returns {module:dice-expression~DivisionExpression!} The new division
* expression.
*
* @throws {Error} If `dividendExpression` is not defined or if
* `divisorExpression` is not defined.
*/
forDivision (dividendExpression, divisorExpression) {
if (!dividendExpression) {
throw new Error('dividend expression is not defined')
} else if (!divisorExpression) {
throw new Error('divisor expression is not defined')
}
/**
* An expression that divides two expressions.
*
* @namespace DivisionExpression
*/
return {
/**
* The dividend expression.
*
* @memberOf module:dice-expression~DivisionExpression
*
* @type {module:dice-expression~Expression!}
*/
dividendExpression,
/**
* The divisor expression.
*
* @memberOf module:dice-expression~DivisionExpression
*
* @type {module:dice-expression~Expression!}
*/
divisorExpression,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~DivisionExpression
*
* @returns {module:dice-expression-result~DivisionExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forDivision(
dividendExpression.evaluate(),
divisorExpression.evaluate()
)
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~DivisionExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.DIVISION
}
},
/**
* Creates a new function call expression.
*
* @param {String!} name - The function name.
* @param {Function!} func - The function.
* @param {module:dice-expression~Expression[]!} argumentListExpressions -
* The expressions that represent the arguments to the function call.
*
* @returns {module:dice-expression~FunctionCallExpression!} The new
* function call expression.
*
* @throws {Error} If `name` is not a string, or if `func` is not a
* function, or if `argumentListExpressions` is not an array.
*/
forFunctionCall (name, func, argumentListExpressions) {
if (!_.isString(name)) {
throw new Error('function name is not a string')
} else if (!_.isFunction(func)) {
throw new Error('function is not a function')
} else if (!_.isArray(argumentListExpressions)) {
throw new Error('function argument list expressions is not an array')
}
/**
* An expression that calls a function.
*
* @namespace FunctionCallExpression
*/
return {
/**
* The expressions that represent the arguments to the function
* call.
*
* @memberOf module:dice-expression~FunctionCallExpression
*
* @type {module:dice-expression~Expression[]!}
*/
argumentListExpressions,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~FunctionCallExpression
*
* @returns {module:dice-expression-result~FunctionCallExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
const argumentListExpressionResults = _.invoke(argumentListExpressions, 'evaluate')
const argumentList = _.pluck(argumentListExpressionResults, 'value')
const returnValue = func.apply(null, argumentList)
return diceExpressionResult.forFunctionCall(returnValue, name, argumentListExpressionResults)
},
/**
* The function name.
*
* @memberOf module:dice-expression~FunctionCallExpression
*
* @type {String!}
*/
name,
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~FunctionCallExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.FUNCTION_CALL
}
},
/**
* Creates a new group expression.
*
* @param {module:dice-expression~Expression!} childExpression - The
* expression that is grouped.
*
* @returns {module:dice-expression~GroupExpression!} The new group
* expression.
*
* @throws {Error} If `childExpression` is not defined.
*/
forGroup (childExpression) {
if (!childExpression) {
throw new Error('child expression is not defined')
}
/**
* An expression that groups another expression.
*
* @namespace GroupExpression
*/
return {
/**
* The expression that is grouped.
*
* @memberOf module:dice-expression~GroupExpression
*
* @type {module:dice-expression~Expression!}
*/
childExpression,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~GroupExpression
*
* @returns {module:dice-expression-result~GroupExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forGroup(childExpression.evaluate())
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~GroupExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.GROUP
}
},
/**
* Creates a new modulo expression.
*
* @param {module:dice-expression~Expression!} dividendExpression - The
* dividend expression.
* @param {module:dice-expression~Expression!} divisorExpression - The
* divisor expression.
*
* @returns {module:dice-expression~ModuloExpression!} The new modulo
* expression.
*
* @throws {Error} If `dividendExpression` is not defined or if
* `divisorExpression` is not defined.
*/
forModulo (dividendExpression, divisorExpression) {
if (!dividendExpression) {
throw new Error('dividend expression is not defined')
} else if (!divisorExpression) {
throw new Error('divisor expression is not defined')
}
/**
* An expression that modulos two expressions.
*
* @namespace ModuloExpression
*/
return {
/**
* The dividend expression.
*
* @memberOf module:dice-expression~ModuloExpression
*
* @type {module:dice-expression~Expression!}
*/
dividendExpression,
/**
* The divisor expression.
*
* @memberOf module:dice-expression~ModuloExpression
*
* @type {module:dice-expression~Expression!}
*/
divisorExpression,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~ModuloExpression
*
* @returns {module:dice-expression-result~ModuloExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forModulo(
dividendExpression.evaluate(),
divisorExpression.evaluate()
)
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~ModuloExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.MODULO
}
},
/**
* Creates a new multiplication expression.
*
* @param {module:dice-expression~Expression!} multiplicandExpression - The
* multiplicand expression.
* @param {module:dice-expression~Expression!} multiplierExpression - The
* multiplier expression.
*
* @returns {module:dice-expression~MultiplicationExpression!} The new
* multiplication expression.
*
* @throws {Error} If `multiplicandExpression` is not defined or if
* `multiplierExpression` is not defined.
*/
forMultiplication (multiplicandExpression, multiplierExpression) {
if (!multiplicandExpression) {
throw new Error('multiplicand expression is not defined')
} else if (!multiplierExpression) {
throw new Error('multiplier expression is not defined')
}
/**
* An expression that multiplies two expressions.
*
* @namespace MultiplicationExpression
*/
return {
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~MultiplicationExpression
*
* @returns {module:dice-expression-result~MultiplicationExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forMultiplication(
multiplicandExpression.evaluate(),
multiplierExpression.evaluate()
)
},
/**
* The multiplicand expression.
*
* @memberOf module:dice-expression~MultiplicationExpression
*
* @type {module:dice-expression~Expression!}
*/
multiplicandExpression,
/**
* The multiplier expression.
*
* @memberOf module:dice-expression~MultiplicationExpression
*
* @type {module:dice-expression~Expression!}
*/
multiplierExpression,
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~MultiplicationExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.MULTIPLICATION
}
},
/**
* Creates a new negative expression.
*
* @param {module:dice-expression~Expression!} childExpression - The
* expression to be negated.
*
* @returns {module:dice-expression~NegativeExpression!} The new negative
* expression.
*
* @throws {Error} If `childExpression` is not defined.
*/
forNegative (childExpression) {
if (!childExpression) {
throw new Error('child expression is not defined')
}
/**
* An expression that negates another expression.
*
* @namespace NegativeExpression
*/
return {
/**
* The expression to be negated.
*
* @memberOf module:dice-expression~NegativeExpression
*
* @type {module:dice-expression~Expression!}
*/
childExpression,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~NegativeExpression
*
* @returns {module:dice-expression-result~NegativeExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forNegative(childExpression.evaluate())
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~NegativeExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.NEGATIVE
}
},
/**
* Creates a new positive expression.
*
* @param {module:dice-expression~Expression!} childExpression - The
* expression to be applied.
*
* @returns {module:dice-expression~PositiveExpression!} The new positive
* expression.
*
* @throws {Error} If `childExpression` is not defined.
*/
forPositive (childExpression) {
if (!childExpression) {
throw new Error('child expression is not defined')
}
/**
* An expression that applies another expression.
*
* @namespace PositiveExpression
*/
return {
/**
* The expression to be applied.
*
* @memberOf module:dice-expression~PositiveExpression
*
* @type {module:dice-expression~Expression!}
*/
childExpression,
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~PositiveExpression
*
* @returns {module:dice-expression-result~PositiveExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forPositive(childExpression.evaluate())
},
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~PositiveExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.POSITIVE
}
},
/**
* Creates a new subtraction expression.
*
* @param {module:dice-expression~Expression!} minuendExpression - The
* minuend expression.
* @param {module:dice-expression~Expression!} subtrahendExpression - The
* subtrahend expression.
*
* @returns {module:dice-expression~SubtractionExpression!} The new
* subtraction expression.
*
* @throws {Error} If `minuendExpression` is not defined or if
* `subtrahendExpression` is not defined.
*/
forSubtraction (minuendExpression, subtrahendExpression) {
if (!minuendExpression) {
throw new Error('minuend expression is not defined')
} else if (!subtrahendExpression) {
throw new Error('subtrahend expression is not defined')
}
/**
* An expression that subtracts two expressions.
*
* @namespace SubtractionExpression
*/
return {
/**
* Evaluates the expression.
*
* @memberOf module:dice-expression~SubtractionExpression
*
* @returns {module:dice-expression-result~SubtractionExpressionResult!}
* The result of evaluating the expression.
*/
evaluate () {
return diceExpressionResult.forSubtraction(
minuendExpression.evaluate(),
subtrahendExpression.evaluate()
)
},
/**
* The minuend expression.
*
* @memberOf module:dice-expression~SubtractionExpression
*
* @type {module:dice-expression~Expression!}
*/
minuendExpression,
/**
* The subtrahend expression.
*
* @memberOf module:dice-expression~SubtractionExpression
*
* @type {module:dice-expression~Expression!}
*/
subtrahendExpression,
/**
* The expression type identifier.
*
* @memberOf module:dice-expression~SubtractionExpression
*
* @type {String!}
*/
typeId: diceExpressionTypeIds.SUBTRACTION
}
}
}
|
// inheritientence!!
function Pet() {
this.animal = "";
this.name="";
this.setAnimal = function(newAnimal){
this.animal = newAnimal;
}
this.setName = function(newName){
this.name = newName;
}
}
var myCat = new Pet();
myCat.setAnimal = "cat";
myCat.setName = "Sylvester";
function Dog(){
this.breed ="";
this.setBread = function(newBreed){
this.breed = newBreed;
}
}
Dog.prototype = new Pet();
// Now I can access the propertites and methods of Pet in addition to Dog
var myDog = new Dog();
myDog.setName("Alan");
myDog.setBreed("Greyhound");
alert(myDog.name + "is a " myDog.breed);
|
export const u1F443 = {"viewBox":"0 0 2600 2760.837","children":[{"name":"path","attribs":{"d":"M2043 2036q-41 85-119.5 119.5T1784 2190q-25 0-46-3.5t-39-8.5l-35-8q-16-4-30-4-47 0-130.5 53t-204.5 53q-70 0-119-16t-86-37l-64-37q-29-16-63-16-17 0-33 4l-35 8q-17 5-38 8.5t-46 3.5q-58 0-134.5-31.5t-121-118.5-44.5-195q0-66 28-141.5t74-155.5l67-117q27-46 50.5-107t48.5-135l55-160h-1q59-171 108-265.5T1094.5 603t204.5-66q98 0 200.5 63t160 174 131.5 343 124 314l18 29q55 86 103 191t48 197q0 103-41 188zm-128.5-319q-32.5-78-100.5-186l-17-30q-30-52-54.5-114.5T1692 1249l-56-163q-59-172-96-243.5T1438.5 725 1316 675l-16-1-16 1q-54 4-117.5 46t-103 112T963 1085l-55 163q-26 75-50.5 138T803 1501l-18 30-44 76q-37 63-63 127t-26 112q0 94 39.5 149t123.5 55q17 0 34-4l34-7 38-7q19-3 42-3 90 0 168 53t168 53 169-53 164-53q22 0 38.5 2t47.5 8l33 7q16 4 33 4 54 0 91-23t54.5-74.5T1947 1848t-32.5-131z"},"children":[]}]}; |
//= require fluent/admin/admin.js |
'use strict'
import ObjectUtils from 'es-common-core/object-utils';
import Asset from 'rpgmv-asset-manager-core/datas/asset';
import AssetFileDeserializer from 'rpgmv-asset-manager-core/datas/asset-file-deserializer';
/**
* Asset Manager MV
* アセットデシリアライザ
*
* @since 2016/01/03
* @author RaTTiE
*/
export default class AssetDeserializer {
/**
* オブジェクトのデシリアライズを行う。
*
* @param data デシリアライズに使用するデータ。
* @return デシリアライズしたインスタンス。
*/
static deserialize(data) {
if (data == null) return null;
var asset = new Asset();
var files = [];
for (var i = 0; i < data.files.length; i++) {
files.push(AssetFileDeserializer.deserialize(data.files[i]));
}
ObjectUtils.setFields(asset, {
name: data.name,
type: data.type,
files: files,
using: data.using,
checked: data.checked,
selected: data.selected
});
return asset;
}
}
|
// Use require('arpjs') if youre running this example elsewhere.
var arp = require('../')
// arp.setInterface('en0');
arp.send({
'op': 'request',
'src_ip': '10.105.50.100',
'dst_ip': '10.105.50.1',
'src_mac': '8f:3f:20:33:54:44',
'dst_mac': 'ff:ff:ff:ff:ff:11'
})
|
class AddAktModalController{
constructor(API, $uibModal, $state,$timeout){
'ngInject';
let vm=this;
vm.API=API;
vm.program=vm.resolve.program;
vm.programs=vm.resolve.programs;
vm.data={
program:vm.program.id,
title:null,
date:new Date()
};
vm.dateOptions = {
altInputFormats: ['yyyy-MM-dd', 'dd.MM.yyyy'],
formatDay: 'dd',
formatMonth: 'MM',
formatYear: 'yyyy',
minDate: new Date(),
startingDay: 1
};
vm.date = {
opened: false
};
vm.openCalendar=()=>{
vm.date.opened=true;
};
vm.close=()=>{
this.modalInstance.dismiss('cancel');
};
vm.add=()=>{
let calendar = this.API.all('akt');
calendar.post({
program:vm.data.program,
title:vm.data.title,
date:moment(vm.data.date).format('YYYY-MM-DD'),
}).then((response) => {
vm.success=true;
$timeout( ()=>{
$state.reload();
}, 300);
$timeout(()=> {
vm.close();
}, 500);
},
(response) => {
vm.message=response.data.uniqemessage;
vm.errors=response.data.errors;
});
}
//
}
$onInit(){
}
}
export const AddAktModalComponent = {
templateUrl: './views/app/components/addAktModal/addAktModal.component.html',
controller: AddAktModalController,
controllerAs: 'vm',
bindings: {
modalInstance: "<",
resolve: "<"
}
}
|
// A DOM operation helper. Append an Element to a parent
export default function append(parent, ...children) {
// Always select the first item of a list, similarly to jQuery
if (Array.isArray(parent)) {
parent = parent[0]
}
children.forEach(parent.appendChild, parent)
return parent
}
|
///
// Dependencies
///
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';
import isString from 'lodash/isString';
import * as types from './types';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import ExpanderButton from '../elements/ExpanderButton';
import Icon from '../elements/Icon';
import Scrollable from '../elements/Scrollable';
import * as actions from './actions';
import * as formsActions from '../forms/actions';
///
// View
///
class OverviewPanelItemView extends Component {
///
// Construction / Hooks
///
constructor(props) {
super(props);
this.onToggle = this.onToggle.bind(this);
this.onSelect = this.onSelect.bind(this);
this.onShowForm = this.onShowForm.bind(this);
}
///
// Event handling
///
onToggle() {
this.props.toggleItem(this.props.name);
}
onSelect() {
this.props.selectItem(this.props.name);
}
onShowForm() {
this.props.clearForm(this.props.name);
this.props.showForm(this.props.name);
}
///
// Rendering
///
renderIcon(icon) {
if(! icon) return '';
if(isString(icon)) {
icon = (
<Icon name={icon} />
);
}
return (
<div className="item-icon">
{icon}
</div>
);
}
render() {
const isSelected = this.props.selected === this.props.name;
const isExpanded = isSelected || this.props.overview.getIn(
['panels', this.props.name, 'isExpanded']
);
const itemClassName = classNames('overview-panel-item', {
selected: isSelected,
expanded: isExpanded,
});
return (
<div className={itemClassName}>
<div className="item-header">
<ExpanderButton
expanded={isExpanded}
disabled={isSelected}
onClick={this.onToggle}
/>
<h4
className="item-title"
onClick={this.onSelect}
>
{this.renderIcon(this.props.icon)}
{this.props.title}
</h4>
<Button
className="add-button"
onClick={this.onShowForm}
>
<Icon name="plus" />
</Button>
</div>
<Panel
collapsible expanded={isExpanded}
className="item-content"
>
{this.props.notifications}
<Scrollable>
{this.props.children}
</Scrollable>
</Panel>
</div>
);
}
}
OverviewPanelItemView.propTypes = {
name: PropTypes.string.isRequired,
icon: PropTypes.node,
title: PropTypes.node.isRequired,
selected: PropTypes.string,
notifications: PropTypes.node,
overview: types.Overview.isRequired,
toggleItem: PropTypes.func.isRequired,
selectItem: PropTypes.func.isRequired,
clearForm: PropTypes.func.isRequired,
showForm: PropTypes.func.isRequired,
children: PropTypes.node,
};
export { OverviewPanelItemView };
///
// Container
///
function mapStateToProps(state) {
return {
selected: state.getIn(['overview', 'root', 'selected']),
overview: state.get('overview'),
};
}
function mapDispatchToProps(dispatch) {
return {
toggleItem: (name) => dispatch(actions.toggleItem(name)),
selectItem: (name) => dispatch(actions.selectItem(name)),
clearForm: (name) => dispatch(formsActions.clearForm(name)),
showForm: (name) => dispatch(formsActions.showForm(name)),
};
}
const connector = connect(
mapStateToProps,
mapDispatchToProps
);
export default connector(OverviewPanelItemView);
|
/* global moment, angular */
function TimePickerCtrl($scope, $mdDialog, time, autoSwitch, ampm, confirmText, cancelText, $mdMedia) {
var self = this;
this.VIEW_HOURS = 1;
this.VIEW_MINUTES = 2;
this.currentView = this.VIEW_HOURS;
this.time = moment(time);
this.autoSwitch = !!autoSwitch;
this.ampm = !!ampm;
this.confirmText= confirmText ? confirmText :"OK";
this.cancelText= cancelText ? cancelText :"Cancel";
this.hoursFormat = self.ampm ? "h" : "H";
this.minutesFormat = "mm";
this.clockHours = parseInt(this.time.format(this.hoursFormat));
this.clockMinutes = parseInt(this.time.format(this.minutesFormat));
$scope.$mdMedia = $mdMedia;
this.switchView = function() {
self.currentView = self.currentView == self.VIEW_HOURS ? self.VIEW_MINUTES : self.VIEW_HOURS;
};
this.setAM = function() {
if(self.time.hours() >= 12)
self.time.hour(self.time.hour() - 12);
};
this.setPM = function() {
if(self.time.hours() < 12)
self.time.hour(self.time.hour() + 12);
};
this.cancel = function() {
$mdDialog.cancel();
};
this.confirm = function() {
$mdDialog.hide(this.time.toDate());
};
}
function ClockCtrl($scope) {
var TYPE_HOURS = "hours";
var TYPE_MINUTES = "minutes";
var self = this;
this.STEP_DEG = 360 / 12;
this.steps = [];
this.CLOCK_TYPES = {
"hours": {
range: self.ampm ? 12 : 24,
},
"minutes": {
range: 60,
}
}
this.getPointerStyle = function() {
var divider = 1;
switch(self.type) {
case TYPE_HOURS:
divider = self.ampm ? 12 : 24;
break;
case TYPE_MINUTES:
divider = 60;
break;
}
var degrees = Math.round(self.selected * (360 / divider)) - 180;
return {
"-webkit-transform": "rotate(" + degrees + "deg)",
"-ms-transform": "rotate(" + degrees + "deg)",
"transform": "rotate(" + degrees + "deg)"
}
};
this.setTimeByDeg = function(deg) {
deg = deg >= 360 ? 0 : deg;
var divider = 0;
switch(self.type) {
case TYPE_HOURS:
divider = self.ampm ? 12 : 24;
break;
case TYPE_MINUTES:
divider = 60;
break;
}
self.setTime(
Math.round(divider / 360 * deg)
);
};
this.setTime = function(time, type) {
this.selected = time;
switch(self.type) {
case TYPE_HOURS:
if(self.ampm && self.time.format("A") == "PM") time += 12;
this.time.hours(time);
break;
case TYPE_MINUTES:
if(time > 59) time -= 60;
this.time.minutes(time);
break;
}
};
this.init = function() {
self.type = self.type || "hours";
switch(self.type) {
case TYPE_HOURS:
var f = self.ampm ? 1 : 2;
var t = self.ampm ? 12 : 23;
for(var i = f; i <= t; i+=f)
self.steps.push(i);
if (!self.ampm) self.steps.push(0);
self.selected = self.time.hours() || 0;
if(self.ampm && self.selected > 12) self.selected -= 12;
break;
case TYPE_MINUTES:
for(var i = 5; i <= 55; i+=5)
self.steps.push(i);
self.steps.push(0);
self.selected = self.time.minutes() || 0;
break;
}
};
this.init();
}
module.directive("mdpClock", ["$animate", "$timeout", function($animate, $timeout) {
return {
restrict: 'E',
bindToController: {
'type': '@?',
'time': '=',
'autoSwitch': '=?',
'ampm': '=?'
},
replace: true,
template: '<div class="mdp-clock">' +
'<div class="mdp-clock-container">' +
'<md-toolbar class="mdp-clock-center md-primary"></md-toolbar>' +
'<md-toolbar ng-style="clock.getPointerStyle()" class="mdp-pointer md-primary">' +
'<span class="mdp-clock-selected md-button md-raised md-primary"></span>' +
'</md-toolbar>' +
'<md-button ng-class="{ \'md-primary\': clock.selected == step }" class="md-icon-button md-raised mdp-clock-deg{{ ::(clock.STEP_DEG * ($index + 1)) }}" ng-repeat="step in clock.steps" ng-click="clock.setTime(step)">{{ step }}</md-button>' +
'</div>' +
'</div>',
controller: ["$scope", ClockCtrl],
controllerAs: "clock",
link: function(scope, element, attrs, ctrl) {
var pointer = angular.element(element[0].querySelector(".mdp-pointer")),
timepickerCtrl = scope.$parent.timepicker;
var onEvent = function(event) {
var containerCoords = event.currentTarget.getClientRects()[0];
var x = ((event.currentTarget.offsetWidth / 2) - (event.pageX - containerCoords.left)),
y = ((event.pageY - containerCoords.top) - (event.currentTarget.offsetHeight / 2));
var deg = Math.round((Math.atan2(x, y) * (180 / Math.PI)));
$timeout(function() {
ctrl.setTimeByDeg(deg + 180);
if(ctrl.autoSwitch && ["mouseup", "click"].indexOf(event.type) !== -1 && timepickerCtrl) timepickerCtrl.switchView();
});
};
element.on("mousedown", function() {
element.on("mousemove", onEvent);
});
element.on("mouseup", function(e) {
element.off("mousemove");
});
element.on("click", onEvent);
scope.$on("$destroy", function() {
element.off("click", onEvent);
element.off("mousemove", onEvent);
});
}
}
}]);
module.provider("$mdpTimePicker", function() {
this.$get = ["$mdDialog", function($mdDialog) {
var timePicker = function(time, options) {
if(!angular.isDate(time)) time = Date.now();
if (!angular.isObject(options)) options = {};
return $mdDialog.show({
controller: ['$scope', '$mdDialog', 'time', 'autoSwitch', 'ampm', 'confirmText', 'cancelText', '$mdMedia', TimePickerCtrl],
controllerAs: 'timepicker',
clickOutsideToClose: true,
template: '<md-dialog aria-label="" class="mdp-timepicker" ng-class="{ \'portrait\': !$mdMedia(\'gt-xs\') }">' +
'<md-dialog-content layout-gt-xs="row" layout-wrap>' +
'<md-toolbar layout-gt-xs="column" layout-xs="row" layout-align="center center" flex class="mdp-timepicker-time md-hue-1 md-primary">' +
'<div class="mdp-timepicker-selected-time">' +
'<span ng-class="{ \'active\': timepicker.currentView == timepicker.VIEW_HOURS }" ng-click="timepicker.currentView = timepicker.VIEW_HOURS">{{ timepicker.time.format(timepicker.hoursFormat) }}</span>:' +
'<span ng-class="{ \'active\': timepicker.currentView == timepicker.VIEW_MINUTES }" ng-click="timepicker.currentView = timepicker.VIEW_MINUTES">{{ timepicker.time.format(timepicker.minutesFormat) }}</span>' +
'</div>' +
'<div layout="column" ng-show="timepicker.ampm" class="mdp-timepicker-selected-ampm">' +
'<span ng-click="timepicker.setAM()" ng-class="{ \'active\': timepicker.time.hours() < 12 }">AM</span>' +
'<span ng-click="timepicker.setPM()" ng-class="{ \'active\': timepicker.time.hours() >= 12 }">PM</span>' +
'</div>' +
'</md-toolbar>' +
'<div>' +
'<div class="mdp-clock-switch-container" ng-switch="timepicker.currentView" layout layout-align="center center">' +
'<mdp-clock class="mdp-animation-zoom" ampm="timepicker.ampm" auto-switch="timepicker.autoSwitch" time="timepicker.time" type="hours" ng-switch-when="1"></mdp-clock>' +
'<mdp-clock class="mdp-animation-zoom" ampm="timepicker.ampm" auto-switch="timepicker.autoSwitch" time="timepicker.time" type="minutes" ng-switch-when="2"></mdp-clock>' +
'</div>' +
'<md-dialog-actions layout="row">' +
'<span flex></span>' +
'<md-button ng-click="timepicker.cancel()" aria-label="{{timepicker.cancelText}}">{{timepicker.cancelText}}</md-button>' +
'<md-button ng-click="timepicker.confirm()" class="md-primary" aria-label="{{timepicker.confirmText}}">{{timepicker.confirmText}}</md-button>' +
'</md-dialog-actions>' +
'</div>' +
'</md-dialog-content>' +
'</md-dialog>',
targetEvent: options.targetEvent,
locals: {
time: time,
autoSwitch: options.autoSwitch,
ampm: options.ampm,
confirmText: options.confirmText,
cancelText: options.cancelText
},
skipHide: true
});
};
return timePicker;
}];
});
module.directive("mdpTimePicker", ["$mdpTimePicker", "$timeout", function($mdpTimePicker, $timeout) {
return {
restrict: 'E',
require: 'ngModel',
transclude: true,
template: function(element, attrs) {
var noFloat = angular.isDefined(attrs.mdpNoFloat),
placeholder = angular.isDefined(attrs.mdpPlaceholder) ? attrs.mdpPlaceholder : "",
openOnClick = angular.isDefined(attrs.mdpOpenOnClick) ? true : false;
return '<div layout layout-align="start start">' +
'<md-button class="md-icon-button" ng-click="showPicker($event)"' + (angular.isDefined(attrs.mdpDisabled) ? ' ng-disabled="disabled"' : '') + '>' +
'<md-icon md-svg-icon="mdp-access-time"></md-icon>' +
'</md-button>' +
'<md-input-container' + (noFloat ? ' md-no-float' : '') + ' md-is-error="isError()">' +
'<input type="{{ ::type }}"' + (angular.isDefined(attrs.mdpDisabled) ? ' ng-disabled="disabled"' : '') + ' aria-label="' + placeholder + '" placeholder="' + placeholder + '"' + (openOnClick ? ' ng-click="showPicker($event)" ' : '') + ' />' +
'</md-input-container>' +
'</div>';
},
scope: {
"timeFormat": "@mdpFormat",
"placeholder": "@mdpPlaceholder",
"autoSwitch": "=?mdpAutoSwitch",
"disabled": "=?mdpDisabled",
"ampm": "=?mdpAmpm",
"confirmText": "@mdpConfirmText",
"cancelText": "@mdpCancelText"
},
link: function(scope, element, attrs, ngModel, $transclude) {
var inputElement = angular.element(element[0].querySelector('input')),
inputContainer = angular.element(element[0].querySelector('md-input-container')),
inputContainerCtrl = inputContainer.controller("mdInputContainer");
$transclude(function(clone) {
inputContainer.append(clone);
});
var messages = angular.element(inputContainer[0].querySelector("[ng-messages]"));
scope.type = scope.timeFormat ? "text" : "time"
scope.timeFormat = scope.timeFormat || "HH:mm";
scope.autoSwitch = scope.autoSwitch || false;
scope.confirmText= scope.confirmText ? scope.confirmText :"OK";
scope.cancelText= scope.cancelText ? scope.cancelText :"Cancel";
scope.$watch(function() { return ngModel.$error }, function(newValue, oldValue) {
inputContainerCtrl.setInvalid(!ngModel.$pristine && !!Object.keys(ngModel.$error).length);
}, true);
// update input element if model has changed
ngModel.$formatters.unshift(function(value) {
var time = angular.isDate(value) && moment(value);
if(time && time.isValid())
updateInputElement(time.format(scope.timeFormat));
else
updateInputElement(null);
});
ngModel.$validators.format = function(modelValue, viewValue) {
return !viewValue || angular.isDate(viewValue) || moment(viewValue, scope.timeFormat, true).isValid();
};
ngModel.$validators.required = function(modelValue, viewValue) {
return angular.isUndefined(attrs.required) || !ngModel.$isEmpty(modelValue) || !ngModel.$isEmpty(viewValue);
};
ngModel.$parsers.unshift(function(value) {
var parsed = moment(value, scope.timeFormat, true);
if(parsed.isValid()) {
if(angular.isDate(ngModel.$modelValue)) {
var originalModel = moment(ngModel.$modelValue);
originalModel.minutes(parsed.minutes());
originalModel.hours(parsed.hours());
originalModel.seconds(parsed.seconds());
parsed = originalModel;
}
return parsed.toDate();
} else
return null;
});
// update input element value
function updateInputElement(value) {
inputElement[0].value = value;
inputContainerCtrl.setHasValue(!ngModel.$isEmpty(value));
}
function updateTime(time) {
var value = moment(time, angular.isDate(time) ? null : scope.timeFormat, true),
strValue = value.format(scope.timeFormat);
if(value.isValid()) {
updateInputElement(strValue);
ngModel.$setViewValue(strValue);
} else {
updateInputElement(time);
ngModel.$setViewValue(time);
}
if(!ngModel.$pristine &&
messages.hasClass("md-auto-hide") &&
inputContainer.hasClass("md-input-invalid")) messages.removeClass("md-auto-hide");
ngModel.$render();
}
scope.showPicker = function(ev) {
$mdpTimePicker(ngModel.$modelValue, {
targetEvent: ev,
autoSwitch: scope.autoSwitch,
ampm: scope.ampm,
confirmText: scope.confirmText,
cancelText: scope.cancelText
}).then(function(time) {
updateTime(time, true);
});
};
function onInputElementEvents(event) {
if(event.target.value !== ngModel.$viewVaue)
updateTime(event.target.value);
}
inputElement.on("reset input blur", onInputElementEvents);
scope.$on("$destroy", function() {
inputElement.off("reset input blur", onInputElementEvents);
})
}
};
}]);
module.directive("mdpTimePicker", ["$mdpTimePicker", "$timeout", function($mdpTimePicker, $timeout) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
"timeFormat": "@mdpFormat",
"autoSwitch": "=?mdpAutoSwitch",
"ampm": "=?mdpAmpm",
"confirmText": "@mdpConfirmText",
"cancelText": "@mdpCancelText"
},
link: function(scope, element, attrs, ngModel, $transclude) {
scope.format = scope.format || "HH:mm";
scope.confirmText= scope.confirmText;
scope.cancelText= scope.cancelText;
function showPicker(ev) {
$mdpTimePicker(ngModel.$modelValue, {
targetEvent: ev,
autoSwitch: scope.autoSwitch,
ampm: scope.ampm,
confirmText: scope.confirmText,
cancelText: scope.cancelText
}).then(function(time) {
ngModel.$setViewValue(moment(time).format(scope.format));
ngModel.$render();
});
};
element.on("click", showPicker);
scope.$on("$destroy", function() {
element.off("click", showPicker);
});
}
}
}]);
|
"use strict";
// Mail Body Parser
var logger = require('./logger');
var Header = require('./mailheader').Header;
var utils = require('./utils');
var events = require('events');
var util = require('util');
var Iconv = require('./mailheader').Iconv;
var attstr = require('./attachment_stream');
var buf_siz = 65536;
function Body (header, options) {
this.header = header || new Header();
this.header_lines = [];
this.is_html = false;
this.options = options || {};
this.bodytext = '';
this.body_text_encoded = '';
this.children = []; // if multipart
this.state = 'start';
this.buf = new Buffer(buf_siz);
this.buf_fill = 0;
}
util.inherits(Body, events.EventEmitter);
exports.Body = Body;
Body.prototype.parse_more = function (line) {
return this["parse_" + this.state](line);
}
Body.prototype.parse_child = function (line) {
// check for MIME boundary
if (line.substr(0, (this.boundary.length + 2)) === ('--' + this.boundary)) {
line = this.children[this.children.length -1].parse_end(line);
if (this.children[this.children.length -1].state === 'attachment') {
var child = this.children[this.children.length - 1];
if (child.buf_fill > 0) {
// see below for why we create a new buffer here.
var to_emit = new Buffer(child.buf_fill);
child.buf.copy(to_emit, 0, 0, child.buf_fill);
child.attachment_stream.emit_data(to_emit);
}
child.attachment_stream.emit('end');
}
if (line.substr(this.boundary.length + 2, 2) === '--') {
// end
this.state = 'end';
}
else {
var bod = new Body(new Header(), this.options);
this.listeners('attachment_start').forEach(function (cb) { bod.on('attachment_start', cb) });
this.listeners('attachment_data' ).forEach(function (cb) { bod.on('attachment_data', cb) });
this.listeners('attachment_end' ).forEach(function (cb) { bod.on('attachment_end', cb) });
this.children.push(bod);
bod.state = 'headers';
}
return line;
}
// Pass data into last child
return this.children[this.children.length - 1].parse_more(line);
}
Body.prototype.parse_headers = function (line) {
if (/^\s*$/.test(line)) {
// end of headers
this.header.parse(this.header_lines);
delete this.header_lines;
this.state = 'start';
}
else {
this.header_lines.push(line);
}
return line;
}
Body.prototype.parse_start = function (line) {
var ct = this.header.get_decoded('content-type') || 'text/plain';
var enc = this.header.get_decoded('content-transfer-encoding') || '8bit';
var cd = this.header.get_decoded('content-disposition') || '';
if (/text\/html/i.test(ct)) {
this.is_html = true;
}
enc = enc.toLowerCase().split("\n").pop().trim();
if (!enc.match(/^base64|quoted-printable|[78]bit$/i)) {
logger.logerror("Invalid CTE on email: " + enc + ", using 8bit");
enc = '8bit';
}
enc = enc.replace(/^quoted-printable$/i, 'qp');
this.decode_function = this["decode_" + enc];
if (!this.decode_function) {
logger.logerror("No decode function found for: " + enc);
this.decode_function = this.decode_8bit;
}
this.ct = ct;
if (/^(?:text|message)\//i.test(ct) && !/^attachment/i.test(cd) ) {
this.state = 'body';
}
else if (/^multipart\//i.test(ct)) {
var match = ct.match(/boundary\s*=\s*["']?([^"';]+)["']?/i);
this.boundary = match ? match[1] : '';
this.state = 'multipart_preamble';
}
else {
var match = cd.match(/name\s*=\s*["']?([^'";]+)["']?/i);
if (!match) {
match = ct.match(/name\s*=\s*["']?([^'";]+)["']?/i);
}
var filename = match ? match[1] : '';
this.attachment_stream = attstr.createStream();
this.emit('attachment_start', ct, filename, this, this.attachment_stream);
this.buf_fill = 0;
this.state = 'attachment';
}
return this["parse_" + this.state](line);
}
function _get_html_insert_position (buf) {
// TODO: consider re-writing this to go backwards from the end
for (var i=0,l=buf.length; i<l; i++) {
if (buf[i] === 60 && buf[i+1] === 47) { // found: "</"
if ( (buf[i+2] === 98 || buf[i+2] === 66) && // "b" or "B"
(buf[i+3] === 111 || buf[i+3] === 79) && // "o" or "O"
(buf[i+4] === 100 || buf[i+4] === 68) && // "d" or "D"
(buf[i+5] === 121 || buf[i+5] === 89) && // "y" or "Y"
buf[i+6] === 62)
{
// matched </body>
return i;
}
if ( (buf[i+2] === 104 || buf[i+2] === 72) && // "h" or "H"
(buf[i+3] === 116 || buf[i+3] === 84) && // "t" or "T"
(buf[i+4] === 109 || buf[i+4] === 77) && // "m" or "M"
(buf[i+5] === 108 || buf[i+5] === 76) && // "l" or "L"
buf[i+6] === 62)
{
// matched </html>
return i;
}
}
}
return buf.length - 1; // default is at the end
}
Body.prototype.parse_end = function (line) {
if (!line) {
line = '';
}
// ignore these lines - but we could store somewhere I guess.
if (this.body_text_encoded.length && this.bodytext.length === 0) {
var buf = this.decode_function(this.body_text_encoded);
var ct = this.header.get_decoded('content-type') || 'text/plain';
var enc = 'UTF-8';
var matches = /\bcharset\s*=\s*(?:\"|3D|')?([\w_\-]*)(?:\"|3D|')?/.exec(ct);
if (matches) {
enc = matches[1];
}
this.body_encoding = enc;
if (this.options.banner && /^text\//i.test(ct)) {
// up until this point we've returned '' for line, so now we insert
// the banner and return the whole lot as one line, re-encoded using
// whatever encoding scheme we had to use to decode it in the first
// place.
// First we convert the banner to the same encoding as the body
var banner_str = this.options.banner[this.is_html ? 1 : 0];
var banner_buf = null;
if (Iconv) {
try {
var converter = new Iconv("UTF-8", enc + "//IGNORE");
banner_buf = converter.convert(banner_str);
}
catch (err) {
logger.logerror("iconv conversion of banner to " + enc + " failed: " + err);
}
}
if (!banner_buf) {
banner_buf = new Buffer(banner_str);
}
// Allocate a new buffer: (6 or 1 is <p>...</p> vs \n...\n - correct that if you change those!)
var new_buf = new Buffer(buf.length + banner_buf.length + (this.is_html ? 6 : 1));
// Now we find where to insert it and combine it with the original buf:
if (this.is_html) {
var insert_pos = _get_html_insert_position(buf);
// copy start of buf into new_buf
buf.copy(new_buf, 0, 0, insert_pos);
// add in <p>
new_buf[insert_pos++] = 60;
new_buf[insert_pos++] = 80;
new_buf[insert_pos++] = 62;
// copy all of banner into new_buf
banner_buf.copy(new_buf, insert_pos);
new_buf[banner_buf.length + insert_pos++] = 60;
new_buf[banner_buf.length + insert_pos++] = 47;
new_buf[banner_buf.length + insert_pos++] = 80;
new_buf[banner_buf.length + insert_pos++] = 62;
// copy remainder of buf into new_buf, if there is buf remaining
if (buf.length > (insert_pos - 6)) {
buf.copy(new_buf, insert_pos + banner_buf.length, insert_pos - 7);
}
}
else {
buf.copy(new_buf);
new_buf[buf.length] = 10; // \n
banner_buf.copy(new_buf, buf.length + 1);
new_buf[buf.length + banner_buf.length + 1] = 10; // \n
}
// Now convert back to base_64 or QP if required:
if (this.decode_function === this.decode_qp) {
line = utils.encode_qp(new_buf.toString("binary")) + "\n" + line;
}
else if (this.decode_function === this.decode_base64) {
line = new_buf.toString("base64").replace(/(.{1,76})/g, "$1\n") + line;
}
else {
line = new_buf.toString("binary") + line; // "binary" is deprecated, lets hope this works...
}
}
// Now convert the buffer to UTF-8 to store in this.bodytext
if (Iconv) {
if (/UTF-?8/i.test(enc)) {
this.bodytext = buf.toString();
}
else {
try {
var converter = new Iconv(enc, "UTF-8");
this.bodytext = converter.convert(buf).toString();
}
catch (err) {
logger.logerror("iconv conversion from " + enc + " to UTF-8 failed: " + err);
this.body_encoding = 'broken//' + enc;
this.bodytext = buf.toString();
}
}
}
else {
this.body_encoding = 'no_iconv';
this.bodytext = buf.toString();
}
// delete this.body_text_encoded;
}
return line;
}
Body.prototype.parse_body = function (line) {
this.body_text_encoded += line;
if (this.options.banner)
return '';
return line;
}
Body.prototype.parse_multipart_preamble = function (line) {
if (this.boundary) {
if (line.substr(0, (this.boundary.length + 2)) === ('--' + this.boundary)) {
if (line.substr(this.boundary.length + 2, 2) === '--') {
// end
}
else {
// next section
var bod = new Body(new Header(), this.options);
this.listeners('attachment_start').forEach(function (cb) { bod.on('attachment_start', cb) });
this.children.push(bod);
bod.state = 'headers';
this.state = 'child';
}
return line;
}
}
this.body_text_encoded += line;
return line;
}
Body.prototype.parse_attachment = function (line) {
if (this.boundary) {
if (line.substr(0, (this.boundary.length + 2)) === ('--' + this.boundary)) {
if (line.substr(this.boundary.length + 2, 2) === '--') {
// end
}
else {
// next section
this.state = 'headers';
}
return line;
}
}
var buf = this.decode_function(line);
if ((buf.length + this.buf_fill) > buf_siz) {
// now we have to create a new buffer, because if we write this out
// using async code, it will get overwritten under us. Creating a new
// buffer eliminates that problem (at the expense of a malloc and a
// memcpy())
var to_emit = new Buffer(this.buf_fill);
this.buf.copy(to_emit, 0, 0, this.buf_fill);
this.attachment_stream.emit_data(to_emit);
if (buf.length > buf_siz) {
// this is an unusual case - the base64/whatever data is larger
// than our buffer size, so we just emit it and reset the counter.
this.attachment_stream.emit_data(buf);
this.buf_fill = 0;
}
else {
buf.copy(this.buf);
this.buf_fill = buf.length;
}
}
else {
buf.copy(this.buf, this.buf_fill);
this.buf_fill += buf.length;
}
return line;
}
Body.prototype.decode_qp = utils.decode_qp;
Body.prototype.decode_base64 = function (line) {
return new Buffer(line, "base64");
}
Body.prototype.decode_8bit = function (line) {
return new Buffer(line);
}
Body.prototype.decode_7bit = Body.prototype.decode_8bit;
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M19.5 3.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2v20l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5zM19 19.09H5V4.91h14v14.18zM6 15h12v2H6zm0-4h12v2H6zm0-4h12v2H6z"
}), 'ReceiptOutlined'); |
'use strict';
/* App Module */
var granuleApp = angular.module('granuleApp', [ 'ngRoute', 'angularBasicAuth', 'granuleControllers', 'granuleServices']);
granuleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
when('/activity', {
templateUrl: 'partials/activity-list.html',
controller: 'ActivityListCtrl'
}).
when('/activity/:activityId', {
templateUrl: 'partials/activity-detail.html',
controller: 'ActivityDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
}]); |
import * as lamb from "../..";
import { nonFunctions, wannabeEmptyArrays } from "../../__tests__/commons";
describe("count / countBy", function () {
var getCity = lamb.getKey("city");
var persons = [
{ name: "Jane", surname: "Doe", age: 12, city: "New York" },
{ name: "John", surname: "Doe", age: 40, city: "New York" },
{ name: "Mario", surname: "Rossi", age: 18, city: "Rome" },
{ name: "Paolo", surname: "Bianchi", age: 15 }
];
var personsCityCount = {
"New York": 2,
Rome: 1,
undefined: 1
};
var personsAgeGroupCount = {
under20: 3,
over20: 1
};
var splitByAgeGroup = function (person, idx, list) {
expect(list).toBe(persons);
expect(persons[idx]).toBe(person);
return person.age > 20 ? "over20" : "under20";
};
it("should count the occurences of the key generated by the provided iteratee", function () {
expect(lamb.count(persons, getCity)).toEqual(personsCityCount);
expect(lamb.countBy(getCity)(persons)).toEqual(personsCityCount);
expect(lamb.count(persons, splitByAgeGroup)).toEqual(personsAgeGroupCount);
expect(lamb.countBy(splitByAgeGroup)(persons)).toEqual(personsAgeGroupCount);
});
it("should work with array-like objects", function () {
var result = {
h: 1, e: 1, l: 3, o: 2, " ": 1, w: 1, r: 1, d: 1
};
expect(lamb.count("hello world", lamb.identity)).toEqual(result);
expect(lamb.countBy(lamb.identity)("hello world")).toEqual(result);
});
it("should throw an exception if the iteratee isn't a function", function () {
nonFunctions.forEach(function (value) {
expect(function () { lamb.count(persons, value); }).toThrow();
expect(function () { lamb.countBy(value)(persons); }).toThrow();
});
expect(function () { lamb.count(persons); }).toThrow();
expect(function () { lamb.countBy()(persons); }).toThrow();
});
it("should consider deleted or unassigned indexes in sparse arrays as `undefined` values", function () {
var arr = [1, , 3, void 0, 5]; // eslint-disable-line no-sparse-arrays
var result = { false: 3, true: 2 };
expect(lamb.count(arr, lamb.isUndefined)).toEqual(result);
expect(lamb.countBy(lamb.isUndefined)(arr)).toEqual(result);
});
it("should throw an exception if called without the data argument", function () {
expect(lamb.count).toThrow();
expect(lamb.countBy(lamb.identity)).toThrow();
});
it("should throw an exception if supplied with `null` or `undefined`", function () {
expect(function () { lamb.count(null, lamb.identity); }).toThrow();
expect(function () { lamb.count(void 0, lamb.identity); }).toThrow();
expect(function () { lamb.countBy(lamb.identity)(null); }).toThrow();
expect(function () { lamb.countBy(lamb.identity)(void 0); }).toThrow();
});
it("should treat every other value as an empty array and return an empty object", function () {
wannabeEmptyArrays.forEach(function (value) {
expect(lamb.countBy(lamb.identity)(value)).toEqual({});
expect(lamb.count(value, lamb.identity)).toEqual({});
});
});
});
|
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
// import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
export default class NewTaskDialog extends React.Component {
state = {
open: false,
valid: false,
title: '',
description: ''
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.resetDialog();
this.setState({open: false});
};
resetDialog = () => {
this.setState({title: '', description: '', valid: false})
};
handleCreateTask = (e) => {
e.preventDefault();
this.props.onCreateTask({
title: this.state.title,
description: this.state.description
});
this.handleClose();
};
onTitleChange = (e) => {
this.setState({ title: e.target.value });
this.validate();
};
onDescriptionChange = (e) => {
this.setState({ description: e.target.value });
this.validate();
};
validate = () => {
if(this.state.title && this.state.description) {
this.setState({valid: true});
}
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Create Task"
primary={true}
disabled={!this.state.valid}
onTouchTap={this.handleCreateTask}
/>,
];
return (
<div>
<FlatButton label="New Task" onTouchTap={this.handleOpen} />
<Dialog
title="Create New Task"
actions={actions}
modal={true}
open={this.state.open}>
<TextField id="task-title"
hintText="Title"
value={this.state.title}
onChange={this.onTitleChange}/>
<br/>
<TextField id="task-description"
hintText="Description"
value={this.state.description}
onChange={this.onDescriptionChange}/>
<br/>
</Dialog>
</div>
);
}
} |
/* eslint key-spacing : 0 */
const EventEmitter = require('events');
class CAS extends EventEmitter {
constructor() {
super();
this.timeout = {
encode_ignition : null,
};
} // constructor()
// [0x130] Ignition status
decode_ignition(data) {
data.command = 'bro';
let new_level_name;
// Save previous ignition status
const previous_level = status.vehicle.ignition_level;
// Set ignition status value
update.status('vehicle.ignition_level', data.msg[0], false);
switch (data.msg[0]) {
case 0x00 : new_level_name = 'off'; break;
case 0x40 : // Whilst just beginning to turn the key
case 0x41 : new_level_name = 'accessory'; break;
case 0x45 : new_level_name = 'run'; break;
case 0x55 : new_level_name = 'start'; break;
default : new_level_name = 'unknown';
}
update.status('vehicle.ignition', new_level_name, false);
if (data.msg[0] > previous_level) { // Ignition going up
switch (data.msg[0]) { // Evaluate new ignition state
case 0x40 :
case 0x41 : { // Accessory
log.module('Powerup state');
break;
}
case 0x45 : { // Run
log.module('Run state');
// Perform KOMBI gauge sweep, if enabled
KOMBI.gauge_sweep();
break;
}
case 0x55 : { // Start
switch (previous_level) {
case 0x00 : { // If the accessory (1) ignition message wasn't caught
log.module('Powerup state');
break;
}
case 0x45 : { // If the run (3) ignition message wasn't caught
log.module('Run state');
break;
}
default : {
log.module('Start-begin state');
}
}
}
}
}
else if (data.msg[0] < previous_level) { // Ignition going down
switch (data.msg[0]) { // Evaluate new ignition state
case 0x00 : { // Off
// If the accessory (1) ignition message wasn't caught
if (previous_level === 0x45) {
log.module('Powerdown state');
}
log.module('Poweroff state');
break;
}
case 0x40 :
case 0x41 : { // Accessory
log.module('Powerdown state');
break;
}
case 0x45 : { // Run
log.module('Start-end state');
}
}
}
data.value = 'ignition status: ' + status.vehicle.ignition;
return data;
} // decode_ignition(data)
// Ignition status
encode_ignition(action) {
// Bounce if not enabled
if (config.emulate.cas !== true) return;
// Handle setting/unsetting timeout
switch (action) {
case false : {
// Return here if timeout is already null
if (this.timeout.encode_ignition !== null) {
clearTimeout(this.timeout.encode_ignition);
this.timeout.encode_ignition = null;
log.module('Unset ignition status timeout');
}
// Send ignition off message
bus.data.send({
bus : config.cas.can_intf,
id : 0x12F,
data : Buffer.from([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]),
});
// Return here since we're not re-sending again
return;
}
case true : {
if (this.timeout.encode_ignition === null) {
log.module('Set ignition status timeout');
}
this.timeout.encode_ignition = setTimeout(this.encode_ignition, 100);
}
}
const msg = {
bus : config.cas.can_intf,
};
switch (config.cas.generation.toLowerCase()) {
case 'exx' : { // CIC
msg.id = 0x4F8;
msg.data = [ 0x00, 0x42, 0xFE, 0x01, 0xFF, 0xFF, 0xFF, 0xFF ];
break;
}
case 'fxx' : { // NBT
msg.id = 0x12F;
msg.data = [ 0x37, 0x7C, 0x8A, 0xDD, 0xD4, 0x05, 0x33, 0x6B ];
break;
}
default : {
log.error('config.cas.generation must be set to one of Exx or Fxx');
return;
}
}
// Convert data array to Buffer
msg.data = Buffer.from(msg.data);
// Send message
bus.data.send(msg);
} // encode_ignition(action)
// Broadcast: Key fob status
// [0x23A] Decode a key fob bitmask message, and act upon the results
decode_status_keyfob(data) {
data.command = 'bro';
data.value = 'key fob status - ';
const mask = bitmask.check(data.msg[2]).mask;
const keyfob = {
button : null,
button_str : null,
buttons : {
lock : mask.bit2 && !mask.bit0 && !mask.bit4 && !mask.bit8,
unlock : !mask.bit2 && mask.bit0 && !mask.bit4 && !mask.bit8,
trunk : !mask.bit2 && !mask.bit0 && mask.bit4 && !mask.bit8,
none : !mask.bit2 && !mask.bit0 && !mask.bit4,
},
};
// Loop button object to populate log string
for (const button in keyfob.buttons) {
if (keyfob.buttons[button] !== true) continue;
keyfob.button = button;
keyfob.button_str = 'button: ' + button;
break;
}
// Update status object
update.status('cas.keyfob.button', keyfob.button, false);
update.status('cas.keyfob.buttons.lock', keyfob.buttons.lock, false);
update.status('cas.keyfob.buttons.none', keyfob.buttons.none, false);
update.status('cas.keyfob.buttons.trunk', keyfob.buttons.trunk, false);
update.status('cas.keyfob.buttons.unlock', keyfob.buttons.unlock, false);
// Emit keyfob event
this.emit('keyfob', keyfob);
// Assemble log string
data.value += keyfob.key_str + ', ' + keyfob.button_str + ', ' + keyfob.low_batt_str;
return data;
} // decode_status_keyfob(data)
// [0x2FC] Decode a door status message from CAS and act upon the results
decode_status_opened(data) {
data.command = 'bro';
data.value = 'door status';
// Set status from message by decoding bitmask
update.status('doors.front_left', bitmask.test(data.msg[1], 0x01), false);
update.status('doors.front_right', bitmask.test(data.msg[1], 0x04), false);
update.status('doors.hood', bitmask.test(data.msg[2], 0x04), false);
update.status('doors.rear_left', bitmask.test(data.msg[1], 0x10), false);
update.status('doors.rear_right', bitmask.test(data.msg[1], 0x40), false);
update.status('doors.trunk', bitmask.test(data.msg[2], 0x01), false);
// Set status.doors.closed if all doors are closed
const update_closed_doors = (!status.doors.front_left && !status.doors.front_right && !status.doors.rear_left && !status.doors.rear_right);
update.status('doors.closed', update_closed_doors, false);
// Set status.doors.opened if any doors are opened
update.status('doors.opened', (update_closed_doors === false), false);
// Set status.doors.sealed if all doors and flaps are closed
const update_sealed_doors = (status.doors.closed && !status.doors.hood && !status.doors.trunk);
update.status('doors.sealed', update_sealed_doors, false);
return data;
} // decode_status_opened(data)
init_listeners() {
// Bounce if not enabled
if (config.emulate.cas !== true && config.retrofit.cas !== true) return;
// Perform commands on power lib active event
power.on('active', data => {
this.encode_ignition(data.new);
});
log.module('Initialized listeners');
} // init_listeners()
// Parse data sent to module
parse_in(data) {
// Bounce if not enabled
if (config.emulate.cas !== true) return;
return data;
} // parse_in(data);
// Parse data sent from module
parse_out(data) {
switch (data.src.id) {
case 0x130 : return this.decode_ignition(data); // 0x12F / 0x4F8
case 0x23A : return this.decode_status_keyfob(data);
case 0x2FC : return this.decode_status_opened(data);
}
return data;
} // parse_out();
}
module.exports = CAS;
|
/*globals describe, afterEach, beforeEach, it*/
var should = require('should'),
sinon = require('sinon'),
Promise = require('bluebird'),
// Stuff we're testing
db = require('../../server/data/db'),
errors = require('../../server/errors'),
exporter = require('../../server/data/export'),
schema = require('../../server/data/schema'),
settings = require('../../server/api/settings'),
schemaTables = Object.keys(schema.tables),
sandbox = sinon.sandbox.create();
require('should-sinon');
describe('Exporter', function () {
var versionStub, tablesStub, queryMock, knexMock, knexStub;
afterEach(function () {
sandbox.restore();
knexStub.restore();
});
describe('doExport', function () {
beforeEach(function () {
versionStub = sandbox.stub(schema.versioning, 'getDatabaseVersion').returns(new Promise.resolve('004'));
tablesStub = sandbox.stub(schema.commands, 'getTables').returns(schemaTables);
queryMock = {
select: sandbox.stub()
};
knexMock = sandbox.stub().returns(queryMock);
// this MUST use sinon, not sandbox, see sinonjs/sinon#781
knexStub = sinon.stub(db, 'knex', {get: function () { return knexMock; }});
});
it('should try to export all the correct tables', function (done) {
// Setup for success
queryMock.select.returns(new Promise.resolve({}));
// Execute
exporter.doExport().then(function (exportData) {
// No tables, less the number of excluded tables
var expectedCallCount = schemaTables.length - 4;
should.exist(exportData);
versionStub.should.be.calledOnce();
tablesStub.should.be.calledOnce();
knexStub.get.should.be.called();
knexMock.should.be.called();
queryMock.select.should.be.called();
knexMock.should.have.callCount(expectedCallCount);
queryMock.select.should.have.callCount(expectedCallCount);
knexMock.getCall(0).should.be.calledWith('posts');
knexMock.getCall(1).should.be.calledWith('users');
knexMock.getCall(2).should.be.calledWith('roles');
knexMock.getCall(3).should.be.calledWith('roles_users');
knexMock.getCall(4).should.be.calledWith('permissions');
knexMock.getCall(5).should.be.calledWith('permissions_users');
knexMock.getCall(6).should.be.calledWith('permissions_roles');
knexMock.getCall(7).should.be.calledWith('permissions_apps');
knexMock.getCall(8).should.be.calledWith('settings');
knexMock.getCall(9).should.be.calledWith('tags');
knexMock.getCall(10).should.be.calledWith('posts_tags');
knexMock.getCall(11).should.be.calledWith('apps');
knexMock.getCall(12).should.be.calledWith('app_settings');
knexMock.getCall(13).should.be.calledWith('app_fields');
knexMock.should.not.be.calledWith('clients');
knexMock.should.not.be.calledWith('client_trusted_domains');
knexMock.should.not.be.calledWith('refreshtokens');
knexMock.should.not.be.calledWith('accesstokens');
done();
}).catch(done);
});
it('should catch and log any errors', function (done) {
// Setup for failure
var errorStub = sandbox.stub(errors, 'logAndThrowError');
queryMock.select.returns(new Promise.reject({}));
// Execute
exporter.doExport().then(function (exportData) {
should.not.exist(exportData);
errorStub.should.be.calledOnce();
done();
}).catch(done);
});
});
describe('exportFileName', function () {
it('should return a correctly structured filename', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.resolve({settings: [{value: 'testblog'}]})
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^testblog\.ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
it('should return a correctly structured filename if settings is empty', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.resolve()
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
it('should return a correctly structured filename if settings errors', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.reject()
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
});
});
|
'use strict';
const Sites = require('./reducers/sites-list');
const Site = require('./reducers/site-form');
const User = require('./reducers/user');
const Delete = require('./reducers/delete');
const Count = require('./reducers/count');
const Redux = require('redux');
module.exports = Redux.createStore(
Redux.combineReducers({
delete: Delete,
sites: Sites,
site: Site,
count: Count,
user: User
})
);
|
/**
* Linked lists utilities
* Algorithm author: Harold Gonzalez
* Twitter: @haroldcng
* Questions: [email protected]
*/
'use strict';
/**
* Definition of Linked List Node Data Structure
*/
module.exports.ListNode = function(v){
this.val = v;
this.next = null;
};
/**
* Prints a linked list from the given node to the end
*/
module.exports.printLinkedList = (node) => {
while(node !== null){
process.stdout.write(node.val + " -> ");
node = node.next;
}
console.log("NULL");
}; |
/**
* System commands
* Pokemon Showdown - http://pokemonshowdown.com/
*
* These are system commands - commands required for Pokemon Showdown
* to run. A lot of these are sent by the client.
*
* System commands should not be modified, added, or removed. If you'd
* like to modify or add commands, add or edit files in chat-plugins/
*
* For the API, see chat-plugins/COMMANDS.md
*
* @license MIT license
*/
var crypto = require('crypto');
var fs = require('fs');
// MODIFICADO PARA POKEFABRICA EMOTICONOS
var parseEmoticons = require('./chat-plugins/emoticons').parseEmoticons;
// MODIFICADO PARA POKEFABRICA EMOTICONOS
const MAX_REASON_LENGTH = 300;
const MUTE_LENGTH = 7 * 60 * 1000;
const HOURMUTE_LENGTH = 60 * 60 * 1000;
var commands = exports.commands = {
version: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox("Server version: <b>" + CommandParser.package.version + "</b>");
},
auth: 'authority',
stafflist: 'authority',
globalauth: 'authority',
authlist: 'authority',
authority: function (target, room, user, connection) {
var rankLists = {};
var ranks = Object.keys(Config.groups);
for (var u in Users.usergroups) {
var rank = Users.usergroups[u].charAt(0);
if (rank === ' ' || rank === '+') continue;
// In case the usergroups.csv file is not proper, we check for the server ranks.
if (ranks.indexOf(rank) >= 0) {
var name = Users.usergroups[u].substr(1);
if (!rankLists[rank]) rankLists[rank] = [];
if (name) rankLists[rank].push(name);
}
}
var buffer = [];
Object.keys(rankLists).sort(function (a, b) {
return (Config.groups[b] || {rank: 0}).rank - (Config.groups[a] || {rank: 0}).rank;
}).forEach(function (r) {
buffer.push((Config.groups[r] ? Config.groups[r].name + "s (" + r + ")" : r) + ":\n" + rankLists[r].sortBy(toId).join(", "));
});
if (!buffer.length) buffer = "This server has no global authority.";
connection.popup(buffer.join("\n\n"));
},
me: function (target, room, user, connection) {
// By default, /me allows a blank message
if (target) target = this.canTalk(target);
if (!target) return;
return '/me ' + target;
},
mee: function (target, room, user, connection) {
// By default, /mee allows a blank message
if (target) target = this.canTalk(target);
if (!target) return;
return '/mee ' + target;
},
avatar: function (target, room, user) {
if (!target) return this.parse('/avatars');
var parts = target.split(',');
var avatar = parseInt(parts[0]);
if (parts[0] === '#bw2elesa') {
avatar = parts[0];
}
if (typeof avatar === 'number' && (!avatar || avatar > 294 || avatar < 1)) {
if (!parts[1]) {
this.sendReply("Invalid avatar.");
}
return false;
}
user.avatar = avatar;
if (!parts[1]) {
this.sendReply("Avatar changed to:\n" +
'|raw|<img src="//play.pokemonshowdown.com/sprites/trainers/' + (typeof avatar === 'string' ? avatar.substr(1) : avatar) + '.png" alt="" width="80" height="80" />');
}
},
avatarhelp: ["/avatar [avatar number 1 to 293] - Change your trainer sprite."],
signout: 'logout',
logout: function (target, room, user) {
user.resetName();
},
requesthelp: 'report',
report: function (target, room, user) {
if (room.id === 'help') {
this.sendReply("Ask one of the Moderators (@) in the Help room.");
} else {
this.parse('/join help');
}
},
r: 'reply',
reply: function (target, room, user) {
if (!target) return this.parse('/help reply');
if (!user.lastPM) {
return this.sendReply("No one has PMed you yet.");
}
return this.parse('/msg ' + (user.lastPM || '') + ', ' + target);
},
replyhelp: ["/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."],
pm: 'msg',
whisper: 'msg',
w: 'msg',
msg: function (target, room, user, connection) {
if (!target) return this.parse('/help msg');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!target) {
this.sendReply("You forgot the comma.");
return this.parse('/help msg');
}
this.pmTarget = (targetUser || this.targetUsername);
if (!targetUser || !targetUser.connected) {
if (targetUser && !targetUser.connected) {
this.errorReply("User " + this.targetUsername + " is offline.");
return;
} else {
this.errorReply("User " + this.targetUsername + " not found. Did you misspell their name?");
return this.parse('/help msg');
}
return;
}
if (Config.pmmodchat) {
var userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.errorReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to PM users.");
return false;
}
}
if (user.locked && !targetUser.can('lock')) {
return this.errorReply("You can only private message members of the moderation team (users marked by %, @, &, or ~) when locked.");
}
if (targetUser.locked && !user.can('lock')) {
return this.errorReply("This user is locked and cannot PM.");
}
if (targetUser.ignorePMs && targetUser.ignorePMs !== user.group && !user.can('lock')) {
if (!targetUser.can('lock')) {
return this.errorReply("This user is blocking private messages right now.");
} else if (targetUser.can('bypassall')) {
return this.errorReply("This admin is too busy to answer private messages right now. Please contact a different staff member.");
}
}
if (user.ignorePMs && user.ignorePMs !== targetUser.group && !targetUser.can('lock')) {
return this.errorReply("You are blocking private messages right now.");
}
target = this.canTalk(target, null, targetUser);
if (!target) return false;
if (target.charAt(0) === '/' && target.charAt(1) !== '/') {
// PM command
var innerCmdIndex = target.indexOf(' ');
var innerCmd = (innerCmdIndex >= 0 ? target.slice(1, innerCmdIndex) : target.slice(1));
var innerTarget = (innerCmdIndex >= 0 ? target.slice(innerCmdIndex + 1) : '');
switch (innerCmd) {
case 'me':
case 'mee':
case 'announce':
break;
case 'invite':
case 'inv':
var targetRoom = Rooms.search(innerTarget);
if (!targetRoom || targetRoom === Rooms.global) return this.errorReply('The room "' + innerTarget + '" does not exist.');
if (targetRoom.staffRoom && !targetUser.isStaff) return this.errorReply('User "' + this.targetUsername + '" requires global auth to join room "' + targetRoom.id + '".');
if (targetRoom.isPrivate === true && targetRoom.modjoin && targetRoom.auth) {
if (Config.groupsranking.indexOf(targetRoom.auth[targetUser.userid] || ' ') < Config.groupsranking.indexOf(targetRoom.modjoin) && !targetUser.can('bypassall')) {
return this.errorReply('The room "' + innerTarget + '" does not exist.');
}
}
if (targetRoom.modjoin) {
if (targetRoom.auth && (targetRoom.isPrivate === true || targetUser.group === ' ') && !(targetUser.userid in targetRoom.auth)) {
this.parse('/roomvoice ' + targetUser.name, false, targetRoom);
if (!(targetUser.userid in targetRoom.auth)) {
return;
}
}
}
target = '/invite ' + targetRoom.id;
break;
default:
return this.errorReply("The command '/" + innerCmd + "' was unrecognized or unavailable in private messages. To send a message starting with '/" + innerCmd + "', type '//" + innerCmd + "'.");
}
}
// MODIFICADO POKEFABRICA PARA EMOTICONOS
var emoteMsg = parseEmoticons(target, room, user, true);
if (emoteMsg) target = '/html ' + emoteMsg;
// MODIFICADO POKEFABRICA PARA EMOTICONOS
var message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target;
user.send(message);
if (targetUser !== user) targetUser.send(message);
targetUser.lastPM = user.userid;
user.lastPM = targetUser.userid;
},
msghelp: ["/msg OR /whisper OR /w [username], [message] - Send a private message."],
blockpm: 'ignorepms',
blockpms: 'ignorepms',
ignorepm: 'ignorepms',
ignorepms: function (target, room, user) {
if (user.ignorePMs === (target || true)) return this.sendReply("You are already blocking private messages! To unblock, use /unblockpms");
if (user.can('lock') && !user.can('bypassall')) return this.sendReply("You are not allowed to block private messages.");
user.ignorePMs = true;
if (target in Config.groups) {
user.ignorePMs = target;
return this.sendReply("You are now blocking private messages, except from staff and " + target + ".");
}
return this.sendReply("You are now blocking private messages, except from staff.");
},
ignorepmshelp: ["/blockpms - Blocks private messages. Unblock them with /unignorepms."],
unblockpm: 'unignorepms',
unblockpms: 'unignorepms',
unignorepm: 'unignorepms',
unignorepms: function (target, room, user) {
if (!user.ignorePMs) return this.sendReply("You are not blocking private messages! To block, use /blockpms");
user.ignorePMs = false;
return this.sendReply("You are no longer blocking private messages.");
},
unignorepmshelp: ["/unblockpms - Unblocks private messages. Block them with /blockpms."],
idle: 'away',
afk: 'away',
away: function (target, room, user) {
this.parse('/blockchallenges');
this.parse('/blockpms ' + target);
},
awayhelp: ["/away - Blocks challenges and private messages. Unblock them with /back."],
unaway: 'back',
unafk: 'back',
back: function () {
this.parse('/unblockpms');
this.parse('/unblockchallenges');
},
backhelp: ["/back - Unblocks challenges and/or private messages, if either are blocked."],
makeprivatechatroom: 'makechatroom',
makechatroom: function (target, room, user, connection, cmd) {
if (!this.can('makeroom')) return;
// `,` is a delimiter used by a lot of /commands
// `|` and `[` are delimiters used by the protocol
// `-` has special meaning in roomids
if (target.includes(',') || target.includes('|') || target.includes('[') || target.includes('-')) {
return this.sendReply("Room titles can't contain any of: ,|[-");
}
var id = toId(target);
if (!id) return this.parse('/help makechatroom');
// Check if the name already exists as a room or alias
if (Rooms.search(id)) return this.sendReply("The room '" + target + "' already exists.");
if (Rooms.global.addChatRoom(target)) {
if (cmd === 'makeprivatechatroom') {
var targetRoom = Rooms.search(target);
targetRoom.isPrivate = true;
targetRoom.chatRoomData.isPrivate = true;
Rooms.global.writeChatRoomData();
if (Rooms('upperstaff')) {
Rooms('upperstaff').add('|raw|<div class="broadcast-green">Private chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update();
}
return this.sendReply("The private chat room '" + target + "' was created.");
} else {
if (Rooms('staff')) {
Rooms('staff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update();
}
if (Rooms('upperstaff')) {
Rooms('upperstaff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update();
}
return this.sendReply("The chat room '" + target + "' was created.");
}
}
return this.sendReply("An error occurred while trying to create the room '" + target + "'.");
},
makechatroomhelp: ["/makechatroom [roomname] - Creates a new room named [roomname]. Requires: ~"],
makegroupchat: function (target, room, user, connection, cmd) {
if (!user.autoconfirmed) {
return this.errorReply("You don't have permission to make a group chat right now.");
}
if (target.length > 64) return this.errorReply("Title must be under 32 characters long.");
var targets = target.split(',', 2);
// Title defaults to a random 8-digit number.
var title = targets[0].trim();
if (title.length >= 32) {
return this.errorReply("Title must be under 32 characters long.");
} else if (!title) {
title = ('' + Math.floor(Math.random() * 100000000));
} else if (Config.chatfilter) {
var filterResult = Config.chatfilter.call(this, title, user, null, connection);
if (!filterResult) return;
if (title !== filterResult) {
return this.errorReply("Invalid title.");
}
}
// `,` is a delimiter used by a lot of /commands
// `|` and `[` are delimiters used by the protocol
// `-` has special meaning in roomids
if (title.includes(',') || title.includes('|') || title.includes('[') || title.includes('-')) {
return this.errorReply("Room titles can't contain any of: ,|[-");
}
// Even though they're different namespaces, to cut down on confusion, you
// can't share names with registered chatrooms.
var existingRoom = Rooms.search(toId(title));
if (existingRoom && !existingRoom.modjoin) return this.errorReply("The room '" + title + "' already exists.");
// Room IDs for groupchats are groupchat-TITLEID
var titleid = toId(title);
if (!titleid) {
titleid = '' + Math.floor(Math.random() * 100000000);
}
var roomid = 'groupchat-' + user.userid + '-' + titleid;
// Titles must be unique.
if (Rooms.search(roomid)) return this.errorReply("A group chat named '" + title + "' already exists.");
// Tab title is prefixed with '[G]' to distinguish groupchats from
// registered chatrooms
title = title;
if (ResourceMonitor.countGroupChat(connection.ip)) {
this.errorReply("Due to high load, you are limited to creating 4 group chats every hour.");
return;
}
// Privacy settings, default to hidden.
var privacy = toId(targets[1]) || 'hidden';
var privacySettings = {private: true, hidden: 'hidden', public: false};
if (!(privacy in privacySettings)) privacy = 'hidden';
var groupChatLink = '<code><<' + roomid + '>></code>';
var groupChatURL = '';
if (Config.serverid) {
groupChatURL = 'http://' + (Config.serverid === 'showdown' ? 'psim.us' : Config.serverid + '.psim.us') + '/' + roomid;
groupChatLink = '<a href="' + groupChatURL + '">' + groupChatLink + '</a>';
}
var titleHTML = '';
if (/^[0-9]+$/.test(title)) {
titleHTML = groupChatLink;
} else {
titleHTML = Tools.escapeHTML(title) + ' <small style="font-weight:normal;font-size:9pt">' + groupChatLink + '</small>';
}
var targetRoom = Rooms.createChatRoom(roomid, '[G] ' + title, {
isPersonal: true,
isPrivate: privacySettings[privacy],
auth: {},
introMessage: '<h2 style="margin-top:0">' + titleHTML + '</h2><p>There are several ways to invite people:<br />- in this chat: <code>/invite USERNAME</code><br />- anywhere in PS: link to <code><<' + roomid + '>></code>' + (groupChatURL ? '<br />- outside of PS: link to <a href="' + groupChatURL + '">' + groupChatURL + '</a>' : '') + '</p><p>This room will expire after 40 minutes of inactivity or when the server is restarted.</p><p style="margin-bottom:0"><button name="send" value="/roomhelp">Room management</button>'
});
if (targetRoom) {
// The creator is RO.
targetRoom.auth[user.userid] = '#';
// Join after creating room. No other response is given.
user.joinRoom(targetRoom.id);
return;
}
return this.errorReply("An unknown error occurred while trying to create the room '" + title + "'.");
},
makegroupchathelp: ["/makegroupchat [roomname], [private|hidden|public] - Creates a group chat named [roomname]. Leave off privacy to default to hidden."],
deregisterchatroom: function (target, room, user) {
if (!this.can('makeroom')) return;
var id = toId(target);
if (!id) return this.parse('/help deregisterchatroom');
var targetRoom = Rooms.search(id);
if (!targetRoom) return this.sendReply("The room '" + target + "' doesn't exist.");
target = targetRoom.title || targetRoom.id;
if (Rooms.global.deregisterChatRoom(id)) {
this.sendReply("The room '" + target + "' was deregistered.");
this.sendReply("It will be deleted as of the next server restart.");
return;
}
return this.sendReply("The room '" + target + "' isn't registered.");
},
deregisterchatroomhelp: ["/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: ~"],
hideroom: 'privateroom',
hiddenroom: 'privateroom',
secretroom: 'privateroom',
publicroom: 'publicroom',
privateroom: function (target, room, user, connection, cmd) {
if (room.battle || room.isPersonal) {
if (!this.can('editroom', null, room)) return;
} else {
// registered chatrooms show up on the room list and so require
// higher permissions to modify privacy settings
if (!this.can('makeroom')) return;
}
var setting;
switch (cmd) {
case 'privateroom':
return this.parse('/help privateroom');
break;
case 'publicroom':
setting = false;
break;
case 'secretroom':
setting = true;
break;
default:
if (room.isPrivate === true && target !== 'force') {
return this.sendReply("This room is a secret room. Use `/publicroom` to make it public, or `/hiddenroom force` to force hidden.");
}
setting = 'hidden';
break;
}
if ((setting === true || room.isPrivate === true) && !room.isPersonal) {
if (!this.can('makeroom')) return;
}
if (target === 'off' || !setting) {
delete room.isPrivate;
this.addModCommand("" + user.name + " made this room public.");
if (room.chatRoomData) {
delete room.chatRoomData.isPrivate;
Rooms.global.writeChatRoomData();
}
} else {
if (room.isPrivate === setting) {
return this.errorReply("This room is already " + (setting === true ? 'secret' : setting) + ".");
}
room.isPrivate = setting;
this.addModCommand("" + user.name + " made this room " + (setting === true ? 'secret' : setting) + ".");
if (room.chatRoomData) {
room.chatRoomData.isPrivate = setting;
Rooms.global.writeChatRoomData();
}
}
},
privateroomhelp: ["/secretroom - Makes a room secret. Secret rooms are visible to & and up. Requires: & ~",
"/hiddenroom [on/off] - Makes a room hidden. Hidden rooms are visible to % and up, and inherit global ranks. Requires: \u2605 & ~",
"/publicroom - Makes a room public. Requires: \u2605 & ~"],
modjoin: function (target, room, user) {
if (room.battle || room.isPersonal) {
if (!this.can('editroom', null, room)) return;
} else {
if (!this.can('makeroom')) return;
}
if (target === 'off' || target === 'false') {
delete room.modjoin;
this.addModCommand("" + user.name + " turned off modjoin.");
if (room.chatRoomData) {
delete room.chatRoomData.modjoin;
Rooms.global.writeChatRoomData();
}
} else {
if ((target === 'on' || target === 'true' || !target) || !user.can('editroom')) {
room.modjoin = true;
this.addModCommand("" + user.name + " turned on modjoin.");
} else if (target in Config.groups) {
room.modjoin = target;
this.addModCommand("" + user.name + " set modjoin to " + target + ".");
} else {
this.sendReply("Unrecognized modjoin setting.");
return false;
}
if (room.chatRoomData) {
room.chatRoomData.modjoin = room.modjoin;
Rooms.global.writeChatRoomData();
}
if (!room.modchat) this.parse('/modchat ' + Config.groupsranking[1]);
if (!room.isPrivate) this.parse('/hiddenroom');
}
},
officialchatroom: 'officialroom',
officialroom: function (target, room, user) {
if (!this.can('makeroom')) return;
if (!room.chatRoomData) {
return this.sendReply("/officialroom - This room can't be made official");
}
if (target === 'off') {
delete room.isOfficial;
this.addModCommand("" + user.name + " made this chat room unofficial.");
delete room.chatRoomData.isOfficial;
Rooms.global.writeChatRoomData();
} else {
room.isOfficial = true;
this.addModCommand("" + user.name + " made this chat room official.");
room.chatRoomData.isOfficial = true;
Rooms.global.writeChatRoomData();
}
},
roomdesc: function (target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
if (!room.desc) return this.sendReply("This room does not have a description set.");
this.sendReplyBox("The room description is: " + Tools.escapeHTML(room.desc));
return;
}
if (!this.can('declare')) return false;
if (target.length > 80) return this.sendReply("Error: Room description is too long (must be at most 80 characters).");
var normalizedTarget = ' ' + target.toLowerCase().replace('[^a-zA-Z0-9]+', ' ').trim() + ' ';
if (normalizedTarget.includes(' welcome ')) {
return this.sendReply("Error: Room description must not contain the word 'welcome'.");
}
if (normalizedTarget.slice(0, 9) === ' discuss ') {
return this.sendReply("Error: Room description must not start with the word 'discuss'.");
}
if (normalizedTarget.slice(0, 12) === ' talk about ' || normalizedTarget.slice(0, 17) === ' talk here about ') {
return this.sendReply("Error: Room description must not start with the phrase 'talk about'.");
}
room.desc = target;
this.sendReply("(The room description is now: " + target + ")");
this.privateModCommand("(" + user.name + " changed the roomdesc to: \"" + target + "\".)");
if (room.chatRoomData) {
room.chatRoomData.desc = room.desc;
Rooms.global.writeChatRoomData();
}
},
topic: 'roomintro',
roomintro: function (target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
if (!room.introMessage) return this.sendReply("This room does not have an introduction set.");
this.sendReply('|raw|<div class="infobox infobox-limited">' + room.introMessage + '</div>');
if (!this.broadcasting && user.can('declare', null, room)) {
this.sendReply('Source:');
this.sendReplyBox('<code>/roomintro ' + Tools.escapeHTML(room.introMessage) + '</code>');
}
return;
}
target = target.trim();
if (!this.can('declare', null, room)) return false;
if (!this.canHTML(target)) return;
if (!/</.test(target)) {
// not HTML, do some simple URL linking
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g;
target = target.replace(re, '<a href="$1">$1</a>');
}
if (target.substr(0, 11) === '/roomintro ') target = target.substr(11);
room.introMessage = target;
this.sendReply("(The room introduction has been changed to:)");
this.sendReply('|raw|<div class="infobox infobox-limited">' + target + '</div>');
this.privateModCommand("(" + user.name + " changed the roomintro.)");
if (room.chatRoomData) {
room.chatRoomData.introMessage = room.introMessage;
Rooms.global.writeChatRoomData();
}
},
stafftopic: 'staffintro',
staffintro: function (target, room, user) {
if (!target) {
if (!this.can('mute', null, room)) return false;
if (!room.staffMessage) return this.sendReply("This room does not have a staff introduction set.");
this.sendReply('|raw|<div class="infobox">' + room.staffMessage + '</div>');
if (user.can('ban', null, room)) {
this.sendReply('Source:');
this.sendReplyBox('<code>/staffintro ' + Tools.escapeHTML(room.staffMessage) + '</code>');
}
return;
}
if (!this.can('ban', null, room)) return false;
target = target.trim();
if (!this.canHTML(target)) return;
if (!/</.test(target)) {
// not HTML, do some simple URL linking
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g;
target = target.replace(re, '<a href="$1">$1</a>');
}
if (target.substr(0, 12) === '/staffintro ') target = target.substr(12);
room.staffMessage = target;
this.sendReply("(The staff introduction has been changed to:)");
this.sendReply('|raw|<div class="infobox">' + target + '</div>');
this.privateModCommand("(" + user.name + " changed the staffintro.)");
if (room.chatRoomData) {
room.chatRoomData.staffMessage = room.staffMessage;
Rooms.global.writeChatRoomData();
}
},
roomalias: function (target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
if (!room.aliases || !room.aliases.length) return this.sendReplyBox("This room does not have any aliases.");
return this.sendReplyBox("This room has the following aliases: " + room.aliases.join(", ") + "");
}
if (!this.can('setalias')) return false;
var alias = toId(target);
if (!alias.length) return this.sendReply("Only alphanumeric characters are valid in an alias.");
if (Rooms.get(alias) || Rooms.aliases[alias]) return this.sendReply("You cannot set an alias to an existing room or alias.");
if (room.isPersonal) return this.sendReply("Personal rooms can't have aliases.");
Rooms.aliases[alias] = room.id;
this.privateModCommand("(" + user.name + " added the room alias '" + target + "'.)");
if (!room.aliases) room.aliases = [];
room.aliases.push(alias);
if (room.chatRoomData) {
room.chatRoomData.aliases = room.aliases;
Rooms.global.writeChatRoomData();
}
},
removeroomalias: function (target, room, user) {
if (!room.aliases) return this.sendReply("This room does not have any aliases.");
if (!this.can('setalias')) return false;
var alias = toId(target);
if (!alias.length || !Rooms.aliases[alias]) return this.sendReply("Please specify an existing alias.");
if (Rooms.aliases[alias] !== room.id) return this.sendReply("You may only remove an alias from the current room.");
this.privateModCommand("(" + user.name + " removed the room alias '" + target + "'.)");
var aliasIndex = room.aliases.indexOf(alias);
if (aliasIndex >= 0) {
room.aliases.splice(aliasIndex, 1);
delete Rooms.aliases[alias];
Rooms.global.writeChatRoomData();
}
},
roomowner: function (target, room, user) {
if (!room.chatRoomData) {
return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added");
}
if (!target) return this.parse('/help roomowner');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' is not online.");
if (!this.can('makeroom')) return false;
if (!room.auth) room.auth = room.chatRoomData.auth = {};
var name = targetUser.name;
room.auth[targetUser.userid] = '#';
this.addModCommand("" + name + " was appointed Room Owner by " + user.name + ".");
room.onUpdateIdentity(targetUser);
Rooms.global.writeChatRoomData();
},
roomownerhelp: ["/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: ~"],
roomdeowner: 'deroomowner',
deroomowner: function (target, room, user) {
if (!room.auth) {
return this.sendReply("/roomdeowner - This room isn't designed for per-room moderation");
}
if (!target) return this.parse('/help roomdeowner');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
var name = this.targetUsername;
var userid = toId(name);
if (!userid || userid === '') return this.sendReply("User '" + name + "' does not exist.");
if (room.auth[userid] !== '#') return this.sendReply("User '" + name + "' is not a room owner.");
if (!this.can('makeroom')) return false;
delete room.auth[userid];
this.sendReply("(" + name + " is no longer Room Owner.)");
if (targetUser) targetUser.updateIdentity();
if (room.chatRoomData) {
Rooms.global.writeChatRoomData();
}
},
deroomownerhelp: ["/roomdeowner [username] - Removes [username]'s status as a room owner. Requires: ~"],
roomdemote: 'roompromote',
roompromote: function (target, room, user, connection, cmd) {
if (!room.auth) {
this.sendReply("/roompromote - This room isn't designed for per-room moderation");
return this.sendReply("Before setting room mods, you need to set it up with /roomowner");
}
if (!target) return this.parse('/help roompromote');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
var userid = toId(this.targetUsername);
var name = targetUser ? targetUser.name : this.targetUsername;
if (!userid) return this.parse('/help roompromote');
if (!room.auth || !room.auth[userid]) {
if (!targetUser) {
return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
}
if (!targetUser.registered) {
return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
}
}
var currentGroup = ((room.auth && room.auth[userid]) || (room.isPrivate !== true && targetUser.group) || ' ');
var nextGroup = target;
if (target === 'deauth') nextGroup = Config.groupsranking[0];
if (!nextGroup) {
return this.sendReply("Please specify a group such as /roomvoice or /roomdeauth");
}
if (!Config.groups[nextGroup]) {
return this.sendReply("Group '" + nextGroup + "' does not exist.");
}
if (Config.groups[nextGroup].globalonly || (Config.groups[nextGroup].battleonly && !room.battle)) {
return this.sendReply("Group 'room" + Config.groups[nextGroup].id + "' does not exist as a room rank.");
}
var groupName = Config.groups[nextGroup].name || "regular user";
if ((room.auth[userid] || Config.groupsranking[0]) === nextGroup) {
return this.sendReply("User '" + name + "' is already a " + groupName + " in this room.");
}
if (!user.can('makeroom')) {
if (currentGroup !== ' ' && !user.can('room' + (Config.groups[currentGroup] ? Config.groups[currentGroup].id : 'voice'), null, room)) {
return this.sendReply("/" + cmd + " - Access denied for promoting/demoting from " + (Config.groups[currentGroup] ? Config.groups[currentGroup].name : "an undefined group") + ".");
}
if (nextGroup !== ' ' && !user.can('room' + Config.groups[nextGroup].id, null, room)) {
return this.sendReply("/" + cmd + " - Access denied for promoting/demoting to " + Config.groups[nextGroup].name + ".");
}
}
if (nextGroup === ' ') {
delete room.auth[userid];
} else {
room.auth[userid] = nextGroup;
}
if (Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) {
this.privateModCommand("(" + name + " was demoted to Room " + groupName + " by " + user.name + ".)");
if (targetUser && Rooms.rooms[room.id].users[targetUser.userid]) targetUser.popup("You were demoted to Room " + groupName + " by " + user.name + ".");
} else if (nextGroup === '#') {
this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + ".");
} else {
this.addModCommand("" + name + " was promoted to Room " + groupName + " by " + user.name + ".");
}
if (targetUser) targetUser.updateIdentity(room.id);
if (room.chatRoomData) Rooms.global.writeChatRoomData();
},
roompromotehelp: ["/roompromote OR /roomdemote [username], [group symbol] - Promotes/demotes the user to the specified room rank. Requires: @ # & ~",
"/room[group] [username] - Promotes/demotes the user to the specified room rank. Requires: @ # & ~",
"/roomdeauth [username] - Removes all room rank from the user. Requires: @ # & ~"],
roomstaff: 'roomauth',
roomauth: function (target, room, user, connection) {
var targetRoom = room;
if (target) targetRoom = Rooms.search(target);
var unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom'));
if (!targetRoom || unavailableRoom) return this.sendReply("The room '" + target + "' does not exist.");
if (!targetRoom.auth) return this.sendReply("/roomauth - The room '" + (targetRoom.title ? targetRoom.title : target) + "' isn't designed for per-room moderation and therefore has no auth list.");
var rankLists = {};
for (var u in targetRoom.auth) {
if (!rankLists[targetRoom.auth[u]]) rankLists[targetRoom.auth[u]] = [];
rankLists[targetRoom.auth[u]].push(u);
}
var buffer = [];
Object.keys(rankLists).sort(function (a, b) {
return (Config.groups[b] || {rank:0}).rank - (Config.groups[a] || {rank:0}).rank;
}).forEach(function (r) {
buffer.push((Config.groups[r] ? Config.groups[r] .name + "s (" + r + ")" : r) + ":\n" + rankLists[r].sort().join(", "));
});
if (!buffer.length) {
connection.popup("The room '" + targetRoom.title + "' has no auth.");
return;
}
if (targetRoom !== room) buffer.unshift("" + targetRoom.title + " room auth:");
connection.popup(buffer.join("\n\n"));
},
userauth: function (target, room, user, connection) {
var targetId = toId(target) || user.userid;
var targetUser = Users.getExact(targetId);
var targetUsername = (targetUser ? targetUser.name : target);
var buffer = [];
var innerBuffer = [];
var group = Users.usergroups[targetId];
if (group) {
buffer.push('Global auth: ' + group.charAt(0));
}
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || curRoom.isPrivate) continue;
group = curRoom.auth[targetId];
if (!group) continue;
innerBuffer.push(group + curRoom.id);
}
if (innerBuffer.length) {
buffer.push('Room auth: ' + innerBuffer.join(', '));
}
if (targetId === user.userid || user.can('lock')) {
innerBuffer = [];
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || !curRoom.isPrivate) continue;
if (curRoom.isPrivate === true) continue;
var auth = curRoom.auth[targetId];
if (!auth) continue;
innerBuffer.push(auth + curRoom.id);
}
if (innerBuffer.length) {
buffer.push('Hidden room auth: ' + innerBuffer.join(', '));
}
}
if (targetId === user.userid || user.can('makeroom')) {
innerBuffer = [];
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || !curRoom.isPrivate) continue;
if (curRoom.isPrivate !== true) continue;
var auth = curRoom.auth[targetId];
if (!auth) continue;
innerBuffer.push(auth + curRoom.id);
}
if (innerBuffer.length) {
buffer.push('Private room auth: ' + innerBuffer.join(', '));
}
}
if (!buffer.length) {
buffer.push("No global or room auth.");
}
buffer.unshift("" + targetUsername + " user auth:");
connection.popup(buffer.join("\n\n"));
},
rb: 'roomban',
roomban: function (target, room, user, connection) {
if (!target) return this.parse('/help roomban');
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
var name = this.targetUsername;
var userid = toId(name);
if (!userid || !targetUser) return this.sendReply("User '" + name + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('ban', targetUser, room)) return false;
if (!room.bannedUsers || !room.bannedIps) {
return this.sendReply("Room bans are not meant to be used in room " + room.id + ".");
}
if (room.bannedUsers[userid] && room.bannedIps[targetUser.latestIp]) return this.sendReply("User " + targetUser.name + " is already banned from room " + room.id + ".");
if (targetUser in room.users) {
targetUser.popup(
"|html|<p>" + Tools.escapeHTML(user.name) + " has banned you from the room " + room.id + ".</p>" + (target ? "<p>Reason: " + Tools.escapeHTML(target) + "</p>" : "") +
"<p>To appeal the ban, PM the staff member that banned you" + (room.auth ? " or a room owner. </p><p><button name=\"send\" value=\"/roomauth " + room.id + "\">List Room Staff</button></p>" : ".</p>")
);
}
this.addModCommand("" + targetUser.name + " was banned from room " + room.id + " by " + user.name + "." + (target ? " (" + target + ")" : ""));
var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
var alts = room.roomBan(targetUser);
if (alts.length) {
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "roombanned alts: " + alts.join(", ") + ")");
for (var i = 0; i < alts.length; ++i) {
this.add('|unlink|' + toId(alts[i]));
}
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
this.add('|unlink|' + this.getLastIdOf(targetUser));
},
roombanhelp: ["/roomban [username] - Bans the user from the room you are in. Requires: @ # & ~"],
unroomban: 'roomunban',
roomunban: function (target, room, user, connection) {
if (!target) return this.parse('/help roomunban');
if (!room.bannedUsers || !room.bannedIps) {
return this.sendReply("Room bans are not meant to be used in room " + room.id + ".");
}
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
this.splitTarget(target, true);
var targetUser = this.targetUser;
var userid = room.isRoomBanned(targetUser) || toId(target);
if (!userid) return this.sendReply("User '" + target + "' is an invalid username.");
if (targetUser && !this.can('ban', targetUser, room)) return false;
var unbannedUserid = room.unRoomBan(userid);
if (!unbannedUserid) return this.sendReply("User " + userid + " is not banned from room " + room.id + ".");
this.addModCommand("" + unbannedUserid + " was unbanned from room " + room.id + " by " + user.name + ".");
},
roomunbanhelp: ["/roomunban [username] - Unbans the user from the room you are in. Requires: @ # & ~"],
autojoin: function (target, room, user, connection) {
Rooms.global.autojoinRooms(user, connection);
var targets = target.split(',');
var autojoins = [];
if (targets.length > 9 || Object.keys(connection.rooms).length > 1) return;
for (var i = 0; i < targets.length; i++) {
if (user.tryJoinRoom(targets[i], connection) === null) {
autojoins.push(targets[i]);
}
}
connection.autojoins = autojoins.join(',');
},
joim: 'join',
j: 'join',
join: function (target, room, user, connection) {
if (!target) return false;
if (user.tryJoinRoom(target, connection) === null) {
connection.sendTo(target, "|noinit|namerequired|The room '" + target + "' does not exist or requires a login to join.");
}
},
leave: 'part',
part: function (target, room, user, connection) {
if (room.id === 'global') return false;
var targetRoom = Rooms.search(target);
if (target && !targetRoom) {
return this.sendReply("The room '" + target + "' does not exist.");
}
user.leaveRoom(targetRoom || room, connection);
},
/*********************************************************
* Moderating: Punishments
*********************************************************/
kick: 'warn',
k: 'warn',
warn: function (target, room, user) {
if (!target) return this.parse('/help warn');
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (room.isPersonal && !user.can('warn')) return this.sendReply("Warning is unavailable in group chats.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (!(targetUser in room.users)) {
return this.sendReply("User " + this.targetUsername + " is not in the room " + room.id + ".");
}
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('warn', targetUser, room)) return false;
this.addModCommand("" + targetUser.name + " was warned by " + user.name + "." + (target ? " (" + target + ")" : ""));
targetUser.send('|c|~|/warn ' + target);
this.add('|unlink|' + this.getLastIdOf(targetUser));
},
warnhelp: ["/warn OR /k [username], [reason] - Warns a user showing them the Pok\u00e9mon Showdown Rules and [reason] in an overlay. Requires: % @ # & ~"],
redirect: 'redir',
redir: function (target, room, user, connection) {
if (!target) return this.parse('/help redirect');
if (room.isPrivate || room.isPersonal) return this.sendReply("Users cannot be redirected from private or personal rooms.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
var targetRoom = Rooms.search(target);
if (!targetRoom || targetRoom.modjoin) {
return this.sendReply("The room '" + target + "' does not exist.");
}
if (!this.can('warn', targetUser, room) || !this.can('warn', targetUser, targetRoom)) return false;
if (!targetUser || !targetUser.connected) {
return this.sendReply("User " + this.targetUsername + " not found.");
}
if (targetRoom.id === "global") return this.sendReply("Users cannot be redirected to the global room.");
if (targetRoom.isPrivate || targetRoom.isPersonal) {
return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id);
}
if (Rooms.rooms[targetRoom.id].users[targetUser.userid]) {
return this.sendReply("User " + targetUser.name + " is already in the room " + targetRoom.title + "!");
}
if (!Rooms.rooms[room.id].users[targetUser.userid]) {
return this.sendReply("User " + this.targetUsername + " is not in the room " + room.id + ".");
}
if (targetUser.joinRoom(targetRoom.id) === false) return this.sendReply("User " + targetUser.name + " could not be joined to room " + targetRoom.title + ". They could be banned from the room.");
this.addModCommand("" + targetUser.name + " was redirected to room " + targetRoom.title + " by " + user.name + ".");
targetUser.leaveRoom(room);
},
redirhelp: ["/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~"],
m: 'mute',
mute: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help mute');
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
var muteDuration = ((cmd === 'hm' || cmd === 'hourmute') ? HOURMUTE_LENGTH : MUTE_LENGTH);
if (!this.can('mute', targetUser, room)) return false;
var canBeMutedFurther = ((room.getMuteTime(targetUser) || 0) <= (muteDuration * 5 / 6));
if ((room.isMuted(targetUser) && !canBeMutedFurther) || targetUser.locked || !targetUser.connected) {
var problem = " but was already " + (!targetUser.connected ? "offline" : targetUser.locked ? "locked" : "muted");
if (!target) {
return this.privateModCommand("(" + targetUser.name + " would be muted by " + user.name + problem + ".)");
}
return this.addModCommand("" + targetUser.name + " would be muted by " + user.name + problem + "." + (target ? " (" + target + ")" : ""));
}
if (targetUser in room.users) targetUser.popup("|modal|" + user.name + " has muted you in " + room.id + " for " + muteDuration.duration() + ". " + target);
this.addModCommand("" + targetUser.name + " was muted by " + user.name + " for " + muteDuration.duration() + "." + (target ? " (" + target + ")" : ""));
if (targetUser.autoconfirmed && targetUser.autoconfirmed !== targetUser.userid) this.privateModCommand("(" + targetUser.name + "'s ac account: " + targetUser.autoconfirmed + ")");
this.add('|unlink|' + this.getLastIdOf(targetUser));
room.mute(targetUser, muteDuration, false);
},
mutehelp: ["/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ # & ~"],
hm: 'hourmute',
hourmute: function (target) {
if (!target) return this.parse('/help hourmute');
this.run('mute');
},
hourmutehelp: ["/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ # & ~"],
um: 'unmute',
unmute: function (target, room, user) {
if (!target) return this.parse('/help unmute');
target = this.splitTarget(target);
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!this.can('mute', null, room)) return false;
var targetUser = this.targetUser;
var successfullyUnmuted = room.unmute(targetUser ? targetUser.userid : this.targetUsername, "Your mute in '" + room.title + "' has been lifted.");
if (successfullyUnmuted) {
this.addModCommand("" + (targetUser ? targetUser.name : successfullyUnmuted) + " was unmuted by " + user.name + ".");
} else {
this.sendReply("" + (targetUser ? targetUser.name : this.targetUsername) + " is not muted.");
}
},
unmutehelp: ["/unmute [username] - Removes mute from user. Requires: % @ # & ~"],
forcelock: 'lock',
l: 'lock',
ipmute: 'lock',
lock: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help lock');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('lock', targetUser)) return false;
if ((targetUser.locked || Users.checkBanned(targetUser.latestIp)) && !target) {
var problem = " but was already " + (targetUser.locked ? "locked" : "banned");
return this.privateModCommand("(" + targetUser.name + " would be locked by " + user.name + problem + ".)");
}
if (targetUser.confirmed) {
if (cmd === 'forcelock') {
var from = targetUser.deconfirm();
ResourceMonitor.log("[CrisisMonitor] " + targetUser.name + " was locked by " + user.name + " and demoted from " + from.join(", ") + ".");
} else {
return this.sendReply("" + targetUser.name + " is a confirmed user. If you are sure you would like to lock them use /forcelock.");
}
} else if (cmd === 'forcelock') {
return this.sendReply("Use /lock; " + targetUser.name + " is not a confirmed user.");
}
targetUser.popup("|modal|" + user.name + " has locked you from talking in chats, battles, and PMing regular users." + (target ? "\n\nReason: " + target : "") + "\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it" + (Config.appealurl ? " or you can appeal:\n" + Config.appealurl : ".") + "\n\nYour lock will expire in a few days.");
this.addModCommand("" + targetUser.name + " was locked from talking by " + user.name + "." + (target ? " (" + target + ")" : ""));
var alts = targetUser.getAlts();
var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
if (alts.length) {
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "locked alts: " + alts.join(", ") + ")");
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
var userid = this.getLastIdOf(targetUser);
this.add('|unlink|hide|' + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername));
this.globalModlog("LOCK", targetUser, " by " + user.name + (target ? ": " + target : ""));
targetUser.lock(false, userid);
return true;
},
lockhelp: ["/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ & ~"],
unlock: function (target, room, user) {
if (!target) return this.parse('/help unlock');
if (!this.can('lock')) return false;
var targetUser = Users.get(target);
var reason = '';
if (targetUser && targetUser.locked && targetUser.locked.charAt(0) === '#') {
reason = ' (' + targetUser.locked + ')';
}
var unlocked = Users.unlock(target);
if (unlocked) {
var names = Object.keys(unlocked);
this.addModCommand(names.join(", ") + " " + ((names.length > 1) ? "were" : "was") +
" unlocked by " + user.name + "." + reason);
if (!reason) this.globalModlog("UNLOCK", target, " by " + user.name);
if (targetUser) targetUser.popup("" + user.name + " has unlocked you.");
} else {
this.sendReply("User '" + target + "' is not locked.");
}
},
unlockhelp: ["/unlock [username] - Unlocks the user. Requires: % @ & ~"],
forceban: 'ban',
b: 'ban',
ban: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help ban');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('ban', targetUser)) return false;
if (Users.checkBanned(targetUser.latestIp) && !target && !targetUser.connected) {
var problem = " but was already banned";
return this.privateModCommand("(" + targetUser.name + " would be banned by " + user.name + problem + ".)");
}
if (targetUser.confirmed) {
if (cmd === 'forceban') {
var from = targetUser.deconfirm();
ResourceMonitor.log("[CrisisMonitor] " + targetUser.name + " was banned by " + user.name + " and demoted from " + from.join(", ") + ".");
} else {
return this.sendReply("" + targetUser.name + " is a confirmed user. If you are sure you would like to ban them use /forceban.");
}
} else if (cmd === 'forceban') {
return this.sendReply("Use /ban; " + targetUser.name + " is not a confirmed user.");
}
targetUser.popup("|modal|" + user.name + " has banned you." + (target ? "\n\nReason: " + target : "") + (Config.appealurl ? "\n\nIf you feel that your ban was unjustified, you can appeal:\n" + Config.appealurl : "") + "\n\nYour ban will expire in a few days.");
this.addModCommand("" + targetUser.name + " was banned by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")");
var alts = targetUser.getAlts();
var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
if (alts.length) {
var guests = 0;
alts = alts.filter(function (alt) {
if (alt.substr(0, 6) !== 'Guest ') return true;
guests++;
return false;
});
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "banned alts: " + alts.join(", ") + (guests ? " [" + guests + " guests]" : "") + ")");
for (var i = 0; i < alts.length; ++i) {
this.add('|unlink|' + toId(alts[i]));
}
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
var userid = this.getLastIdOf(targetUser);
this.add('|unlink|hide|' + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername));
targetUser.ban(false, userid);
this.globalModlog("BAN", targetUser, " by " + user.name + (target ? ": " + target : ""));
return true;
},
banhelp: ["/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: @ & ~"],
unban: function (target, room, user) {
if (!target) return this.parse('/help unban');
if (!this.can('ban')) return false;
var name = Users.unban(target);
if (name) {
this.addModCommand("" + name + " was unbanned by " + user.name + ".");
this.globalModlog("UNBAN", name, " by " + user.name);
} else {
this.sendReply("User '" + target + "' is not banned.");
}
},
unbanhelp: ["/unban [username] - Unban a user. Requires: @ & ~"],
unbanall: function (target, room, user) {
if (!this.can('rangeban')) return false;
// we have to do this the hard way since it's no longer a global
var punishKeys = ['bannedIps', 'bannedUsers', 'lockedIps', 'lockedUsers', 'lockedRanges', 'rangeLockedUsers'];
for (var i = 0; i < punishKeys.length; i++) {
var dict = Users[punishKeys[i]];
for (var entry in dict) delete dict[entry];
}
this.addModCommand("All bans and locks have been lifted by " + user.name + ".");
},
unbanallhelp: ["/unbanall - Unban all IP addresses. Requires: & ~"],
banip: function (target, room, user) {
target = target.trim();
if (!target) {
return this.parse('/help banip');
}
if (!this.can('rangeban')) return false;
if (Users.bannedIps[target] === '#ipban') return this.sendReply("The IP " + (target.charAt(target.length - 1) === '*' ? "range " : "") + target + " has already been temporarily banned.");
Users.bannedIps[target] = '#ipban';
this.addModCommand("" + user.name + " temporarily banned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target);
},
baniphelp: ["/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"],
unbanip: function (target, room, user) {
target = target.trim();
if (!target) {
return this.parse('/help unbanip');
}
if (!this.can('rangeban')) return false;
if (!Users.bannedIps[target]) {
return this.sendReply("" + target + " is not a banned IP or IP range.");
}
delete Users.bannedIps[target];
this.addModCommand("" + user.name + " unbanned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target);
},
unbaniphelp: ["/unbanip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"],
rangelock: function (target, room, user) {
if (!target) return this.sendReply("Please specify a range to lock.");
if (!this.can('rangeban')) return false;
var isIp = (target.slice(-1) === '*' ? true : false);
var range = (isIp ? target : Users.shortenHost(target));
if (Users.lockedRanges[range]) return this.sendReply("The range " + range + " has already been temporarily locked.");
Users.lockRange(range, isIp);
this.addModCommand("" + user.name + " temporarily locked the range: " + range);
},
unrangelock: 'rangeunlock',
rangeunlock: function (target, room, user) {
if (!target) return this.sendReply("Please specify a range to unlock.");
if (!this.can('rangeban')) return false;
var range = (target.slice(-1) === '*' ? target : Users.shortenHost(target));
if (!Users.lockedRanges[range]) return this.sendReply("The range " + range + " is not locked.");
Users.unlockRange(range);
this.addModCommand("" + user.name + " unlocked the range " + range + ".");
},
/*********************************************************
* Moderating: Other
*********************************************************/
mn: 'modnote',
modnote: function (target, room, user, connection) {
if (!target) return this.parse('/help modnote');
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The note is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('receiveauthmessages', null, room)) return false;
return this.privateModCommand("(" + user.name + " notes: " + target + ")");
},
modnotehelp: ["/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ # & ~"],
globalpromote: 'promote',
promote: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help promote');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
var userid = toId(this.targetUsername);
var name = targetUser ? targetUser.name : this.targetUsername;
if (!userid) return this.parse('/help promote');
var currentGroup = ((targetUser && targetUser.group) || Users.usergroups[userid] || ' ')[0];
var nextGroup = target;
if (target === 'deauth') nextGroup = Config.groupsranking[0];
if (!nextGroup) {
return this.sendReply("Please specify a group such as /globalvoice or /globaldeauth");
}
if (!Config.groups[nextGroup]) {
return this.sendReply("Group '" + nextGroup + "' does not exist.");
}
if (Config.groups[nextGroup].roomonly) {
return this.sendReply("Group '" + nextGroup + "' does not exist as a global rank.");
}
var groupName = Config.groups[nextGroup].name || "regular user";
if (currentGroup === nextGroup) {
return this.sendReply("User '" + name + "' is already a " + groupName);
}
if (!user.canPromote(currentGroup, nextGroup)) {
return this.sendReply("/" + cmd + " - Access denied.");
}
if (!Users.setOfflineGroup(name, nextGroup)) {
return this.sendReply("/promote - WARNING: This user is offline and could be unregistered. Use /forcepromote if you're sure you want to risk it.");
}
if (Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) {
this.privateModCommand("(" + name + " was demoted to " + groupName + " by " + user.name + ".)");
if (targetUser) targetUser.popup("You were demoted to " + groupName + " by " + user.name + ".");
} else {
this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + ".");
}
if (targetUser) targetUser.updateIdentity();
},
promotehelp: ["/promote [username], [group] - Promotes the user to the specified group. Requires: & ~"],
globaldemote: 'demote',
demote: function (target) {
if (!target) return this.parse('/help demote');
this.run('promote');
},
demotehelp: ["/demote [username], [group] - Demotes the user to the specified group. Requires: & ~"],
forcepromote: function (target, room, user) {
// warning: never document this command in /help
if (!this.can('forcepromote')) return false;
target = this.splitTarget(target, true);
var name = this.targetUsername;
var nextGroup = target;
if (!Config.groups[nextGroup]) return this.sendReply("Group '" + nextGroup + "' does not exist.");
if (!Users.setOfflineGroup(name, nextGroup, true)) {
return this.sendReply("/forcepromote - Don't forcepromote unless you have to.");
}
this.addModCommand("" + name + " was promoted to " + (Config.groups[nextGroup].name || "regular user") + " by " + user.name + ".");
},
devoice: 'deauth',
deauth: function (target, room, user) {
return this.parse('/demote ' + target + ', deauth');
},
deroomvoice: 'roomdeauth',
roomdevoice: 'roomdeauth',
deroomauth: 'roomdeauth',
roomdeauth: function (target, room, user) {
return this.parse('/roomdemote ' + target + ', deauth');
},
modchat: function (target, room, user) {
if (!target) return this.sendReply("Moderated chat is currently set to: " + room.modchat);
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!this.can('modchat', null, room)) return false;
if (room.modchat && room.modchat.length <= 1 && Config.groupsranking.indexOf(room.modchat) > 1 && !user.can('modchatall', null, room)) {
return this.sendReply("/modchat - Access denied for removing a setting higher than " + Config.groupsranking[1] + ".");
}
target = target.toLowerCase();
var currentModchat = room.modchat;
switch (target) {
case 'off':
case 'false':
case 'no':
case ' ':
room.modchat = false;
break;
case 'ac':
case 'autoconfirmed':
room.modchat = 'autoconfirmed';
break;
case '*':
case 'player':
target = '\u2605';
/* falls through */
default:
if (!Config.groups[target]) {
return this.parse('/help modchat');
}
if (Config.groupsranking.indexOf(target) > 1 && !user.can('modchatall', null, room)) {
return this.sendReply("/modchat - Access denied for setting higher than " + Config.groupsranking[1] + ".");
}
room.modchat = target;
break;
}
if (currentModchat === room.modchat) {
return this.sendReply("Modchat is already set to " + currentModchat + ".");
}
if (!room.modchat) {
this.add("|raw|<div class=\"broadcast-blue\"><b>Moderated chat was disabled!</b><br />Anyone may talk now.</div>");
} else {
var modchat = Tools.escapeHTML(room.modchat);
this.add("|raw|<div class=\"broadcast-red\"><b>Moderated chat was set to " + modchat + "!</b><br />Only users of rank " + modchat + " and higher can talk.</div>");
}
this.logModCommand(user.name + " set modchat to " + room.modchat);
if (room.chatRoomData) {
room.chatRoomData.modchat = room.modchat;
Rooms.global.writeChatRoomData();
}
},
modchathelp: ["/modchat [off/autoconfirmed/+/%/@/#/&/~] - Set the level of moderated chat. Requires: @ for off/autoconfirmed/+ options, # & ~ for all the options"],
declare: function (target, room, user) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
this.add('|raw|<div class="broadcast-blue"><b>' + Tools.escapeHTML(target) + '</b></div>');
this.logModCommand(user.name + " declared " + target);
},
declarehelp: ["/declare [message] - Anonymously announces a message. Requires: # & ~"],
htmldeclare: function (target, room, user) {
if (!target) return this.parse('/help htmldeclare');
if (!this.can('gdeclare', null, room)) return false;
if (!this.canTalk()) return;
this.add('|raw|<div class="broadcast-blue"><b>' + target + '</b></div>');
this.logModCommand(user.name + " declared " + target);
},
htmldeclarehelp: ["/htmldeclare [message] - Anonymously announces a message using safe HTML. Requires: ~"],
gdeclare: 'globaldeclare',
globaldeclare: function (target, room, user) {
if (!target) return this.parse('/help globaldeclare');
if (!this.can('gdeclare')) return false;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>');
}
this.logModCommand(user.name + " globally declared " + target);
},
globaldeclarehelp: ["/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~"],
cdeclare: 'chatdeclare',
chatdeclare: function (target, room, user) {
if (!target) return this.parse('/help chatdeclare');
if (!this.can('gdeclare')) return false;
for (var id in Rooms.rooms) {
if (id !== 'global') if (Rooms.rooms[id].type !== 'battle') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>');
}
this.logModCommand(user.name + " globally declared (chat level) " + target);
},
chatdeclarehelp: ["/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~"],
wall: 'announce',
announce: function (target, room, user) {
if (!target) return this.parse('/help announce');
if (!this.can('announce', null, room)) return false;
target = this.canTalk(target);
if (!target) return;
return '/announce ' + target;
},
announcehelp: ["/announce OR /wall [message] - Makes an announcement. Requires: % @ # & ~"],
fr: 'forcerename',
forcerename: function (target, room, user) {
if (!target) return this.parse('/help forcerename');
var reason = this.splitTarget(target, true);
var targetUser = this.targetUser;
if (!targetUser) {
this.splitTarget(target);
if (this.targetUser) {
return this.sendReply("User has already changed their name to '" + this.targetUser.name + "'.");
}
return this.sendReply("User '" + target + "' not found.");
}
if (!this.can('forcerename', targetUser)) return false;
var entry = targetUser.name + " was forced to choose a new name by " + user.name + (reason ? ": " + reason : "");
this.privateModCommand("(" + entry + ")");
Rooms.global.cancelSearch(targetUser);
targetUser.resetName();
targetUser.send("|nametaken||" + user.name + " considers your name inappropriate" + (reason ? ": " + reason : "."));
return true;
},
forcerenamehelp: ["/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: % @ & ~"],
hidetext: function (target, room, user) {
if (!target) return this.parse('/help hidetext');
var reason = this.splitTarget(target);
var targetUser = this.targetUser;
var name = this.targetUsername;
if (!targetUser) return this.errorReply("User '" + name + "' does not exist.");
var userid = this.getLastIdOf(targetUser);
var hidetype = '';
if (!user.can('lock', targetUser) && !user.can('ban', targetUser, room)) {
this.errorReply('/hidetext' + this.namespaces.concat(this.cmd).join(" ") + " - Access denied.");
return false;
}
if (targetUser.locked || Users.checkBanned(targetUser.latestIp)) {
hidetype = 'hide|';
} else if (room.bannedUsers[toId(name)] && room.bannedIps[targetUser.latestIp]) {
hidetype = 'roomhide|';
} else {
return this.errorReply("User '" + name + "' is not banned from this room or locked.");
}
this.addModCommand("" + targetUser.name + "'s messages were cleared from room " + room.id + " by " + user.name + ".");
this.add('|unlink|' + hidetype + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|' + hidetype + toId(this.inputUsername));
},
hidetexthelp: ["/hidetext [username] - Removes a locked or banned user's messages from chat (includes users banned from the room). Requires: % (global only), @ & ~"],
modlog: function (target, room, user, connection) {
var lines = 0;
// Specific case for modlog command. Room can be indicated with a comma, lines go after the comma.
// Otherwise, the text is defaulted to text search in current room's modlog.
var roomId = (room.id === 'staff' ? 'global' : room.id);
var hideIps = !user.can('lock');
var path = require('path');
var isWin = process.platform === 'win32';
var logPath = 'logs/modlog/';
if (target.includes(',')) {
var targets = target.split(',');
target = targets[1].trim();
roomId = toId(targets[0]) || room.id;
}
if (room.id.startsWith('battle-') || room.id.startsWith('groupchat-')) {
return this.errorReply("Battles and groupchats do not have modlogs.");
}
// Let's check the number of lines to retrieve or if it's a word instead
if (!target.match('[^0-9]')) {
lines = parseInt(target || 20, 10);
if (lines > 100) lines = 100;
}
var wordSearch = (!lines || lines < 0);
// Control if we really, really want to check all modlogs for a word.
var roomNames = '';
var filename = '';
var command = '';
if (roomId === 'all' && wordSearch) {
if (!this.can('modlog')) return;
roomNames = "all rooms";
// Get a list of all the rooms
var fileList = fs.readdirSync('logs/modlog');
for (var i = 0; i < fileList.length; ++i) {
filename += path.normalize(__dirname + '/' + logPath + fileList[i]) + ' ';
}
} else {
if (!this.can('modlog', null, Rooms.get(roomId))) return;
roomNames = "the room " + roomId;
filename = path.normalize(__dirname + '/' + logPath + 'modlog_' + roomId + '.txt');
}
// Seek for all input rooms for the lines or text
if (isWin) {
command = path.normalize(__dirname + '/lib/winmodlog') + ' tail ' + lines + ' ' + filename;
} else {
command = 'tail -' + lines + ' ' + filename;
}
var grepLimit = 100;
if (wordSearch) { // searching for a word instead
if (target.match(/^["'].+["']$/)) target = target.substring(1, target.length - 1);
if (isWin) {
command = path.normalize(__dirname + '/lib/winmodlog') + ' ws ' + grepLimit + ' "' + target.replace(/%/g, "%%").replace(/([\^"&<>\|])/g, "^$1") + '" ' + filename;
} else {
command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -i '" + target.replace(/\\/g, '\\\\\\\\').replace(/["'`]/g, '\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g, '[$&]') + "'";
}
}
// Execute the file search to see modlog
require('child_process').exec(command, function (error, stdout, stderr) {
if (error && stderr) {
connection.popup("/modlog empty on " + roomNames + " or erred");
console.log("/modlog error: " + error);
return false;
}
if (stdout && hideIps) {
stdout = stdout.replace(/\([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\)/g, '');
}
stdout = stdout.split('\n').map(function (line) {
var bracketIndex = line.indexOf(']');
var parenIndex = line.indexOf(')');
if (bracketIndex < 0) return Tools.escapeHTML(line);
var time = line.slice(1, bracketIndex);
var timestamp = new Date(time).format('{yyyy}-{MM}-{dd} {hh}:{mm}{tt}');
var parenIndex = line.indexOf(')');
var roomid = line.slice(bracketIndex + 3, parenIndex);
if (!hideIps && Config.modloglink) {
var url = Config.modloglink(time, roomid);
if (url) timestamp = '<a href="' + url + '">' + timestamp + '</a>';
}
return '<small>[' + timestamp + '] (' + roomid + ')</small>' + Tools.escapeHTML(line.slice(parenIndex + 1));
}).join('<br />');
if (lines) {
if (!stdout) {
connection.popup("The modlog is empty. (Weird.)");
} else {
connection.popup("|wide||html|<p>The last " + lines + " lines of the Moderator Log of " + roomNames + ":</p>" + stdout);
}
} else {
if (!stdout) {
connection.popup("No moderator actions containing '" + target + "' were found on " + roomNames + ".");
} else {
connection.popup("|wide||html|<p>The last " + grepLimit + " logged actions containing '" + target + "' on " + roomNames + ":</p>" + stdout);
}
}
});
},
modloghelp: ["/modlog [roomid|all], [n] - Roomid defaults to current room.",
"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' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: % @ # & ~"],
/*********************************************************
* Server management commands
*********************************************************/
hotpatch: function (target, room, user) {
if (!target) return this.parse('/help hotpatch');
if (!this.can('hotpatch')) return false;
this.logEntry(user.name + " used /hotpatch " + target);
if (target === 'chat' || target === 'commands') {
try {
CommandParser.uncacheTree('./command-parser.js');
delete require.cache[require.resolve('./commands.js')];
delete require.cache[require.resolve('./chat-plugins/info.js')];
global.CommandParser = require('./command-parser.js');
var runningTournaments = Tournaments.tournaments;
CommandParser.uncacheTree('./tournaments');
global.Tournaments = require('./tournaments');
Tournaments.tournaments = runningTournaments;
return this.sendReply("Chat commands have been hot-patched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch chat: \n" + e.stack);
}
} else if (target === 'tournaments') {
try {
var runningTournaments = Tournaments.tournaments;
CommandParser.uncacheTree('./tournaments');
global.Tournaments = require('./tournaments');
Tournaments.tournaments = runningTournaments;
return this.sendReply("Tournaments have been hot-patched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch tournaments: \n" + e.stack);
}
} else if (target === 'battles') {
Simulator.SimulatorProcess.respawn();
return this.sendReply("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.");
} else if (target === 'formats') {
try {
var toolsLoaded = !!Tools.isLoaded;
// uncache the tools.js dependency tree
CommandParser.uncacheTree('./tools.js');
// reload tools.js
global.Tools = require('./tools.js')[toolsLoaded ? 'includeData' : 'includeFormats'](); // note: this will lock up the server for a few seconds
// rebuild the formats list
Rooms.global.formatListText = Rooms.global.getFormatListText();
// respawn validator processes
TeamValidator.ValidatorProcess.respawn();
// respawn simulator processes
Simulator.SimulatorProcess.respawn();
// broadcast the new formats list to clients
Rooms.global.send(Rooms.global.formatListText);
return this.sendReply("Formats have been hotpatched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch formats: \n" + e.stack);
}
} else if (target === 'learnsets') {
try {
var toolsLoaded = !!Tools.isLoaded;
// uncache the tools.js dependency tree
CommandParser.uncacheTree('./tools.js');
// reload tools.js
global.Tools = require('./tools.js')[toolsLoaded ? 'includeData' : 'includeFormats'](); // note: this will lock up the server for a few seconds
return this.sendReply("Learnsets have been hotpatched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch learnsets: \n" + e.stack);
}
}
this.sendReply("Your hot-patch command was unrecognized.");
},
hotpatchhelp: ["Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~",
"Hot-patching has greater memory requirements than restarting.",
"/hotpatch chat - reload commands.js and the chat-plugins",
"/hotpatch battles - spawn new simulator processes",
"/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes"],
savelearnsets: function (target, room, user) {
if (!this.can('hotpatch')) return false;
fs.writeFile('data/learnsets.js', 'exports.BattleLearnsets = ' + JSON.stringify(Tools.data.Learnsets) + ";\n");
this.sendReply("learnsets.js saved.");
},
disableladder: function (target, room, user) {
if (!this.can('disableladder')) return false;
if (LoginServer.disabled) {
return this.sendReply("/disableladder - Ladder is already disabled.");
}
LoginServer.disabled = true;
this.logModCommand("The ladder was disabled by " + user.name + ".");
this.add("|raw|<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>");
},
enableladder: function (target, room, user) {
if (!this.can('disableladder')) return false;
if (!LoginServer.disabled) {
return this.sendReply("/enable - Ladder is already enabled.");
}
LoginServer.disabled = false;
this.logModCommand("The ladder was enabled by " + user.name + ".");
this.add("|raw|<div class=\"broadcast-green\"><b>The ladder is now back.</b><br />Rated games will update the ladder now.</div>");
},
lockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = true;
for (var id in Rooms.rooms) {
if (id === 'global') continue;
var curRoom = Rooms.rooms[id];
curRoom.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 (curRoom.requestKickInactive && !curRoom.battle.ended) {
curRoom.requestKickInactive(user, true);
if (curRoom.modchat !== '+') {
curRoom.modchat = '+';
curRoom.addRaw("<div class=\"broadcast-red\"><b>Moderated chat was set to +!</b><br />Only users of rank + and higher can talk.</div>");
}
}
}
this.logEntry(user.name + " used /lockdown");
},
lockdownhelp: ["/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~"],
prelockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = 'pre';
this.sendReply("Tournaments have been disabled in preparation for the server restart.");
this.logEntry(user.name + " used /prelockdown");
},
slowlockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = true;
for (var id in Rooms.rooms) {
if (id === 'global') continue;
var curRoom = Rooms.rooms[id];
if (curRoom.battle) continue;
curRoom.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>");
}
this.logEntry(user.name + " used /slowlockdown");
},
endlockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (!Rooms.global.lockdown) {
return this.sendReply("We're not under lockdown right now.");
}
if (Rooms.global.lockdown === true) {
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>");
}
} else {
this.sendReply("Preparation for the server shutdown was canceled.");
}
Rooms.global.lockdown = false;
this.logEntry(user.name + " used /endlockdown");
},
emergency: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (Config.emergency) {
return this.sendReply("We're already in emergency mode.");
}
Config.emergency = true;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("<div class=\"broadcast-red\">The server has entered emergency mode. Some features might be disabled or limited.</div>");
}
this.logEntry(user.name + " used /emergency");
},
endemergency: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (!Config.emergency) {
return this.sendReply("We're not in emergency mode.");
}
Config.emergency = false;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("<div class=\"broadcast-green\"><b>The server is no longer in emergency mode.</b></div>");
}
this.logEntry(user.name + " used /endemergency");
},
kill: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (Rooms.global.lockdown !== true) {
return this.sendReply("For safety reasons, /kill can only be used during lockdown.");
}
if (CommandParser.updateServerLock) {
return this.sendReply("Wait for /updateserver to finish before using /kill.");
}
for (var i in Sockets.workers) {
Sockets.workers[i].kill();
}
if (!room.destroyLog) {
process.exit();
return;
}
room.destroyLog(function () {
room.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);
},
killhelp: ["/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: ~"],
loadbanlist: function (target, room, user, connection) {
if (!this.can('hotpatch')) return false;
connection.sendTo(room, "Loading ipbans.txt...");
fs.readFile('config/ipbans.txt', function (err, data) {
if (err) return;
data = ('' + data).split('\n');
var rangebans = [];
for (var i = 0; i < data.length; ++i) {
var line = data[i].split('#')[0].trim();
if (!line) continue;
if (line.includes('/')) {
rangebans.push(line);
} else if (line && !Users.bannedIps[line]) {
Users.bannedIps[line] = '#ipban';
}
}
Users.checkRangeBanned = Cidr.checker(rangebans);
connection.sendTo(room, "ipbans.txt has been reloaded.");
});
},
loadbanlisthelp: ["/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: ~"],
refreshpage: function (target, room, user) {
if (!this.can('hotpatch')) return false;
Rooms.global.send('|refresh|');
this.logEntry(user.name + " used /refreshpage");
},
updateserver: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/updateserver - Access denied.");
}
if (CommandParser.updateServerLock) {
return this.sendReply("/updateserver - Another update is already in progress.");
}
CommandParser.updateServerLock = true;
var logQueue = [];
logQueue.push(user.name + " used /updateserver");
connection.sendTo(room, "updating...");
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).
connection.sendTo(room, "" + error);
logQueue.push("" + error);
logQueue.forEach(function (line) {
room.logEntry(line);
});
CommandParser.updateServerLock = false;
return;
}
}
var entry = "Running `" + cmd + "`";
connection.sendTo(room, entry);
logQueue.push(entry);
exec(cmd, function (error, stdout, stderr) {
("" + stdout + stderr).split("\n").forEach(function (s) {
connection.sendTo(room, s);
logQueue.push(s);
});
logQueue.forEach(function (line) {
room.logEntry(line);
});
CommandParser.updateServerLock = false;
});
});
},
crashfixed: function (target, room, user) {
if (Rooms.global.lockdown !== true) {
return this.sendReply('/crashfixed - There is no active crash.');
}
if (!this.can('hotpatch')) return false;
Rooms.global.lockdown = false;
if (Rooms.lobby) {
Rooms.lobby.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>");
}
this.logEntry(user.name + " used /crashfixed");
},
crashfixedhelp: ["/crashfixed - Ends the active lockdown caused by a crash without the need of a restart. Requires: ~"],
'memusage': 'memoryusage',
memoryusage: function (target) {
if (!this.can('hotpatch')) return false;
var memUsage = process.memoryUsage();
var results = [memUsage.rss, memUsage.heapUsed, memUsage.heapTotal];
var units = ["B", "KiB", "MiB", "GiB", "TiB"];
for (var i = 0; i < results.length; i++) {
var unitIndex = Math.floor(Math.log2(results[i]) / 10); // 2^10 base log
results[i] = "" + (results[i] / Math.pow(2, 10 * unitIndex)).toFixed(2) + " " + units[unitIndex];
}
this.sendReply("Main process. RSS: " + results[0] + ". Heap: " + results[1] + " / " + results[2] + ".");
},
bash: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/bash - Access denied.");
}
var exec = require('child_process').exec;
exec(target, function (error, stdout, stderr) {
connection.sendTo(room, ("" + stdout + stderr));
});
},
eval: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/eval - Access denied.");
}
if (!this.canBroadcast()) return;
if (!this.broadcasting) this.sendReply('||>> ' + target);
try {
var battle = room.battle;
var me = user;
this.sendReply('||<< ' + eval(target));
} catch (e) {
this.sendReply('||<< error: ' + e.message);
var stack = '||' + ('' + e.stack).replace(/\n/g, '\n||');
connection.sendTo(room, stack);
}
},
evalbattle: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/evalbattle - Access denied.");
}
if (!this.canBroadcast()) return;
if (!room.battle) {
return this.sendReply("/evalbattle - This isn't a battle room.");
}
room.battle.send('eval', target.replace(/\n/g, '\f'));
},
ebat: 'editbattle',
editbattle: function (target, room, user) {
if (!this.can('forcewin')) return false;
if (!target) return this.parse('/help editbattle');
if (!room.battle) {
this.sendReply("/editbattle - This is not a battle room.");
return false;
}
var cmd;
var spaceIndex = target.indexOf(' ');
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex).toLowerCase();
target = target.substr(spaceIndex + 1);
} else {
cmd = target.toLowerCase();
target = '';
}
if (cmd.charAt(cmd.length - 1) === ',') cmd = cmd.slice(0, -1);
var targets = target.split(',');
function getPlayer(input) {
if (room.battle.playerids[0] === toId(input)) return 'p1';
if (room.battle.playerids[1] === toId(input)) return 'p2';
if (input.includes('1')) return 'p1';
if (input.includes('2')) return 'p2';
return 'p3';
}
function getPokemon(input) {
if (/^[0-9]+$/.test(input)) {
return '.pokemon[' + (parseInt(input) - 1) + ']';
}
return ".pokemon.find(function(p){return p.speciesid==='" + toId(targets[1]) + "'})";
}
switch (cmd) {
case 'hp':
case 'h':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.sethp(" + parseInt(targets[2]) + ");if (p.isActive)battle.add('-damage',p,p.getHealth);");
break;
case 'status':
case 's':
room.battle.send('eval', "var pl=" + getPlayer(targets[0]) + ";var p=pl" + getPokemon(targets[1]) + ";p.setStatus('" + toId(targets[2]) + "');if (!p.isActive){battle.add('','please ignore the above');battle.add('-status',pl.active[0],pl.active[0].status,'[silent]');}");
break;
case 'pp':
room.battle.send('eval', "var pl=" + getPlayer(targets[0]) + ";var p=pl" + getPokemon(targets[1]) + ";p.moveset[p.moves.indexOf('" + toId(targets[2]) + "')].pp = " + parseInt(targets[3]));
break;
case 'boost':
case 'b':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";battle.boost({" + toId(targets[2]) + ":" + parseInt(targets[3]) + "},p)");
break;
case 'volatile':
case 'v':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.addVolatile('" + toId(targets[2]) + "')");
break;
case 'sidecondition':
case 'sc':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + ".addSideCondition('" + toId(targets[1]) + "')");
break;
case 'fieldcondition': case 'pseudoweather':
case 'fc':
room.battle.send('eval', "battle.addPseudoWeather('" + toId(targets[0]) + "')");
break;
case 'weather':
case 'w':
room.battle.send('eval', "battle.setWeather('" + toId(targets[0]) + "')");
break;
case 'terrain':
case 't':
room.battle.send('eval', "battle.setTerrain('" + toId(targets[0]) + "')");
break;
default:
this.errorReply("Unknown editbattle command: " + cmd);
break;
}
},
editbattlehelp: ["/editbattle hp [player], [pokemon], [hp]",
"/editbattle status [player], [pokemon], [status]",
"/editbattle pp [player], [pokemon], [move], [pp]",
"/editbattle boost [player], [pokemon], [stat], [amount]",
"/editbattle volatile [player], [pokemon], [volatile]",
"/editbattle sidecondition [player], [sidecondition]",
"/editbattle fieldcondition [fieldcondition]",
"/editbattle weather [weather]",
"/editbattle terrain [terrain]",
"Short forms: /ebat h OR s OR pp OR b OR v OR sc OR fc OR w OR t",
"[player] must be a username or number, [pokemon] must be species name or number (not nickname), [move] must be move name"],
/*********************************************************
* Battle commands
*********************************************************/
forfeit: function (target, room, user) {
if (!room.battle) {
return this.sendReply("There's nothing to forfeit here.");
}
if (!room.forfeit(user)) {
return this.sendReply("You can't forfeit this battle.");
}
},
savereplay: function (target, room, user, connection) {
if (!room || !room.battle) return;
var logidx = 0; // 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');
var players = room.battle.lastPlayers.map(Users.getExact);
LoginServer.request('prepreplay', {
id: room.id.substr(7),
loghash: datahash,
p1: players[0] ? players[0].name : room.battle.lastPlayers[0],
p2: players[1] ? players[1].name : room.battle.lastPlayers[1],
format: room.format
}, function (success) {
if (success && success.errorip) {
connection.popup("This server's request IP " + success.errorip + " is not a registered server.");
return;
}
connection.send('|queryresponse|savereplay|' + JSON.stringify({
log: data,
id: room.id.substr(7)
}));
});
},
mv: 'move',
attack: 'move',
move: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', 'move ' + target);
},
sw: 'switch',
switch: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', 'switch ' + parseInt(target, 10));
},
choose: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', target);
},
undo: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'undo', target);
},
team: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', 'team ' + target);
},
addplayer: function (target, room, user) {
if (!target) return this.parse('/help addplayer');
if (!room.battle) return this.sendReply("You can only do this in battle rooms.");
if (room.rated) return this.sendReply("You can only add a Player to unrated battles.");
target = this.splitTarget(target, true);
var userid = toId(this.targetUsername);
var targetUser = this.targetUser;
var name = this.targetUsername;
if (!targetUser) return this.sendReply("User " + name + " not found.");
if (targetUser.can('joinbattle', null, room)) {
return this.sendReply("" + name + " can already join battles as a Player.");
}
if (!this.can('joinbattle', null, room)) return;
room.auth[targetUser.userid] = '\u2605';
this.addModCommand("" + name + " was promoted to Player by " + user.name + ".");
},
addplayerhelp: ["/addplayer [username] - Allow the specified user to join the battle as a player."],
joinbattle: function (target, room, user) {
if (!room.joinBattle) return this.sendReply("You can only do this in battle rooms.");
if (!user.can('joinbattle', null, room)) return this.popupReply("You must be a set as a player to join a battle you didn't start. Ask a player to use /addplayer on you to join this battle.");
room.joinBattle(user);
},
partbattle: 'leavebattle',
leavebattle: function (target, room, user) {
if (!room.leaveBattle) return this.sendReply("You can only do this in battle rooms.");
room.leaveBattle(user);
},
kickbattle: function (target, room, user) {
if (!room.leaveBattle) return this.sendReply("You can only do this in battle rooms.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.sendReply("User " + this.targetUsername + " not found.");
}
if (!this.can('kick', targetUser)) return false;
if (room.leaveBattle(targetUser)) {
this.addModCommand("" + targetUser.name + " was kicked from a battle by " + user.name + (target ? " (" + target + ")" : ""));
} else {
this.sendReply("/kickbattle - User isn't in battle.");
}
},
kickbattlehelp: ["/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: % @ & ~"],
kickinactive: function (target, room, user) {
if (room.requestKickInactive) {
room.requestKickInactive(user);
} else {
this.sendReply("You can only kick inactive players from inside a room.");
}
},
timer: function (target, room, user) {
target = toId(target);
if (room.requestKickInactive) {
if (target === 'off' || target === 'false' || target === 'stop') {
var canForceTimer = user.can('timer', null, room);
if (room.resetTimer) {
room.stopKickInactive(user, canForceTimer);
if (canForceTimer) room.send('|inactiveoff|Timer was turned off by staff. Please do not turn it back on until our staff say it\'s okay');
}
} else if (target === 'on' || target === 'true' || !target) {
room.requestKickInactive(user, user.can('timer'));
} else {
this.sendReply("'" + target + "' is not a recognized timer state.");
}
} else {
this.sendReply("You can only set the timer from inside a battle room.");
}
},
autotimer: 'forcetimer',
forcetimer: function (target, room, user) {
target = toId(target);
if (!this.can('autotimer')) return;
if (target === 'off' || target === 'false' || target === 'stop') {
Config.forcetimer = false;
this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by " + user.name + ")");
} else if (target === 'on' || target === 'true' || !target) {
Config.forcetimer = true;
this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by " + user.name + ")");
} else {
this.sendReply("'" + target + "' is not a recognized forcetimer setting.");
}
},
forcetie: 'forcewin',
forcewin: function (target, room, user) {
if (!this.can('forcewin')) return false;
if (!room.battle) {
this.sendReply("/forcewin - This is not a battle room.");
return false;
}
room.battle.endType = 'forced';
if (!target) {
room.battle.tie();
this.logModCommand(user.name + " forced a tie.");
return false;
}
var targetUser = Users.getExact(target);
if (!targetUser) return this.sendReply("User '" + target + "' not found.");
target = targetUser ? targetUser.userid : '';
if (target) {
room.battle.win(targetUser);
this.logModCommand(user.name + " forced a win for " + target + ".");
}
},
forcewinhelp: ["/forcetie - Forces the current match to end in a tie. Requires: & ~",
"/forcewin [user] - Forces the current match to end in a win for a user. Requires: & ~"],
/*********************************************************
* Challenging and searching commands
*********************************************************/
cancelsearch: 'search',
search: function (target, room, user) {
if (target) {
if (Config.pmmodchat) {
var userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to search for a battle.");
return false;
}
}
Rooms.global.searchBattle(user, target);
} else {
Rooms.global.cancelSearch(user);
}
},
chall: 'challenge',
challenge: function (target, room, user, connection) {
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.popupReply("The user '" + this.targetUsername + "' was not found.");
}
if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) {
return this.popupReply("The user '" + this.targetUsername + "' is not accepting challenges right now.");
}
if (Config.pmmodchat) {
var userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to challenge users.");
return false;
}
}
user.prepBattle(Tools.getFormat(target).id, 'challenge', connection, function (result) {
if (result) user.makeChallenge(targetUser, target);
});
},
bch: 'blockchallenges',
blockchall: 'blockchallenges',
blockchalls: 'blockchallenges',
blockchallenges: function (target, room, user) {
if (user.blockChallenges) return this.sendReply("You are already blocking challenges!");
user.blockChallenges = true;
this.sendReply("You are now blocking all incoming challenge requests.");
},
blockchallengeshelp: ["/blockchallenges - Blocks challenges so no one can challenge you. Unblock them with /unblockchallenges."],
unbch: 'allowchallenges',
unblockchall: 'allowchallenges',
unblockchalls: 'allowchallenges',
unblockchallenges: 'allowchallenges',
allowchallenges: function (target, room, user) {
if (!user.blockChallenges) return this.sendReply("You are already available for challenges!");
user.blockChallenges = false;
this.sendReply("You are available for challenges from now on.");
},
allowchallengeshelp: ["/unblockchallenges - Unblocks challenges so you can be challenged again. Block them with /blockchallenges."],
cchall: 'cancelChallenge',
cancelchallenge: function (target, room, user) {
user.cancelChallengeTo(target);
},
accept: function (target, room, user, connection) {
var userid = toId(target);
var format = '';
if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format;
if (!format) {
this.popupReply(target + " cancelled their challenge before you could accept it.");
return false;
}
user.prepBattle(Tools.getFormat(format).id, 'challenge', connection, function (result) {
if (result) user.acceptChallengeFrom(userid);
});
},
reject: function (target, room, user) {
user.rejectChallengeFrom(toId(target));
},
saveteam: 'useteam',
utm: 'useteam',
useteam: function (target, room, user) {
user.team = target;
},
vtm: function (target, room, user, connection) {
if (ResourceMonitor.countPrepBattle(connection.ip, user.name)) {
connection.popup("Due to high load, you are limited to 6 team validations every 3 minutes.");
return;
}
var format = Tools.getFormat(target);
if (format.effectType !== 'Format') format = Tools.getFormat('Anything Goes');
if (format.effectType !== 'Format') {
connection.popup("Please provide a valid format.");
return;
}
TeamValidator.validateTeam(format.id, user.team, function (success, details) {
if (success) {
connection.popup("Your team is valid for " + format.name + ".");
} else {
connection.popup("Your team was rejected for the following reasons:\n\n- " + details.replace(/\n/g, '\n- '));
}
});
},
/*********************************************************
* Low-level
*********************************************************/
cmd: 'query',
query: function (target, room, user, connection) {
// Avoid guest users to use the cmd errors to ease the app-layer attacks in emergency mode
var trustable = (!Config.emergency || (user.named && user.registered));
if (Config.emergency && ResourceMonitor.countCmd(connection.ip, user.name)) return false;
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') {
var targetUser = Users.get(target);
if (!trustable || !targetUser) {
connection.send('|queryresponse|userdetails|' + JSON.stringify({
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 || targetRoom.isPrivate) 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 = {
userid: targetUser.userid,
avatar: targetUser.avatar,
rooms: roomList
};
connection.send('|queryresponse|userdetails|' + JSON.stringify(userdetails));
} else if (cmd === 'roomlist') {
if (!trustable) return false;
connection.send('|queryresponse|roomlist|' + JSON.stringify({
rooms: Rooms.global.getRoomList(target)
}));
} else if (cmd === 'rooms') {
if (!trustable) return false;
connection.send('|queryresponse|rooms|' + JSON.stringify(
Rooms.global.getRooms(user)
));
} else if (cmd === 'laddertop') {
if (!trustable) return false;
Ladders(target).getTop().then(function (result) {
connection.send('|queryresponse|laddertop|' + JSON.stringify(result));
});
} else {
// default to sending null
if (!trustable) return false;
connection.send('|queryresponse|' + cmd + '|null');
}
},
trn: function (target, room, user, connection) {
var commaIndex = target.indexOf(',');
var targetName = target;
var targetRegistered = false;
var targetToken = '';
if (commaIndex >= 0) {
targetName = target.substr(0, commaIndex);
target = target.substr(commaIndex + 1);
commaIndex = target.indexOf(',');
targetRegistered = target;
if (commaIndex >= 0) {
targetRegistered = !!parseInt(target.substr(0, commaIndex), 10);
targetToken = target.substr(commaIndex + 1);
}
}
user.rename(targetName, targetToken, targetRegistered, connection);
},
a: function (target, room, user) {
if (!this.can('rawpacket')) return false;
// secret sysop command
room.add(target);
},
/*********************************************************
* Help commands
*********************************************************/
commands: 'help',
h: 'help',
'?': 'help',
help: function (target, room, user) {
target = target.toLowerCase();
// overall
if (target === 'help' || target === 'h' || target === '?' || target === 'commands') {
// TRADUCIDO PARA POKEFABRICA
this.sendReply("/help o /h o /? - Te resolverá dudas.");
} else if (!target) {
this.sendReply("COMMANDOS: /nick, /avatar, /rating, /whois, /msg, /reply, /ignore, /away, /back, /timestamps, /highlight, /helado, /emoticons, /slap, /twitter");
this.sendReply("COMANDOS INFORMATIVOS: /data, /dexsearch, /movesearch, /groups, /faq, /reglas, /intro, /formatshelp, /othermetas, /learn, /analysis, /calc, /pxpmetas, /pkfintro, /lideres, /staff (reemplaza con ! para hacer que se muestre a todos. Pero para ello requiere: + % @ # & ~)");
this.sendReply("COMANDOS PxP BOT: .about, .say, .tell, .seen, .salt, .whois, .helix, .rps");
if (user.group !== Config.groupsranking[0]) {
this.sendReply("DRIVER COMMANDS: /salahelp, /kick, /warn, /mute, /hourmute, /unmute, /alts, /forcerename, /modlog, /modnote, /lock, /unlock, /announce, /redirect");
this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip, /modchat");
this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /host, /unbanall");
}
this.sendReply("Para una vista general de los comandos de la sala, usa /roomhelp (no puede ser usado en Looby ni en batallas)");
this.sendReply("Para detalles de un comando específico, usa algo como: /help data");
// TRADUCIDO PARA POKEFABRICA
} else {
var altCommandHelp;
var helpCmd;
var targets = target.split(' ');
var allCommands = CommandParser.commands;
if (typeof allCommands[target] === 'string') {
// If a function changes with command name, help for that command name will be searched first.
altCommandHelp = target + 'help';
if (altCommandHelp in allCommands) {
helpCmd = altCommandHelp;
} else {
helpCmd = allCommands[target] + 'help';
}
} else if (targets.length > 1 && typeof allCommands[targets[0]] === 'object') {
// Handle internal namespace commands
var helpCmd = targets[targets.length - 1] + 'help';
var namespace = allCommands[targets[0]];
for (var i = 1; i < targets.length - 1; i++) {
if (!namespace[targets[i]]) return this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help");
namespace = namespace[targets[i]];
}
if (typeof namespace[helpCmd] === 'object') {
return this.sendReply(namespace[helpCmd].join('\n'));
} else if (typeof namespace[helpCmd] === 'function') {
return this.parse('/' + targets.slice(0, targets.length - 1).concat(helpCmd).join(' '));
} else {
return this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help");
}
} else {
helpCmd = target + 'help';
}
if (helpCmd in allCommands) {
if (typeof allCommands[helpCmd] === 'function') {
// If the help command is a function, parse it instead
this.parse('/' + helpCmd);
} else if (Array.isArray(allCommands[helpCmd])) {
this.sendReply(allCommands[helpCmd].join('\n'));
}
} else {
this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help");
}
}
}
};
|
'use strict';
const Support = require('../support');
const DataTypes = require('../../../lib/data-types');
const chai = require('chai');
const sinon = require('sinon');
const expect = chai.expect;
const current = Support.sequelize;
const _ = require('lodash');
describe(Support.getTestDialectTeaser('Model'), () => {
describe('update', () => {
beforeEach(async function() {
this.Account = this.sequelize.define('Account', {
ownerId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'owner_id'
},
name: {
type: DataTypes.STRING
}
});
await this.Account.sync({ force: true });
});
it('should only update the passed fields', async function() {
const account = await this.Account
.create({ ownerId: 2 });
await this.Account.update({
name: Math.random().toString()
}, {
where: {
id: account.get('id')
}
});
});
describe('skips update query', () => {
it('if no data to update', async function() {
const spy = sinon.spy();
await this.Account.create({ ownerId: 3 });
const result = await this.Account.update({
unknownField: 'haha'
}, {
where: {
ownerId: 3
},
logging: spy
});
expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false;
});
it('skips when timestamps disabled', async function() {
const Model = this.sequelize.define('Model', {
ownerId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'owner_id'
},
name: {
type: DataTypes.STRING
}
}, {
timestamps: false
});
const spy = sinon.spy();
await Model.sync({ force: true });
await Model.create({ ownerId: 3 });
const result = await Model.update({
unknownField: 'haha'
}, {
where: {
ownerId: 3
},
logging: spy
});
expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false;
});
});
it('changed should be false after reload', async function() {
const account0 = await this.Account.create({ ownerId: 2, name: 'foo' });
account0.name = 'bar';
expect(account0.changed()[0]).to.equal('name');
const account = await account0.reload();
expect(account.changed()).to.equal(false);
});
it('should ignore undefined values without throwing not null validation', async function() {
const ownerId = 2;
const account0 = await this.Account.create({
ownerId,
name: Math.random().toString()
});
await this.Account.update({
name: Math.random().toString(),
ownerId: undefined
}, {
where: {
id: account0.get('id')
}
});
const account = await this.Account.findOne();
expect(account.ownerId).to.be.equal(ownerId);
});
if (_.get(current.dialect.supports, 'returnValues.returning')) {
it('should return the updated record', async function() {
const account = await this.Account.create({ ownerId: 2 });
const [, accounts] = await this.Account.update({ name: 'FooBar' }, {
where: {
id: account.get('id')
},
returning: true
});
const firstAcc = accounts[0];
expect(firstAcc.ownerId).to.be.equal(2);
expect(firstAcc.name).to.be.equal('FooBar');
});
}
if (current.dialect.supports['LIMIT ON UPDATE']) {
it('should only update one row', async function() {
await this.Account.create({
ownerId: 2,
name: 'Account Name 1'
});
await this.Account.create({
ownerId: 2,
name: 'Account Name 2'
});
await this.Account.create({
ownerId: 2,
name: 'Account Name 3'
});
const options = {
where: {
ownerId: 2
},
limit: 1
};
const account = await this.Account.update({ name: 'New Name' }, options);
expect(account[0]).to.equal(1);
});
}
});
});
|
// @flow
import React, { Component } from 'react'
import { View, StatusBar } from 'react-native'
import NavigationRouter from '../Navigation/NavigationRouter'
import { connect } from 'react-redux'
import StartupActions from '../Redux/StartupRedux'
import ReduxPersist from '../Config/ReduxPersist'
// Styles
import styles from './Styles/RootContainerStyle'
class RootContainer extends Component {
componentDidMount () {
// if redux persist is not active fire startup action
if (!ReduxPersist.active) {
this.props.startup()
}
}
render () {
return (
<View style={styles.applicationView}>
<StatusBar barStyle='light-content' />
<NavigationRouter />
</View>
)
}
}
const mapStateToDispatch = (dispatch) => ({
startup: () => dispatch(StartupActions.startup())
})
export default connect(null, mapStateToDispatch)(RootContainer)
|
document.onmousemove = moveDefence;
var width = 1200;
var height = 600;
var ballPerSeconds = 1;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var allBalls = new Array();
var defence = {
start: 0,
end: (Math.PI) / 3,
jiao: 0
};
var HP = 100;
var draw = drawInGame;
var score = 0;
function moveDefence(evt) {
if (!evt) {
evt = window.event
}
var xx = evt.clientX - width * 0.5;
var yy = evt.clientY - height * 0.5;
if (yy >= 0 && xx >= 0) {
defence.jiao = Math.atan(yy / xx)
}
if (yy >= 0 && xx < 0) {
defence.jiao = Math.PI + Math.atan(yy / xx)
}
if (yy < 0 && xx >= 0) {
defence.jiao = Math.atan(yy / xx)
}
if (yy < 0 && xx < 0) {
defence.jiao = Math.atan(yy / xx) - Math.PI
}
defence.start = defence.jiao - (Math.PI / 3);
defence.end = defence.jiao + (Math.PI / 3)
}
function Ball() {
if (Math.random() <= 0.25) {
this.x = 2;
this.y = height * Math.random()
}
if ((Math.random() > 0.25) && (Math.random() <= 0.5)) {
this.x = 998;
this.y = height * Math.random()
}
if ((Math.random() < 0.75) && (Math.random() > 0.5)) {
this.y = 798;
this.x = width * Math.random()
}
if (Math.random() >= 0.75) {
this.y = 2;
this.x = width * Math.random()
}
this.act = function() {
this.x = this.x + 10;
this.y = this.y + 10
}
}
function create() {
var cre;
for (cre = 0; cre < ballPerSeconds; cre++) {
var ball = new Ball();
allBalls.push(ball)
}
}
function drawEnd() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, height);
ctx.font = "Bold 60px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText("游戏结束", width * 0.5, height * 0.5);
ctx.font = "Bold 40px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText("得分:", width * 0.5, height * 0.5 + 60);
ctx.font = "Bold 40px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText(score.toString(), width * 0.5, height * 0.5 + 100)
}
function drawInGame() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, height);
var i;
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 60, defence.start, defence.end, false);
ctx.fillStyle = "#00A67C";
ctx.fill();
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 56, 0, Math.PI * 2, true);
ctx.fillStyle = "#000000";
ctx.fill();
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 5, 0, Math.PI * 2, true);
ctx.fillStyle = "#B7F200";
ctx.fill();
for (i = 0; i < allBalls.length; i++) {
ctx.beginPath();
ctx.arc(allBalls[i].x, allBalls[i].y, 5, 0, Math.PI * 2, true);
ctx.fillStyle = "#EF002A";
ctx.fill()
}
ctx.fillStyle = "#DE0052";
ctx.fillRect(0, 0, HP * 3, 25);
ctx.font = "Bold 20px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#FFFFFF";
ctx.fillText(HP.toString(), 20, 20);
ctx.font = "Bold 20px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#EE6B9C";
scoretext = "得分:" + score.toString();
ctx.fillText(scoretext, 20, 50)
}
function act() {
for (var i = 0; i < allBalls.length; i++) {
var ax = width * 0.5 - allBalls[i].x;
var by = height * 0.5 - allBalls[i].y;
var movex = 1.5 * ax * (1.5 / Math.sqrt(ax * ax + by * by));
var movey = 1.5 * by * (1.5 / Math.sqrt(ax * ax + by * by));
allBalls[i].x = allBalls[i].x + movex;
allBalls[i].y = allBalls[i].y + movey
}
}
function check() {
for (var i = 0; i < allBalls.length; i++) {
var ax = allBalls[i].x - width * 0.5;
var by = allBalls[i].y - height * 0.5;
var distance = Math.sqrt(ax * ax + by * by);
var angel;
if (by >= 0 && ax >= 0) {
angel = Math.atan(by / ax)
}
if (by >= 0 && ax < 0) {
angel = Math.PI + Math.atan(by / ax)
}
if (by < 0 && ax >= 0) {
angel = Math.atan(by / ax)
}
if (by < 0 && ax < 0) {
angel = Math.atan(by / ax) - Math.PI
}
if (distance <= 63 && distance >= 57 && ((angel > defence.start && angel < defence.end) || (angel + 2 * Math.PI > defence.start && angel + 2 * Math.PI < defence.end) || (angel - 2 * Math.PI > defence.start && angel - 2 * Math.PI < defence.end))) {
allBalls.splice(i, 1);
if (HP < 100)
HP = HP + 2;
score = score + Math.floor(1000 / HP)
}
if (distance <= 5) {
allBalls.splice(i, 1);
HP = HP - 10;
if (HP < 0) {
draw = drawEnd;
window.clearInterval(int)
}
}
}
}
function start() {
act();
check();
draw()
}
var int = setInterval("start()", 30);
setInterval("create()", 500);
|
/********************** tine translations of Setup**********************/
Locale.Gettext.prototype._msgs['./LC_MESSAGES/Setup'] = new Locale.Gettext.PO(({
""
: "Project-Id-Version: Tine 2.0\nPOT-Creation-Date: 2008-05-17 22:12+0100\nPO-Revision-Date: 2012-09-19 08:58+0000\nLast-Translator: corneliusweiss <[email protected]>\nLanguage-Team: Russian (http://www.transifex.com/projects/p/tine20/language/ru/)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: 8bit\nLanguage: ru\nPlural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\nX-Poedit-Country: GB\nX-Poedit-Language: en\nX-Poedit-SourceCharset: utf-8\n"
, "Name"
: "Имя"
, "Enabled"
: "Позволенный"
, "Order"
: "Последовательность"
, "Installed Version"
: "Установленная версия"
, "Available Version"
: "Доступная версия"
, "Status"
: "Статус"
, "Depends on"
: "Зависит от"
, "Install application"
: "Установить приложение"
, "Uninstall application"
: "Удалить приложение"
, "Update application"
: "Обновить приложение"
, "Go to {0} login"
: ""
, "uninstall"
: "удалить"
, "Do you really want to uninstall the application(s)?"
: "Вы действительно хотите удалить приложение(я)?"
, "This may take a while"
: "Это может занять некоторое время"
, "Dependency Violation"
: ""
, "Delete all existing users and groups"
: "Удалить всех существующих пользователей и группы"
, "Switching from SQL to LDAP will delete all existing User Accounts, Groups and Roles. Do you really want to switch the accounts storage backend to LDAP ?"
: ""
, "Backend"
: ""
, "Initial Admin User"
: ""
, "Initial admin login name"
: ""
, "Initial admin Password"
: ""
, "Password confirmation"
: "Подтверждение пароля"
, "Authentication provider"
: "Проверка подлинности поставщика"
, "Try to split username"
: "Попробуйте разделить имя пользователя"
, "Yes"
: "Да"
, "No"
: "Нет"
, "Account canonical form"
: ""
, "Account domain name "
: ""
, "Account domain short name"
: ""
, "Host"
: "Хост"
, "Port"
: "Порт"
, "Login name"
: ""
, "Password"
: "Пароль"
, "Bind requires DN"
: ""
, "Base DN"
: ""
, "Search filter"
: "Фильтр поиска"
, "Hostname"
: "Имя узла"
, "Secure Connection"
: "Безопасное подключение"
, "None"
: "Нет"
, "TLS"
: "TLS"
, "SSL"
: "SSL"
, "Append domain to login name"
: ""
, "Accounts storage"
: ""
, "Default user group name"
: ""
, "Default admin group name"
: ""
, "User DN"
: ""
, "User Filter"
: "Фильтр пользователей"
, "User Search Scope"
: ""
, "Groups DN"
: "DN групп"
, "Group Filter"
: "Фильтр группы"
, "Group Search Scope"
: ""
, "Password encoding"
: ""
, "Use Rfc 2307 bis"
: "Использовать Rfc 2307 bis"
, "Min User Id"
: "Мин ID пользователя"
, "Max User Id"
: "Макс ID пользователя"
, "Min Group Id"
: "Минимальный ID группы"
, "Max Group Id"
: "Максимальный ID группы"
, "Group UUID Attribute name"
: ""
, "User UUID Attribute name"
: ""
, "Readonly access"
: ""
, "Password Settings"
: ""
, "User can change password"
: "Пользователь должен сменить пароль"
, "Enable password policy"
: ""
, "Only ASCII"
: ""
, "Minimum length"
: ""
, "Minimum word chars"
: ""
, "Minimum uppercase chars"
: ""
, "Minimum special chars"
: ""
, "Minimum numbers"
: ""
, "Redirect Settings"
: ""
, "Redirect Url (redirect to login screen if empty)"
: ""
, "Redirect Always (if No, only redirect after logout)"
: ""
, "Redirect to referring site, if exists"
: ""
, "Save config and install"
: ""
, "Save config"
: "Сохранить конфигурацию"
, "Passwords don't match"
: "Пароли не совпадают"
, "Should not be empty"
: "Не должен быть пустым"
, "File"
: "Файл"
, "Adapter"
: "Адаптер"
, "Setup Authentication"
: "Аутентификация установки"
, "Username"
: "Имя пользователя"
, "Database"
: "База данных"
, "User"
: "Пользователь"
, "Prefix"
: "Префикс"
, "Logging"
: "Регистрация"
, "Filename"
: "Имя файла"
, "Priority"
: "Приоритет"
, "Caching"
: "Кэширование"
, "Path"
: "Путь"
, "Lifetime (seconds)"
: "Время жизни (секунд)"
, "Temporary files"
: "Временные файлы"
, "Temporary Files Path"
: "Путь к временным файлам"
, "Session"
: "Сессия"
, "Filestore directory"
: "Каталог хранилища файлов"
, "Filestore Path"
: ""
, "Addressbook Map panel"
: ""
, "Map panel"
: ""
, "disabled"
: "отключен"
, "enabled"
: "включен"
, "Config file is not writable"
: "Config файл защищен от записи"
, "Download config file"
: "Загрузить файл конфигурации"
, "Standard IMAP"
: "Стандартный IMAP"
, "Standard SMTP"
: "Стандартный SMTP"
, "Imap"
: "Imap"
, "Use system account"
: "Использование системной учетной записи"
, "Cyrus Admin"
: ""
, "Cyrus Admin Password"
: ""
, "Smtp"
: "Smtp"
, "Authentication"
: ""
, "Login"
: ""
, "Plain"
: ""
, "Primary Domain"
: ""
, "Secondary Domains (comma separated)"
: ""
, "Notifications service address"
: ""
, "Notification Username"
: ""
, "Notification Password"
: ""
, "Notifications local client (hostname or IP address)"
: ""
, "SIEVE"
: ""
, "MySql Hostname"
: ""
, "MySql Database"
: "База данных MySql"
, "MySql User"
: "Пользователь MySql"
, "MySql Password"
: "Пароль MySql"
, "MySql Port"
: "Порт MySql"
, "User or UID"
: "Пользователь или UID"
, "Group or GID"
: "Группа или GID"
, "Home Template"
: ""
, "Password Scheme"
: "Схема пароля"
, "PLAIN-MD5"
: "PLAIN-MD5"
, "MD5-CRYPT"
: "MD5-CRYPT"
, "SHA1"
: "SHA1"
, "SHA256"
: "SHA256"
, "SSHA256"
: "SSHA256"
, "SHA512"
: "SHA512"
, "SSHA512"
: "SSHA512"
, "PLAIN"
: "PLAIN"
, "Performing Environment Checks..."
: "Проведение проверок окружения..."
, "There could not be found any {0}. Please try to change your filter-criteria, view-options or the {1} you search in."
: ""
, "Check"
: "Проверка"
, "Result"
: "Результат"
, "Error"
: "Ошибка"
, "Run setup tests"
: "Запуск тестов установки"
, "Ignore setup tests"
: ""
, "Terms and Conditions"
: ""
, "Setup Checks"
: "Проверки установки"
, "Config Manager"
: "Управление конфигурацией"
, "Authentication/Accounts"
: ""
, "Email"
: ""
, "Application Manager"
: "Управление приложениями"
, "Application, Applications"
: [
"Приложение"
,"Приложения"
,"Приложений"
]
, "I have read the license agreement and accept it"
: ""
, "License Agreement"
: ""
, "I have read the privacy agreement and accept it"
: ""
, "Privacy Agreement"
: ""
, "Accept Terms and Conditions"
: ""
, "Application"
: "Приложение"
}));
|
var socketio = require('socket.io');
exports.listen = function( server, Manager ) {
var io = socketio.listen(server);
Manager.findAllUsers(function ( err, data ) {
if(!err){
if(data.length === 0){
Manager.addUser({'login': 'madzia26', 'password': 'qwertyuiop', 'id': new Date().getTime() }, function ( err, data ) {
if(!err){
console.log('first user added');
}
});
}
}
});
io.sockets.on('connection', function ( client ) {
'use strict';
// console.log('socket.io connected');
// console.log(client.id);
//init
client.on('init', function () {
Manager.findAllUsers(function ( err, data ) {
if(!err){
var res = {
'users': [],
'categories': []
};
for(var i = 0; i < data.length; i++){
res.users.push({'login': data[i].login, "id": data[i].id});
}
Manager.findAllCategories( function ( err, data) {
if(!err){
res.categories = data;
Manager.findAllCds( function ( err, data) {
if(!err){
res.cds = data;
client.emit('init', res);
// console.log('init');
}
});
}
});
}
});
});
//users
client.on('addUser', function ( user ) {
Manager.addUser(user, function ( err, data ) {
if(!err){
// var token = new Date().getTime();
// User.signin(data.login, data.id, token);
client.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.broadcast.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.emit('auth', {'login': data.login, 'id': data.id });
}
});
});
//categories
client.on('addCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = { 'name': data.data.name, 'owner': data.data.owner };
Manager.addCategory(category, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'categories', 'data': category });
client.broadcast.emit('add', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('editCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.editCategory(category, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'categories', 'data': category });
client.broadcast.emit('update', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('rmCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.rmCategory(category, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'categories', 'data': category });
client.broadcast.emit('remove', {'coll': 'categories', 'data': category });
}
});
}
});
//cds
client.on('addCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = { 'name': data.data.name, 'owner': data.data.owner,
'category': data.data.category, 'url': data.data.url };
Manager.addCd(cd, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'cds', 'data': cd });
client.broadcast.emit('add', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('editCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.editCd(cd, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'cds', 'data': cd });
client.broadcast.emit('update', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('rmCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.rmCd(cd, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'cds', 'data': cd });
client.broadcast.emit('remove', {'coll': 'cds', 'data': cd });
}
});
}
});
});
};
|
var Document = require('pelias-model').Document;
var docs = {};
docs.named = new Document('item1',1);
docs.named.setName('default','poi1');
docs.unnamed = new Document('item2',2); // no name
docs.unnamedWithAddress = new Document('item3',3);
docs.unnamedWithAddress.setCentroid({lat:3,lon:3});
docs.unnamedWithAddress.address = {
number: '10', street: 'Mapzen pl'
};
docs.namedWithAddress = new Document('item4',4);
docs.namedWithAddress.setName('default','poi4');
docs.namedWithAddress.setCentroid({lat:4,lon:4});
docs.namedWithAddress.address = {
number: '11', street: 'Sesame st'
};
docs.invalidId = new Document('item5',5);
docs.invalidId._meta.id = undefined; // unset the id
docs.invalidId.setCentroid({lat:5,lon:5});
docs.invalidId.address = {
number: '12', street: 'Old st'
};
docs.completeDoc = new Document('item6',6);
docs.completeDoc.address = {
number: '13', street: 'Goldsmiths row', test: 'prop'
};
docs.completeDoc
.setName('default','item6')
.setName('alt','item six')
.setCentroid({lat:6,lon:6})
.setAlpha3('FOO')
.setAdmin('admin0','country')
.setAdmin('admin1','state')
.setAdmin('admin1_abbr','STA')
.setAdmin('admin2','city')
.setAdmin('local_admin','borough')
.setAdmin('locality','town')
.setAdmin('neighborhood','hood')
.setMeta('foo','bar')
.setMeta('bing','bang');
docs.osmNode1 = new Document('item7',7)
.setName('osmnode','node7')
.setCentroid({lat:7,lon:7});
docs.osmWay1 = new Document('osmway',8)
.setName('osmway','way8')
.setMeta('nodes', [
{ lat: 10, lon: 10 },
{ lat: 06, lon: 10 },
{ lat: 06, lon: 06 },
{ lat: 10, lon: 06 }
]);
docs.osmRelation1 = new Document('item9',9)
.setName('osmrelation','relation9')
.setCentroid({lat:9,lon:9});
// ref: https://github.com/pelias/openstreetmap/issues/21
docs.semicolonStreetNumbers = new Document('item10',10);
docs.semicolonStreetNumbers.setName('default','poi10');
docs.semicolonStreetNumbers.setCentroid({lat:10,lon:10});
docs.semicolonStreetNumbers.address = {
number: '1; 2 ;3', street: 'Pennine Road'
};
// has no 'nodes' and a preset centroid
docs.osmWay2 = new Document('osmway',11)
.setName('osmway','way11')
.setCentroid({lat:11,lon:11});
module.exports = docs; |
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
//basePath: '../src/',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../src/**/*.js',
'../test/**/*.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
reporters: ['progress', 'coverage'],
preprocessors: {
'../src/**/*.js': ['coverage']
},
// configure code coverage
coverageReporter: {
reporters: [
{type: 'html', dir: '../coverage/'},
{type: 'lcov', dir: '../coverage/'},
{type: 'text-summary'}
]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
|
/* BBY261 */
/* Sayısal Loto Uygulaması */
//Çekiliş yapılacak sayıların dizisi
var rakamlar = new Array(49);
//Oynanacak kolonun dizisi
var loto = new Array(6);
document.write('<center><img src="sayisalloto.jpg" width=70% ></center>');
//Rakam havuzunun oluşturulması
for(var i=0; i<49; i++){
rakamlar[i]=i+1;
}
document.write('<table cellpadding="6" cellspacing="10" border="0" align="center">');
//6 kolonun ekrana yazdırılması
for(var i4=0; i4<6; i4++){
document.write('<tr>');
//Kolonun oluşturulması
for(var i2=0; i2<6; i2++){
var havuz = rakamlar.length;
var secilen = Math.floor(Math.random() * havuz);
loto[i2]=rakamlar[secilen];
rakamlar.splice(secilen,1);
}
loto.sort(function(a, b){return a-b});
//Tek kolonun yazdırılması
for(var i3=0; i3<6; i3++){
document.write('<td width=23 heigth=23 background="top.png" id="yazitipi">'+loto[i3]+'</td>');
}
document.write('</tr>');
}
document.write('</table>');
document.write('<p><center><img src="buton.png" onclick="yenile()" ></center></p>');
function yenile(){
window.location.href="index.html";
} |
angular.module('tabss.controllers', [])
.controller('TabssCtrl', function($scope,$state) {
$scope.gotoTabs =function(){
$state.go('tabs')
}
$scope.gotoNearby =function(){
$state.go('app.nearby')
}
$scope.gotoEditProfile =function(){
$state.go('editprofile')
}
$scope.gotoQRCode =function(){
$state.go('qrcode')
}
$scope.gotoHome =function(){
$state.go('app.home')
}
$scope.gotoAddFavorite =function(){
$state.go('addfavorite')
}
$scope.gotoFavoriteMenu1 =function(){
$state.go('favoritemenu1')
}
$scope.gotoCoffeeShop1 =function(){
$state.go('coffeeshop1')
}
$scope.gotoNewsPromotion =function(){
$state.go('newspromotion')
}
$scope.gotoNews =function(){
$state.go('news')
}
})
|
'use strict';
var http = require('http');
var Pusher = require('pusher');
var Network = require('./model/network');
var Node = require('./model/node');
var Sensor = require('./model/sensor');
var Feature = require('./model/feature');
require('./model/relations');
// https://pusher.com/docs/server_api_guide/interact_rest_api
var pusher = new Pusher({
appId: process.env.PUSHER_ID,
key: process.env.PUSHER_KEY,
secret: process.env.PUSHER_SECRET
});
/**
* Reverse object keys and values.
*/
function reverse(o) {
console.log('[index.js] reverse');
console.time('[index.js] reverse');
var result = {};
for(var key in o) {
result[o[key]] = key;
}
console.timeEnd('[index.js] reverse');
return result;
}
/**
* Extract the base64 data encoded in the kinesis record to an object.
* @return {Object}
*/
function decode(record) {
console.log('[index.js] decode');
console.time('[index.js] decode');
var data = new Buffer(record.kinesis.data, 'base64').toString();
try {
return JSON.parse(data);
} catch (SyntaxError) {
return {};
}
console.timeEnd('[index.js] decode');
}
/**
* If the sensor maps to an available feature of interest, provide it, otherwise
* reject it as null.
* @return {Object}
*/
function format(record, networkMap) {
var network = record.network;
var node = record.node;
var sensor = record.sensor;
var networkMetadata = networkMap[network];
if (!networkMetadata) {
return null;
}
var nodeMetadata = networkMetadata[node];
if (!nodeMetadata) {
return null;
}
var sensorMetadata = nodeMetadata[sensor];
if (!sensorMetadata) {
return null;
}
var mapping = sensorMetadata;
var feature = '';
for (var property in record.data) {
if (!(property in mapping)) {
return null;
}
feature = mapping[property].split('.')[0];
var formalName = mapping[property].split('.')[1];
record.data[formalName] = record.data[property];
if (formalName != property) {
delete record.data[property];
}
}
record.feature = feature;
record.results = record.data;
delete record.data;
return record;
}
/**
* Determine if a record can be published to a channel.
* @return {Boolean}
*/
function match(record, channel) {
var prefix = channel.split('-')[0];
channel = channel.split('-')[1];
if (prefix != 'private') return false;
var channelParts = channel.split(';');
var network = channelParts[0];
var node = channelParts[1];
var sensor = channelParts[2];
var feature = channelParts[3];
if (network != record.network) return false;
if (node && record.node != node) return false;
if (sensor && record.sensor != sensor) return false;
if (feature && record.feature != feature) return false;
return true;
}
/**
* Iterate through incoming records and emit to the appropriate channels.
*/
function emit(records, channels) {
console.log('[index.js] emit');
console.time('[index.js] emit');
records.forEach((record) => {
if (!record) return;
channels.forEach((channel) => {
var message = { message: JSON.stringify(record) };
if (match(record, channel)) {
pusher.trigger(channel, 'data', message);
}
});
});
console.timeEnd('[index.js] emit');
}
/**
* Implementation of required handler for an incoming batch of kinesis records.
* http://docs.aws.amazon.com/lambda/latest/dg/with-kinesis-example-deployment-pkg.html#with-kinesis-example-deployment-pkg-nodejs
*/
function handler(event, context) {
console.log('[index.js] handler');
console.time('[index.js] handler');
var records = event.Records.map(decode);
var promise = getSensorNetworkTree().then((networkMap) => {
records = records.map((record) => format(record, networkMap));
var valids = records.filter(r => r);
pusher.get({path: '/channels'}, (error, request, response) => {
console.log(response.body);
var result = JSON.parse(response.body);
var channels = Object.keys(result.channels);
emit(records, channels);
});
console.timeEnd('[index.js] handler');
return [records.length, valids.length];
});
return promise;
}
exports.handler = handler;
function extractFeatures(sensors) {
console.log('[index.js] extractFeatures');
console.time('[index.js] extractFeatures');
var result = {};
for (var sensor of sensors) {
result[sensor.name] = sensor.observed_properties;
}
console.timeEnd('[index.js] extractFeatures');
return result;
}
function extractSensors(nodes) {
console.log('[index.js] extractSensors');
console.time('[index.js] extractSensors');
var result = {};
for (var node of nodes) {
result[node.name] = extractFeatures(node.sensor__sensor_metadata);
}
console.timeEnd('[index.js] extractSensors');
return result;
}
function getSensorNetworkTree() {
console.log('[index.js] getSensorNetworkTree');
console.time('[index.js] getSensorNetworkTree');
var networkNames = [];
var promises = [];
return Network.findAll().then( networks => {
for (var network of networks) {
networkNames.push(network.name);
promises.push(network.getNodes({ include: [{ model: Sensor }]}));
}
return Promise.all(promises);
}).then( results => {
var tree = {};
for (var i = 0; i < results.length; i++) {
tree[networkNames[i]] = extractSensors(results[i]);
}
console.timeEnd('[index.js] getSensorNetworkTree');
return tree;
});
}
|
define(['handlebars'], function (Handlebars) {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['ma-ecca-treenode'] = template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
function program1(depth0,data) {
var stack1;
stack1 = helpers['if'].call(depth0, depth0.expanded, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
if(stack1 || stack1 === 0) { return stack1; }
else { return ''; }
}
function program2(depth0,data) {
var stack1;
if (stack1 = helpers.expandedClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.expandedClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
return escapeExpression(stack1);
}
function program4(depth0,data) {
var stack1;
if (stack1 = helpers.collapsedClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.collapsedClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
return escapeExpression(stack1);
}
function program6(depth0,data) {
return "display: none;";
}
buffer += "<ins class='ecca-tree-icon ";
stack1 = helpers['if'].call(depth0, depth0.childNodesAllowed, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "'> </ins><a href='#' class='ecca-tree-node'><ins class='ecca-tree-icon-folder ";
stack1 = helpers['if'].call(depth0, depth0.expanded, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += " ";
if (stack1 = helpers.iconClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.iconClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
buffer += escapeExpression(stack1)
+ "'> </ins><span>";
if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
buffer += escapeExpression(stack1)
+ "</span></a><ul style='";
stack1 = helpers.unless.call(depth0, depth0.expanded, {hash:{},inverse:self.noop,fn:self.program(6, program6, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "'></ul>";
return buffer;
});
}); |
import {combineEpics} from 'redux-observable';
import {combineReducers} from 'redux';
import {
disposePastebinEpic,
pastebinLayoutEpic,
pastebinEpic,
pastebinTokenEpic,
pastebinTokenRejectedEpic,
pastebinReducer,
pastebinContentEpic,
pastebinContentRejectedEpic,
} from './pastebin';
import {
firecoReducer,
firecoEditorsEpic,
firecoActivateEpic,
firecoEditorEpic,
firecoChatEpic,
firecoPersistableComponentEpic,
} from './fireco';
import {
configureMonacoModelsEpic,
updateMonacoModelsEpic,
configureMonacoThemeSwitchEpic,
monacoReducer,
} from './monaco';
import {
monacoEditorsEpic,
monacoEditorsReducer,
mountedEditorEpic,
} from './monacoEditor';
import {
updatePlaygroundReducer,
} from './playground';
import {updateBundleReducer} from './liveExpressionStore';
export const rootEpic = combineEpics(
disposePastebinEpic,
pastebinLayoutEpic,
pastebinEpic,
pastebinContentEpic,
pastebinContentRejectedEpic,
pastebinTokenEpic,
pastebinTokenRejectedEpic,
mountedEditorEpic,
configureMonacoModelsEpic,
updateMonacoModelsEpic,
configureMonacoThemeSwitchEpic,
monacoEditorsEpic,
// updatePlaygroundEpic,
// updatePlaygroundInstrumentationEpic,
firecoEditorsEpic,
firecoActivateEpic,
firecoEditorEpic,
firecoChatEpic,
firecoPersistableComponentEpic,
);
export const rootReducer = combineReducers({
pastebinReducer,
monacoReducer,
monacoEditorsReducer,
firecoReducer,
updateBundleReducer,
updatePlaygroundReducer,
});
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42zM13 20.01L4 11V4h7v-.01l9 9-7 7.02z"
}), h("circle", {
cx: "6.5",
cy: "6.5",
r: "1.5"
}), h("path", {
d: "M8.9 12.55c0 .57.23 1.07.6 1.45l3.5 3.5 3.5-3.5c.37-.37.6-.89.6-1.45 0-1.13-.92-2.05-2.05-2.05-.57 0-1.08.23-1.45.6l-.6.6-.6-.59c-.37-.38-.89-.61-1.45-.61-1.13 0-2.05.92-2.05 2.05z"
})), 'LoyaltyOutlined'); |
export default function isSingleTextTree(treeList) {
return treeList.length === 1 && treeList[0].type === 'text';
} |
const Comparator = require('../../util/comparator');
/**
* Swaps two elements in the array
*/
const swap = (array, x, y) => {
const tmp = array[y];
array[y] = array[x];
array[x] = tmp;
};
/**
* Chooses a pivot and makes every element that is
* lower than the pivot move to its left, and every
* greater element moves to its right
*
* @return Number the positon of the pivot
*/
const partition = (a, comparator, lo, hi) => {
// pick a random element, swap with the rightmost and
// use it as pivot
swap(a, Math.floor(Math.random() * (hi - lo)) + lo, hi);
const pivot = hi;
// dividerPosition keeps track of the position
// where the pivot should be inserted
let dividerPosition = lo;
for (let i = lo; i < hi; i++) {
if (comparator.lessThan(a[i], a[pivot])) {
swap(a, i, dividerPosition);
dividerPosition++;
}
}
swap(a, dividerPosition, pivot);
return dividerPosition;
};
/**
* Quicksort recursively sorts parts of the array in
* O(n.lg n)
*/
const quicksortInit = (array, comparatorFn) => {
const comparator = new Comparator(comparatorFn);
return (function quicksort(array, lo, hi) {
while (lo < hi) {
const p = partition(array, comparator, lo, hi);
// Chooses only the smallest partition to use recursion on and
// tail-optimize the other. This guarantees O(log n) space in worst case.
if (p - lo < hi - p) {
quicksort(array, lo, p - 1);
lo = p + 1;
} else {
quicksort(array, p + 1, hi);
hi = p - 1;
}
}
return array;
})(array, 0, array.length - 1);
};
module.exports = quicksortInit;
|
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let compression = require('compression');
let session = require('express-session');
let index = require('./routes/index');
let users = require('./routes/users');
let server = express();
server.set('views', path.join(__dirname, 'views'));
server.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//server.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
server.use(logger('dev'));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(cookieParser());
server.use(express.static(path.join(__dirname, 'public')));
server.use(compression())
// express-sessions setup
server.use(session({
secret: 'blueberry pie',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 600000
}
// db: knex
}))
server.use('/', index);
server.use('/users', users);
// catch 404 and forward to error handler
server.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (server.get('env') === 'development') {
server.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
server.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = server;
|
const landingText = (
``
)
const aboutText = (
`We are a team of expert web developers coming from diverse backgrounds who
are passionate about building a better web experience and delivering quality
code to our clients`
)
|
import React, { PropTypes } from 'react';
export default function ImageDesciption({desc, price}) {
return (
<div className="text">
<h3>{desc}</h3>
<p className="price">{price}</p>
</div>
);
}
|
var gulp = require("gulp");
var $ = require("gulp-load-plugins");
gulp.task("html", function () {
gulp.src("./src/index.html")
.pipe(gulp.dest("./.tmp"));
});
|
const _ = require('lodash');
module.exports = _.extend(
require('./users/users.authentication.server.controller'),
require('./users/users.authorization.server.controller'),
require('./users/users.password.server.controller'),
require('./users/users.profile.server.controller')
);
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Review Schema
*/
var ReviewSchema = new Schema({
content: {
type: String,
default: '',
trim: true
},
contentHTML: {
type: String,
default: ''
},
name: {
type: String,
default: '',
trim: true
},
score: {
type: Number,
default: 5,
required: 'Must rate the game out of 5',
min: [0, 'Score must be at least 0'],
max: [5, 'Score cannot be higher than 5']
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
gameId: {
type: String,
required: 'Game for review required'
},
game: {
type: Schema.ObjectId,
ref: 'Game'
},
triaged: {
type: Boolean,
default: false
},
liked: {
type: Number,
default: 0
},
disliked: {
type: Number,
default: 0
},
reports: [{
type: String,
enum: [
'Spam',
'Vote Manipulation',
'Personal Information',
'Troll',
'Harrassment'
]
}]
});
mongoose.model('Review', ReviewSchema); |
$(document).ready(function(){
var $nomeInput = $('#nomeInput');
var $descricaoInput = $('#descricaoInput');
var $precoInput = $('#precoInput');
var $categoriaSelect = $('#categoriaSelect');
var $novidadeSelect = $('#novidadeSelect');
var $carregandoImg = $('#carregandoImg');
$carregandoImg.hide();
var $btnSalvar = $('#salvar');
var $btnFechar = $('#fechar');
var $listaProdutos = $('#listaProdutos');
$listaProdutos.hide();
function obterValoresdeProdutos(){
return {'nome' : $nomeInput.val() , 'descricao' : $descricaoInput.val(), 'preco': $precoInput.val() , 'categoria' : $categoriaSelect.val(), 'novidade' : $novidadeSelect.val()}
}
function limparValores(){
$('input[type="text"]').val('');
$novidadeSelect.val('');
}
$.get('/produtos/admin/rest/listar').success(function(produtos){
$.each(produtos,function(index, p){
adicionarProduto(p);
})
});
function adicionarProduto (produto) {
var msg = '<tr id="tr-produto_'+produto.id+'"><td>'+produto.id+'</td><td>'+produto.nome+'</td><td>'+produto.categoria+'</td><td>'+produto.descricao+'</td><td>'+produto.preco+'</td><td>'+(produto.novidade == "1" ? 'Sim' : 'Não')+'</td><td><a href="/produtos/admin/editar/'+produto.id+'" class="btn btn-warning glyphicon glyphicon-pencil"></a></td><td><button id="btn-deletar_'+produto.id+'" class="btn btn-danger"><i class="glyphicon glyphicon-trash"></i></button></td></tr>';
$listaProdutos.show();
$listaProdutos.append(msg);
$('#btn-deletar_'+produto.id).click(function(){
if (confirm("Deseja apagar esse registro? "))
{
var resp = $.post('/produtos/admin/rest/deletar' , {produto_id : produto.id});
resp.success(function(){
$('#tr-produto_'+produto.id).remove()
});
}
});
}
$btnSalvar.click(function(){
$('.has-error').removeClass('has-error');
$('.help-block').empty();
$btnSalvar.attr('disabled' , 'disabled');
$carregandoImg.fadeIn('fast');
var resp = $.post('/produtos/admin/rest/salvar', obterValoresdeProdutos());
resp.success(function(produto){
limparValores();
$btnFechar.click();
adicionarProduto(produto);
})
resp.error(function(erros){
for(campos in erros.responseJSON)
{
$('#'+campos+'Div').addClass('has-error');
$('#'+campos+'Span').text(erros.responseJSON[campos]);
}
}).always(function(){
$btnSalvar.removeAttr('disabled','disabled');
$carregandoImg.hide();
});
});
});
|
// Karma configuration
// Generated on Wed Jul 15 2015 09:44:02 GMT+0200 (Romance Daylight Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular2/node_modules/zone.js/dist/zone-microtask.js',
'node_modules/angular2/node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/angular2/node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/angular2/node_modules/traceur/bin/traceur-runtime.js',
'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/reflect-metadata/Reflect.js',
{ pattern: 'test/**/*.js', included: false, watched: true },
{ pattern: 'node_modules/angular2/**/*.js', included: false, watched: false },
'test-main.js',
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.5.4.20-4-55
description: >
String.prototype.trim handles whitepace and lineterminators
(\u000A\u000A)
includes: [runTestCase.js]
---*/
function testcase() {
if ("\u000A\u000A".trim() === "") {
return true;
}
}
runTestCase(testcase);
|
'use strict';
const os = require('os');
const cluster = require('cluster');
const DEFAULT_DEADLINE_MS = 30000;
function makeWorker(workerFunc) {
var server = workerFunc(cluster.worker.id);
server.on('close', function() {
process.exit();
});
process.on('SIGTERM', function() {
server.close();
});
return server;
}
const Regiment = function(workerFunc, options) {
if (cluster.isWorker) return makeWorker(workerFunc);
options = options || {};
const numCpus = os.cpus().length;
let running = true;
const deadline = options.deadline || DEFAULT_DEADLINE_MS;
const numWorkers = options.numWorkers || numCpus;
const logger = options.logger || console;
function messageHandler(msg) {
if (running && msg.cmd && msg.cmd === 'need_replacement') {
const workerId = msg.workerId;
const replacement = spawn();
logger.log(`Replacing worker ${workerId} with worker ${replacement.id}`);
replacement.on('listening', (address) => {
logger.log(`Replacement ${replacement.id} is listening, killing ${workerId}`);
kill(cluster.workers[workerId]);
})
}
}
function spawn() {
const worker = cluster.fork();
worker.on('message', messageHandler);
return worker;
}
function fork() {
for (var i=0; i<numWorkers; i++) {
spawn();
}
}
function kill(worker) {
logger.log(`Killing ${worker.id}`);
worker.process.kill();
ensureDeath(worker);
}
function ensureDeath(worker) {
setTimeout(() => {
logger.log(`Ensured death of ${worker.id}`);
worker.kill();
}, deadline).unref();
worker.disconnect();
}
function respawn(worker, code, signal) {
if (running && !worker.exitedAfterDisconnect) {
logger.log(`Respawning ${worker.id} after it exited`);
spawn();
}
}
function listen() {
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
cluster.on('exit', respawn);
}
function shutdown() {
running = false;
logger.log(`Shutting down!`);
for (var id in cluster.workers) {
kill(cluster.workers[id]);
}
}
listen();
fork();
}
Regiment.middleware = require('./middleware');
module.exports = Regiment;
|
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, dialect = Support.getTestDialect()
, DataTypes = require(__dirname + "/../../lib/data-types")
, _ = require('lodash')
, sequelize = require(__dirname + '/../../lib/sequelize');
chai.config.includeStack = true
if (dialect.match(/^postgres/)) {
describe('[POSTGRES Specific] DAO', function() {
beforeEach(function(done) {
this.sequelize.options.quoteIdentifiers = true
this.User = this.sequelize.define('User', {
username: DataTypes.STRING,
email: { type: DataTypes.ARRAY(DataTypes.TEXT) },
settings: DataTypes.HSTORE,
document: { type: DataTypes.HSTORE, defaultValue: { default: 'value' } },
phones: DataTypes.ARRAY(DataTypes.HSTORE),
emergency_contact: DataTypes.JSON
})
this.User.sync({ force: true }).success(function() {
done()
})
})
afterEach(function(done) {
this.sequelize.options.quoteIdentifiers = true
done()
})
it('should be able to search within an array', function(done) {
this.User.all({where: {email: ['hello', 'world']}}).on('sql', function(sql) {
expect(sql).to.equal('SELECT "id", "username", "email", "settings", "document", "phones", "emergency_contact", "createdAt", "updatedAt" FROM "Users" AS "User" WHERE "User"."email" && ARRAY[\'hello\',\'world\']::TEXT[];')
done()
})
})
it('should be able to find a record while searching in an array', function(done) {
var self = this
this.User.bulkCreate([
{username: 'bob', email: ['[email protected]']},
{username: 'tony', email: ['[email protected]']}
]).success(function() {
self.User.all({where: {email: ['[email protected]']}}).success(function(user) {
expect(user).to.be.instanceof(Array)
expect(user).to.have.length(1)
expect(user[0].username).to.equal('bob')
done()
})
})
})
describe('json', function () {
it('should tell me that a column is json', function() {
return this.sequelize.queryInterface.describeTable('Users')
.then(function (table) {
expect(table.emergency_contact.type).to.equal('JSON');
});
});
it('should stringify json with insert', function () {
return this.User.create({
username: 'bob',
emergency_contact: { name: 'joe', phones: [1337, 42] }
}).on('sql', function (sql) {
var expected = 'INSERT INTO "Users" ("id","username","document","emergency_contact","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',\'"default"=>"value"\',\'{"name":"joe","phones":[1337,42]}\''
expect(sql.indexOf(expected)).to.equal(0);
});
});
it('should be able retrieve json value as object', function () {
var self = this;
var emergencyContact = { name: 'kate', phone: 1337 };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact); // .eql does deep value comparison instead of strict equal comparison
return self.User.find({ where: { username: 'swen' }, attributes: ['emergency_contact'] });
})
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
});
});
it('should be able to retrieve element of array by index', function () {
var self = this;
var emergencyContact = { name: 'kate', phones: [1337, 42] };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.phones.1'), 'firstEmergencyNumber']] });
})
.then(function (user) {
expect(parseInt(user.getDataValue('firstEmergencyNumber'))).to.equal(42);
});
});
it('should be able to retrieve root level value of an object by key', function () {
var self = this;
var emergencyContact = { kate: 1337 };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.kate'), 'katesNumber']] });
})
.then(function (user) {
expect(parseInt(user.getDataValue('katesNumber'))).to.equal(1337);
});
});
it('should be able to retrieve nested value of an object by path', function () {
var self = this;
var emergencyContact = { kate: { email: '[email protected]', phones: [1337, 42] } };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.kate.email'), 'katesEmail']] });
})
.then(function (user) {
expect(user.getDataValue('katesEmail')).to.equal('[email protected]');
})
.then(function () {
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.kate.phones.1'), 'katesFirstPhone']] });
})
.then(function (user) {
expect(parseInt(user.getDataValue('katesFirstPhone'))).to.equal(42);
});
});
it('should be able to retrieve a row based on the values of the json document', function () {
var self = this;
return this.sequelize.Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })])
.then(function () {
return self.User.find({ where: sequelize.json("emergency_contact->>'name'", 'kate'), attributes: ['username', 'emergency_contact'] });
})
.then(function (user) {
expect(user.emergency_contact.name).to.equal('kate');
});
});
it('should be able to query using the nested query language', function () {
var self = this;
return this.sequelize.Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })])
.then(function () {
return self.User.find({
where: sequelize.json({ emergency_contact: { name: 'kate' } })
});
})
.then(function (user) {
expect(user.emergency_contact.name).to.equal('kate');
});
});
it('should be ablo to query using dot syntax', function () {
var self = this;
return this.sequelize.Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })])
.then(function () {
return self.User.find({ where: sequelize.json('emergency_contact.name', 'joe') });
})
.then(function (user) {
expect(user.emergency_contact.name).to.equal('joe');
});
});
});
describe('hstore', function() {
it('should tell me that a column is hstore and not USER-DEFINED', function(done) {
this.sequelize.queryInterface.describeTable('Users').success(function(table) {
expect(table.settings.type).to.equal('HSTORE')
expect(table.document.type).to.equal('HSTORE')
done()
})
})
it('should stringify hstore with insert', function(done) {
this.User.create({
username: 'bob',
email: ['[email protected]'],
settings: {mailing: false, push: 'facebook', frequency: 3}
}).on('sql', function(sql) {
var expected = 'INSERT INTO "Users" ("id","username","email","settings","document","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'[email protected]\']::TEXT[],\'"mailing"=>false,"push"=>"facebook","frequency"=>3\',\'"default"=>"value"\''
expect(sql.indexOf(expected)).to.equal(0)
done()
})
})
})
describe('enums', function() {
it('should be able to ignore enum types that already exist', function(done) {
var User = this.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('happy', 'sad', 'meh')
})
User.sync({ force: true }).success(function() {
User.sync().success(function() {
done()
})
})
})
it('should be able to create/drop enums multiple times', function(done) {
var User = this.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('happy', 'sad', 'meh')
})
User.sync({ force: true }).success(function() {
User.sync({ force: true }).success(function() {
done()
})
})
})
it("should be able to create/drop multiple enums multiple times", function(done) {
var DummyModel = this.sequelize.define('Dummy-pg', {
username: DataTypes.STRING,
theEnumOne: {
type: DataTypes.ENUM,
values:[
'one',
'two',
'three',
]
},
theEnumTwo: {
type: DataTypes.ENUM,
values:[
'four',
'five',
'six',
],
}
})
DummyModel.sync({ force: true }).done(function(err) {
expect(err).not.to.be.ok
// now sync one more time:
DummyModel.sync({force: true}).done(function(err) {
expect(err).not.to.be.ok
// sync without dropping
DummyModel.sync().done(function(err) {
expect(err).not.to.be.ok
done();
})
})
})
})
it('should be able to add enum types', function(done) {
var self = this
, User = this.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('happy', 'sad', 'meh')
})
var _done = _.after(4, function() {
done()
})
User.sync({ force: true }).success(function() {
User = self.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
})
User.sync().success(function() {
expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful'])
_done()
}).on('sql', function(sql) {
if (sql.indexOf('neutral') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'")
_done()
}
else if (sql.indexOf('ecstatic') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'")
_done()
}
else if (sql.indexOf('joyful') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'")
_done()
}
})
})
})
})
describe('integers', function() {
describe('integer', function() {
beforeEach(function(done) {
this.User = this.sequelize.define('User', {
aNumber: DataTypes.INTEGER
})
this.User.sync({ force: true }).success(function() {
done()
})
})
it('positive', function(done) {
var User = this.User
User.create({aNumber: 2147483647}).success(function(user) {
expect(user.aNumber).to.equal(2147483647)
User.find({where: {aNumber: 2147483647}}).success(function(_user) {
expect(_user.aNumber).to.equal(2147483647)
done()
})
})
})
it('negative', function(done) {
var User = this.User
User.create({aNumber: -2147483647}).success(function(user) {
expect(user.aNumber).to.equal(-2147483647)
User.find({where: {aNumber: -2147483647}}).success(function(_user) {
expect(_user.aNumber).to.equal(-2147483647)
done()
})
})
})
})
describe('bigint', function() {
beforeEach(function(done) {
this.User = this.sequelize.define('User', {
aNumber: DataTypes.BIGINT
})
this.User.sync({ force: true }).success(function() {
done()
})
})
it('positive', function(done) {
var User = this.User
User.create({aNumber: '9223372036854775807'}).success(function(user) {
expect(user.aNumber).to.equal('9223372036854775807')
User.find({where: {aNumber: '9223372036854775807'}}).success(function(_user) {
expect(_user.aNumber).to.equal('9223372036854775807')
done()
})
})
})
it('negative', function(done) {
var User = this.User
User.create({aNumber: '-9223372036854775807'}).success(function(user) {
expect(user.aNumber).to.equal('-9223372036854775807')
User.find({where: {aNumber: '-9223372036854775807'}}).success(function(_user) {
expect(_user.aNumber).to.equal('-9223372036854775807')
done()
})
})
})
})
})
describe('model', function() {
it("create handles array correctly", function(done) {
this.User
.create({ username: 'user', email: ['[email protected]', '[email protected]'] })
.success(function(oldUser) {
expect(oldUser.email).to.contain.members(['[email protected]', '[email protected]'])
done()
})
.error(function(err) {
console.log(err)
})
})
it("should save hstore correctly", function(done) {
this.User
.create({ username: 'user', email: ['[email protected]'], settings: { created: { test: '"value"' }}})
.success(function(newUser) {
// Check to see if the default value for an hstore field works
expect(newUser.document).to.deep.equal({ default: 'value' })
expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})
// Check to see if updating an hstore field works
newUser.updateAttributes({settings: {should: 'update', to: 'this', first: 'place'}}).success(function(oldUser){
// Postgres always returns keys in alphabetical order (ascending)
expect(oldUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
done()
})
})
.error(console.log)
})
it('should save hstore array correctly', function(done) {
this.User.create({
username: 'bob',
email: ['[email protected]'],
phones: [{ number: '123456789', type: 'mobile' }, { number: '987654321', type: 'landline' }]
}).on('sql', function(sql) {
var expected = 'INSERT INTO "Users" ("id","username","email","document","phones","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'[email protected]\']::TEXT[],\'"default"=>"value"\',ARRAY[\'"number"=>"123456789","type"=>"mobile"\',\'"number"=>"987654321","type"=>"landline"\']::HSTORE[]'
expect(sql).to.contain(expected)
done()
})
})
it("should update hstore correctly", function(done) {
var self = this
this.User
.create({ username: 'user', email: ['[email protected]'], settings: { created: { test: '"value"' }}})
.success(function(newUser) {
// Check to see if the default value for an hstore field works
expect(newUser.document).to.deep.equal({default: 'value'})
expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})
// Check to see if updating an hstore field works
self.User.update({settings: {should: 'update', to: 'this', first: 'place'}}, {where: newUser.identifiers}).success(function() {
newUser.reload().success(function() {
// Postgres always returns keys in alphabetical order (ascending)
expect(newUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
done()
});
})
})
.error(console.log)
})
it("should update hstore correctly and return the affected rows", function(done) {
var self = this
this.User
.create({ username: 'user', email: ['[email protected]'], settings: { created: { test: '"value"' }}})
.success(function(oldUser) {
// Update the user and check that the returned object's fields have been parsed by the hstore library
self.User.update({settings: {should: 'update', to: 'this', first: 'place'}}, {where: oldUser.identifiers, returning: true }).spread(function(count, users) {
expect(count).to.equal(1);
expect(users[0].settings).to.deep.equal({should: 'update', to: 'this', first: 'place'})
done()
})
})
.error(console.log)
})
it("should read hstore correctly", function(done) {
var self = this
var data = { username: 'user', email: ['[email protected]'], settings: { created: { test: '"value"' }}}
this.User
.create(data)
.success(function() {
// Check that the hstore fields are the same when retrieving the user
self.User.find({ where: { username: 'user' }})
.success(function(user) {
expect(user.settings).to.deep.equal(data.settings)
done()
})
})
.error(console.log)
})
it('should read an hstore array correctly', function(done) {
var self = this
var data = { username: 'user', email: ['[email protected]'], phones: [{ number: '123456789', type: 'mobile' }, { number: '987654321', type: 'landline' }] }
this.User
.create(data)
.success(function() {
// Check that the hstore fields are the same when retrieving the user
self.User.find({ where: { username: 'user' }})
.success(function(user) {
expect(user.phones).to.deep.equal(data.phones)
done()
})
})
})
it("should read hstore correctly from multiple rows", function(done) {
var self = this
self.User
.create({ username: 'user1', email: ['[email protected]'], settings: { created: { test: '"value"' }}})
.then(function() {
return self.User.create({ username: 'user2', email: ['[email protected]'], settings: { updated: { another: '"example"' }}})
})
.then(function() {
// Check that the hstore fields are the same when retrieving the user
return self.User.findAll({ order: 'username' })
})
.then(function(users) {
expect(users[0].settings).to.deep.equal({ created: { test: '"value"' }})
expect(users[1].settings).to.deep.equal({ updated: { another: '"example"' }})
done()
})
.error(console.log)
})
})
describe('[POSTGRES] Unquoted identifiers', function() {
it("can insert and select", function(done) {
var self = this
this.sequelize.options.quoteIdentifiers = false
this.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = false
this.User = this.sequelize.define('Userxs', {
username: DataTypes.STRING,
fullName: DataTypes.STRING // Note mixed case
}, {
quoteIdentifiers: false
})
this.User.sync({ force: true }).success(function() {
self.User
.create({ username: 'user', fullName: "John Smith" })
.success(function(user) {
// We can insert into a table with non-quoted identifiers
expect(user.id).to.exist
expect(user.id).not.to.be.null
expect(user.username).to.equal('user')
expect(user.fullName).to.equal('John Smith')
// We can query by non-quoted identifiers
self.User.find({
where: {fullName: "John Smith"}
})
.success(function(user2) {
self.sequelize.options.quoteIndentifiers = true
self.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = true
self.sequelize.options.logging = false
// We can map values back to non-quoted identifiers
expect(user2.id).to.equal(user.id)
expect(user2.username).to.equal('user')
expect(user2.fullName).to.equal('John Smith')
done()
})
})
})
})
})
})
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import { post } from '../../api';
class PostActionButton extends Component {
static propTypes = {
bsStyle: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
hideContentOnAction: PropTypes.bool.isRequired,
action: PropTypes.string.isRequired,
body: PropTypes.object.isRequired,
onSuccess: PropTypes.func,
onError: PropTypes.func,
};
static defaultProps = {
body: {},
hideContentOnAction: false,
onSuccess: () => {},
onError: () => {},
};
constructor(props) {
super(props);
this.state = { isWorking: false };
}
onClick = () => {
this.setState({ isWorking: true });
const { body, action, onSuccess, onError } = this.props;
post(action, body).then(() => {
this.setState({ isWorking: false });
onSuccess();
}, (err) => {
console.error(err);
onError(err);
});
};
render() {
const { isWorking } = this.state;
const { hideContentOnAction, bsStyle, children } = this.props;
const renderChildren = !isWorking || (isWorking && !hideContentOnAction);
return (
<Button onClick={this.onClick} bsStyle={bsStyle}>
{isWorking &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {renderChildren && children}
</Button>
);
}
}
export default PostActionButton;
|
import $ from 'jquery'
const DURATION_MS = 400
export default function scrollToTop () {
const scrollTop = $('.auction-artworks-HeaderDesktop').offset().top - $('.mlh-navbar').height()
$('html,body').animate({ scrollTop }, DURATION_MS)
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:96c89faf399ad903c813617aca830b28b3330c35d8af37d08743722e06d9323d
size 84
|
module.exports = function(grunt) {
grunt.initConfig({
web_server: {
options: {
cors: true,
port: 8000,
nevercache: true,
logRequests: true
},
foo: 'bar'
},
uglify: {
my_target: {
files: {
'dist/ng-video-preview.min.js': ['video-preview.js']
}
}
},
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
globals: {
jQuery: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-web-server');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['jshint']);
}; |
var model = require('./model');
var backbone = require('backbone');
var fs = require('fs');
var util = require('util');
var fpath = require('path');
var hive = require('./hive');
var EMPTY_FILE = '';
var exports = module.exports = model.extend({
initialize: function(attributes) {
var _self = this;
var path = this.get('path');
if(path) {
var name = fpath.basename(path);
if(name) {
this.set({name: name});
}
if(attributes.watch) {
fs.watchFile(path, function() {
_self.sync('read', _self);
_self.change();
});
}
}
return this;
},
ext: function() {
return fpath.extname(this.get('name'));
},
absolute: function() {
return fpath.resolve(this.get('path'));
},
dir: function() {
return fpath.dirname(this.absolute());
},
sync: function(method, model) {
model.syncing = true;
var path = model.absolute();
switch(method) {
case 'create':
case 'update':
hive.log(method + '-ing file @ ' + path);
fs.writeFile(path, model.get('data') || EMPTY_FILE, model.get('encoding'), function(err) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: model.get('data'), exists: true}, true);
});
break;
case 'read':
hive.log(method + '-ing file @ ' + path);
fs.readFile(path, function(err, data) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: data.toString(), exists: true});
});
break;
case 'delete':
hive.log(method + '-ing file @ ' + path);
fs.unlink(path, function(err) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: null, exists: false});
});
break;
}
},
paste: function(destination, name) {
var _self = this;
_self.syncing = true;
if(typeof destination === 'string') {
destination = new hive.Dir({path: destination});
}
var name = name || _self.get('name'),
path = destination.get('path') + '/' + name;
if(!path) _self.error('Could not paste file to hive.Dir without a path');
var i = fs.createReadStream(_self.get('path')),
o = fs.createWriteStream(path);
util.pump(i, o, function() {
hive.log('wrote file @ ' + path);
_self.trigger('pasted');
_self.success({data: o});
});
return this;
},
update: function(callback, done) {
var _self = this;
hive.log('**UPDATING**', _self);
_self.fetch(function() {
hive.log('**UPDATING**', 'fetched');
hive.log('**UPDATING** data - ', _self.get('data'));
var changed = callback(_self.get('data') || '');
hive.log('**UPDATING** changed - ', changed);
_self.set({data: changed}, {silent: true});
_self.once('success', function() {
hive.log('**UPDATING**', 'done');
done && done();
});
_self.save();
});
}
}); |
/**
min任务
-------------
min脚本,样式,图片或html
### 用法
<min src='my.js' dest='my.min.js'/>
<min file='reset.css' destfile='reset.min.css'/>
@class min
**/
module.exports = function(bee) {
bee.register('min', function(options, callback) {
var path = require('path');
var minifier = require('node-minifier');
var src = options.src || options.file;
var destfile = options.destfile || options.dest;
if (!src || !destfile) {
return callback(new Error('src/file and dest/destfile are required in minify task.'));
}
var childNodes = options.childNodes;
var banner, footer;
options.childNodes.forEach(function(item){
if(item.name === 'banner' || item.name === 'header'){
banner = item.value.value;
}else if(item.name === 'footer'){
footer = item.value.value;
}
});
var readWrite = function(transform, input, output, callback) {
var encoding = options.encoding || 'utf-8';
var filecontent = bee.file.read(input, encoding);
filecontent = transform(filecontent, options);
bee.file.mkdir(path.dirname(output));
bee.file.write(output, filecontent, encoding);
callback();
}
var minifyJS = function(input, output, callback) {
bee.log('minify JS input:' + input + ' output: ' + output);
var remove = options.remove ? options.remove.split(',') : [];
readWrite(function(filecontent) {
return minifier.minifyJS(filecontent, {
remove: remove,
copyright: options.copyright || true,
banner: banner,
footer: footer
});
}, input, output, callback);
}
var minifyCSS = function(input, output, callback) {
bee.log('minify CSS input:' + input + ' output: ' + output);
readWrite(function(filecontent) {
return minifier.minifyCSS(filecontent, {
datauri: options.datauri,
banner: banner,
footer: footer
});
}, input, output, callback);
}
var minifyHTML = function(input, output, callback) {
bee.log('minify HTML input:' + input + ' output: ' + output);
options.banner = banner;
options.footer = footer;
readWrite(function(filecontent) {
return minifier.minifyHTML(filecontent, options);
}, input, output, callback);
}
var minifyImage = function(input, output, callback) {
bee.log('minify Image input:' + input + ' output: ' + output);
minifier.minifyImage(input, output, function(e, data) {
if (e) {
callback && callback(e);
} else {
callback(null);
}
}, {
service: options.service
})
}
var extname = options.type || bee.file.extname(src).toLowerCase();
var method;
if (extname == 'js') {
method = minifyJS;
} else if (extname == 'css') {
method = minifyCSS;
} else if (['html', 'htm'].indexOf(extname) >= 0) {
method = minifyHTML;
} else if (['png', 'jpg', 'jpeg', 'gif'].indexOf(extname) >= 0) {
method = minifyImage;
}
if(!method){
bee.warn('the filetype of ' + src + ' cannot be minified.')
return callback();
}
method(src, destfile, callback);
});
} |
// Generated by CoffeeScript 1.10.0
(function() {
(function($) {
return $(".some_button").on("click", function(event) {
console.log("some_button clicked!");
return event.preventDefault();
});
})(jQuery);
}).call(this);
|
const mongoose = require('mongoose')
const TABLE_NAME = 'Post'
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const escape = (require('../utils')).escape
const PostSchema = new Schema({
//类型
type: {
type: String,
default: 'post' // post | page
},
//标题
title: {
type: String,
trim: true,
set: escape
},
//别名
alias: {
type: String,
trim: true,
set: escape
},
//创建者
user: {
type: ObjectId,
ref: 'User'
},
//类别
category: {
type: ObjectId,
ref: 'Category'
},
//摘要
excerpt: {
type: String,
trim: true,
},
//内容
contents: {
type: String,
trim: true,
},
//markdown
markdown: {
type: String,
trim: true,
},
//标签
tags: Array,
//缩略图
thumbnail: {
type: String,
trim: true,
set: escape
},
//统计
count: {
//浏览次数
views: {
type: Number,
default: 1,
},
//评论数
comments: {
type: Number,
default: 0,
},
//点赞数
praises: {
type: Number,
default: 1
}
},
//状态
status: {
type: Number,
default: 1 // 1:发布, 0 :草稿, -1 :删除
},
//置顶
top: Boolean,
//允许评论
allowComment: {
type: Boolean,
default: true
},
//允许打赏
allowReward: Boolean,
//著名版权
license: Boolean,
//使用密码
usePassword: Boolean,
//密码
password: {
type: String,
trim: true
},
order: {
type: Number,
default: 1
},
//创建时间
createTime: {
type: Date,
default: Date.now()
},
//修改时间
updateTime: {
type: Date,
default: Date.now()
}
}, {
connection: TABLE_NAME,
versionKey: false,
})
module.exports = mongoose.model(TABLE_NAME, PostSchema) |
var test = require("tape")
var mongo = require("continuable-mongo")
var uuid = require("node-uuid")
var setTimeout = require("timers").setTimeout
var eventLog = require("../index")
var client = mongo("mongodb://localhost:27017/colingo-group-tests")
var collectionName = uuid()
var col = client.collection(collectionName)
var rawCollection = client.collection(collectionName + "@")
var SECOND = 1000
var MINUTE = 60 * SECOND
var HOUR = 60 * MINUTE
test("ensure col is capped", function (assert) {
client(function (err, db) {
assert.ifError(err)
db.createCollection(collectionName, {
capped: true
, size: 100000
}, function (err, res) {
assert.ifError(err)
assert.end()
})
})
})
test("can add to eventLog", function (assert) {
var log = eventLog(col, {
timeToLive: HOUR
, rawCollection: rawCollection
})
var id = uuid()
log.add("add", {
id: id
, timestamp: Date.now()
, type: "some-event"
}, function (err, value) {
assert.ifError(err)
assert.equal(value.eventType, "add")
assert.ok(value._id)
assert.equal(value.value.id, id)
log.close()
assert.end()
})
})
test("can read from eventLog", function (assert) {
var log = eventLog(col, {
rawCollection: rawCollection
, timeToLive: HOUR
})
var stream = log.read(Date.now() - 1000)
setTimeout(function () {
log.add("add", {
id: uuid()
, timestamp: Date.now()
, type: "some-event"
, foo: "inserted after"
}, function (err, value) {
assert.ifError(err)
})
}, 20)
log.add("add", {
id: uuid()
, timestamp: Date.now()
, type: "some-event"
, foo: "inserted before"
}, function (err, value) {
assert.ifError(err)
var list = []
var cleanupCounter = 2
stream.on("data", function (chunk) {
list.push(chunk)
if (list.length === 3) {
next()
}
})
stream.resume()
function next() {
assert.equal(list.length, 3)
assert.equal(list[0].value.type, "some-event")
assert.equal(list[1].value.foo, "inserted before")
assert.equal(list[2].value.foo, "inserted after")
rawCollection(function (err, rawCollection) {
assert.ifError(err)
rawCollection.drop(function (err) {
assert.ifError(err)
if (--cleanupCounter === 0) {
cleanup()
}
})
})
col(function (err, col) {
assert.ifError(err)
col.drop(function (err) {
assert.ifError(err)
if (--cleanupCounter === 0) {
cleanup()
}
})
})
}
function cleanup() {
log.close()
client.close(function (err) {
assert.ifError(err)
assert.end()
})
}
})
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:356614d2260c69b92680d59e99601dcd5e068f761756f22fb959b5562b9a7d62
size 17413
|
import * as React from 'react';
import {Row,Col,Table,Code,Items,Item} from 'yrui';
import thead from './thead';
let items=[{
key:'style',
expr:'设置items样式',
type:'object',
values:'-',
default:'-',
}];
let item=[{
key:'border',
expr:'设置border样式',
type:'string',
values:'-',
default:'-',
}];
const code=`
<Items>
<Item>
<h2>items配置</h2>
<Table thead={thead} tbody={items} />
</Item>
<Item>
<h2>item配置</h2>
<Table thead={thead} tbody={item} />
</Item>
</Items>
`;
export default class ItemsDemo extends React.Component{
render(){
return(
<Items>
<Item>
<h2>代码示例</h2>
<Code title="input" code={code} />
</Item>
<Item>
<Row gutter={8}>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={items} noBorder={true} />
</Col>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={item} noBorder={true} />
</Col>
</Row>
</Item>
</Items>
);
}
}
|
define(function() {
'use strict';
/* @ngInject */
var gameCtrl = function($scope, commoditySrvc, citySrvc, accountSrvc, gameSrvc, tutorialSrvc, $modal) {
//todo: find a better way to expose services to template
this.gameSrvc = gameSrvc;
this.commoditySrvc = commoditySrvc;
this.citySrvc = citySrvc;
this.accountSrvc = accountSrvc;
this.tutorialOptions = tutorialSrvc.options;
this.$modal = $modal;
this.$scope = $scope;
if (!citySrvc.currentCity) {
commoditySrvc.setCitySpecialty();
citySrvc.getRandomCity();
commoditySrvc.updatePrices();
}
//todo: figure out why this ctrl gets called twice on page load
if (gameSrvc.initialLoad) {
this.showModal('start');
gameSrvc.initialLoad = false;
}
};
gameCtrl.prototype.submitScore = function() {
this.showModal('gameOver', this.accountSrvc.netWorth);
this.gameSrvc.gameOver();
};
gameCtrl.prototype.goToCity = function(city) {
this.citySrvc.setCurrentCity(city);
this.commoditySrvc.updatePrices();
this.gameSrvc.reduceDaysLeft();
};
gameCtrl.prototype.buyItem = function(item, quantity) {
this.commoditySrvc.buyCommodity(item, quantity);
};
gameCtrl.prototype.sellItem = function(item) {
this.commoditySrvc.sellCommodity(item);
};
gameCtrl.prototype.setMarketHoverItem = function(item) {
this.marketHoverItem = item.name;
};
gameCtrl.prototype.resetMarketHoverItem = function() {
this.marketHoverItem = '';
};
gameCtrl.prototype.isCurrentCity = function(city) {
return city.name === this.citySrvc.currentCity.name;
};
gameCtrl.prototype.getPotentialProfit = function(item) {
var expectedProfit = 'unknown';
if (item.averageSellPrice) {
expectedProfit = ((item.averageSellPrice - item.currentPrice) * item.maxQuantityPurchasable) / 100;
}
return expectedProfit;
};
gameCtrl.prototype.openMenu = function() {
this.showModal('gameMenu');
};
gameCtrl.prototype.showModal = function(type, score) {
var templateUrl, self = this;
switch (type) {
case 'start':
templateUrl = 'components/game/gameModalStart.tmpl.html';
break;
case 'gameMenu':
templateUrl = 'components/game/gameModalGameMenu.tmpl.html';
break;
case 'gameOver':
templateUrl = 'components/game/gameModalGameOver.tmpl.html';
break;
}
var modalInstance = this.$modal.open({
templateUrl: templateUrl,
controller: 'gameModalInstanceCtrl',
size: 'sm',
resolve: {
type: function() {
return type;
},
score: function() {
return score;
}
}
});
modalInstance.result.then(function(action) {
switch (action) {
case 'startTutorial':
self.$scope.startTutorial();
break;
case 'resetGame':
self.gameSrvc.gameOver(true);
break;
}
}, function() {
});
};
return gameCtrl;
}); |
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var index = require('./routes/index');
// Example route
// var user = require('./routes/user');
// below added by tommy
var login = require('./routes/login');
var messages = require('./routes/messages');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// Add routes here
app.get('/', index.view);
// Example route
// app.get('/users', user.list);
//below added by tommy
app.get('/login', login.view);
app.get('/messages', messages.view);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
import _jsx from "@babel/runtime/helpers/builtin/jsx";
import React from 'react';
import EditMediaDialog from '../../containers/EditMediaDialog';
import LoginDialog from '../../containers/LoginDialog';
import PreviewMediaDialog from '../../containers/PreviewMediaDialog';
var _ref =
/*#__PURE__*/
_jsx("div", {
className: "Dialogs"
}, void 0, _jsx(EditMediaDialog, {}), _jsx(LoginDialog, {}), _jsx(PreviewMediaDialog, {}));
var Dialogs = function Dialogs() {
return _ref;
};
export default Dialogs;
//# sourceMappingURL=index.js.map
|
import {
addClass,
removeClass,
EVENTS,
on,
off,
getViewportSize,
getClosest,
getParents
} from '../../utils/domUtils'
import {nodeListToArray} from '../../utils/arrayUtils'
function ScrollSpy (element, target = 'body', options = {}) {
this.el = element
this.opts = Object.assign({}, ScrollSpy.DEFAULTS, options)
this.opts.target = target
if (target === 'body') {
this.scrollElement = window
} else {
this.scrollElement = document.querySelector(`[id=${target}]`)
}
this.selector = 'li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
if (this.scrollElement) {
this.refresh()
this.process()
}
}
ScrollSpy.DEFAULTS = {
offset: 10,
callback: (ele) => 0
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
let list = nodeListToArray(this.el.querySelectorAll(this.selector))
const isWindow = this.scrollElement === window
list
.map(ele => {
const href = ele.getAttribute('href')
if (/^#./.test(href)) {
const doc = document.documentElement
const rootEl = isWindow ? document : this.scrollElement
const hrefEl = rootEl.querySelector(`[id='${href.slice(1)}']`)
const windowScrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
const offset = isWindow ? hrefEl.getBoundingClientRect().top + windowScrollTop : hrefEl.offsetTop + this.scrollElement.scrollTop
return [offset, href]
} else {
return null
}
})
.filter(item => item)
.sort((a, b) => a[0] - b[0])
.forEach(item => {
this.offsets.push(item[0])
this.targets.push(item[1])
})
// console.log(this.offsets, this.targets)
}
ScrollSpy.prototype.process = function () {
const isWindow = this.scrollElement === window
const scrollTop = (isWindow ? window.pageYOffset : this.scrollElement.scrollTop) + this.opts.offset
const scrollHeight = this.getScrollHeight()
const scrollElementHeight = isWindow ? getViewportSize().height : this.scrollElement.getBoundingClientRect().height
const maxScroll = this.opts.offset + scrollHeight - scrollElementHeight
const offsets = this.offsets
const targets = this.targets
const activeTarget = this.activeTarget
let i
if (this.scrollHeight !== scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget !== (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget !== targets[i] &&
scrollTop >= offsets[i] &&
(offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) &&
this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
const selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
const activeCallback = this.opts.callback
let active = nodeListToArray(this.el.querySelectorAll(selector))
active.forEach(ele => {
getParents(ele, 'li')
.forEach(item => {
addClass(item, 'active')
activeCallback(item)
})
if (getParents(ele, '.dropdown-menu').length) {
addClass(getClosest(ele, 'li.dropdown'), 'active')
}
})
}
ScrollSpy.prototype.clear = function () {
let list = nodeListToArray(this.el.querySelectorAll(this.selector))
list.forEach(ele => {
getParents(ele, '.active', this.opts.target).forEach(item => {
removeClass(item, 'active')
})
})
}
const INSTANCE = '_uiv_scrollspy_instance'
const events = [EVENTS.RESIZE, EVENTS.SCROLL]
const bind = (el, binding) => {
// console.log('bind')
unbind(el)
}
const inserted = (el, binding) => {
// console.log('inserted')
const scrollSpy = new ScrollSpy(el, binding.arg, binding.value)
if (scrollSpy.scrollElement) {
scrollSpy.handler = () => {
scrollSpy.process()
}
events.forEach(event => {
on(scrollSpy.scrollElement, event, scrollSpy.handler)
})
}
el[INSTANCE] = scrollSpy
}
const unbind = (el) => {
// console.log('unbind')
let instance = el[INSTANCE]
if (instance && instance.scrollElement) {
events.forEach(event => {
off(instance.scrollElement, event, instance.handler)
})
delete el[INSTANCE]
}
}
const update = (el, binding) => {
// console.log('update')
const isArgUpdated = binding.arg !== binding.oldArg
const isValueUpdated = binding.value !== binding.oldValue
if (isArgUpdated || isValueUpdated) {
bind(el, binding)
inserted(el, binding)
}
}
export default {bind, unbind, update, inserted}
|
import { red } from "./colors.js";
export default `body { background: url("${
new URL("./file.png" + __resourceQuery, import.meta.url).href
}"); color: ${red}; }`;
|
angular.module('app').directive('ngReallyClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
var message = attrs.ngReallyMessage;
if (message && confirm(message)) {
scope.$apply(attrs.ngReallyClick);
}
});
}
}
}]); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.